text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: catching sql related errors with try--catch in java (to log the errors) I am using log4j for logging messages in a java desktop application (working on Eclipse to create this app).
One part of the work is to do bulk insertion of csv (comma separated values) data into sql server database using JDBC.
I want to catch any error during the bulk inserts, and log the details of specific record for which the error occurred, and then resume the work of bulk insertion.
The relevant code which does the bulk insertion is given below, how do I code the exception handling to do what I desire? One more question- currently the stack trace is printed onto console, I want to log this into log file (using Log4j)... How do I do this?
public void insertdata(String filename)
{
String path = System.getProperty("user.dir");
String createString = "BULK INSERT Assignors FROM '" + path + "\\" +filename+ ".txt' WITH (FIELDTERMINATOR = ',')";
System.out.println(" Just before try block...");
try
{
// Load the SQLServerDriver class, build the
// connection string, and get a connection
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://ARVIND-PC\\SQLEXPRESS;" +
"database=test01;" +
"integratedSecurity=true;";
Connection con = DriverManager.getConnection(connectionUrl);
System.out.println("Connected.");
// Create and execute an SQL statement that returns some data.
String SQL = "BULK INSERT dbo.Assignor FROM '" + path + "\\" +filename+ ".txt' WITH (FIELDTERMINATOR = ',')";
Statement stmt = con.createStatement();
//ResultSet rs = stmt.executeQuery(SQL);
Integer no_exec;
no_exec=stmt.executeUpdate(SQL);
// Iterate through the data in the result set and display it.
//while (rs.next())
//{
// //System.out.println(rs.getString(1) + " " + rs.getString(2));
// System.out.println(" Going through data");
//}
System.out.println("Number of rows updated by the query=" + no_exec);
}
catch(Exception e)
{
System.out.println(e.getMessage());
e.printStackTrace();
System.exit(0);
}
}
A: Did you read Short Introduction to log4j? You need a log instance, and from there the rest is cake.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555297",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to link progress change event to progress bar I have windows form application that run a a class method by BackgroundWorker.
I would like to add the windows form a progress bar to show the progress.
in the class method I have a foreach loop so I would like each loop to send the form event
with the current percentage.
this is what i do :
public partial class Form1 : Form
{
Parsser inst;
public Form1()
{
InitializeComponent();
inst = new Parsser();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
}
private void button2_Click(object sender, EventArgs e)
{
if (this.textBox1 != null & this.textBox2 != null)
{
if (backgroundWorker1.IsBusy != true)
{
// Start the asynchronous operation.
backgroundWorker1.RunWorkerAsync();
}
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
inst.init(this.textBox1.Text, this.textBox2.Text);
inst.ParseTheFile();
System.Windows.Forms.MessageBox.Show("Parsing finish successfully");
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage;
}
}
}
`
and in the class i do this-
public Parsser()
{
bgReports = new BackgroundWorker();
bgReports.WorkerReportsProgress = true;
}
public void ParseTheFile()
{
Lines = File.ReadAllLines(FilePath);
this.size = Lines.Length;
foreach (string line in Lines)
{
bgReports.ReportProgress(allreadtchecked/size);
from some reason it dont work any idea?
A: Pass reference of BackgroundWorker to Parsser and then using that reference call ReportProgrss method
BackgroundWorker worker;
public Parsser(BackgroundWorker bg)
{
worker = bg;
}
public void ParseTheFile()
{
Lines = File.ReadAllLines(FilePath);
this.size = Lines.Length;
foreach (string line in Lines)
{
worker.ReportProgress(allreadtchecked/size);
A: You are creating a duplicate BackgroundWorkder instance in the Parsser class constructor. Try below
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
inst.init(this.textBox1.Text, this.textBox2.Text);
inst.ParseTheFile(backgroundWorker1);
System.Windows.Forms.MessageBox.Show("Parsing finish successfully");
}
In the Parsser Class.
public Parsser()
{
//Don't initialize backgroundworker here.
}
public ParseTheFile(BackgroundWorker bgWorker)
{
bgReports = bgWorker;
.....
}
A: Pass a lambda or method to your worker method:
in form:
public void Run()
{
myParse.DoWork(a => UpdateProgressBar(a.Progress));
}
private void UpdateProgressBar(int progress) { ... }
in Parser:
public void Parse(Action<ProgressArgs> onProgress)
{
// do your job
// invoke onProgress whenever needed
onProgress(current / total * 100);
}
A: You need to set your background worker to do work via the DoWorkEventHandler. Also, it looks like each half of your partial class is using its own BackgroundWorker. You need to use the same reference. You have bgreports and backgroundWorker1.
backgroundWorker1.DoWork += MyMethod;
// ......
private void MyMethod(object sender, DoWorkEventArgs e)
{
}
Also, why are you testing your textboxes for null? Are you trying to test their text string contents for null? if so, I would use String.IsNullOrEmpty.
I think a better design here would be for your "Parsser" (please fix spelling and identify what type / purpose this class is for Opertional code) to define its own events that your consumer class would subscribe to. A parser shouldn't be responsible for running itself asynchronously. A consumer should have the choice of running something synchronously or asynchronusly. In either of those cases, custom progression events can be defined and subscribed (again, optionally).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555298",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Blackberry-ListField with images from URL (XML DATA) I want to display the images which are in my XML in a ListField.I have parsed the data but not able to display that data in listfield.i have created one bean class which includes setter and getter of my data.
if(tempList.item(j).getNodeName().equalsIgnoreCase("bsub")){
tempNode = tempList.item(j);
tempNode2 = ((NodeList)tempNode.getChildNodes()).item(0);
bean.setsubTitle(tempNode2.getNodeValue().trim());
bean.getsubTitle();
System.out.println("Node Value or subtitle" + bean.getsubTitle().toString());
}
if(tempList.item(j).getNodeName().equalsIgnoreCase("bimage")){
tempNode = tempList.item(j);
tempNode2 = ((NodeList)tempNode.getChildNodes()).item(0);
bean.setImageurl(tempNode2.getNodeValue().trim());
bean.getimageurl();
System.out.println("Node Value or bimg" + bean.getimageurl().toString());
}
then i have created one TableRowManager.then i added my bitmap and label in that Manager as above.
enter code here
{
TableRowManager row = new TableRowManager();
BitmapField bitmap = new BitmapField(bean.getImage());
row.add(bitmap);
LabelField label = new LabelField(bean.getTitle());
row.add(label);
label.setFont(myFont1);
bitmap.setFont(myFont);
I am getting the blank screen while running my app.
Any suggestion will be appreciated.
A: looks difficult to understand the problem with the sample code provided. Try to give the complete code. also, visit this link which demonstrates the blackberry web bitmap field. blackberry-webbitmapfield which downloads image from server and renders on screen.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: android : i want use my custom font with WebViewb i want use my custom font with WebViewb
my html file loaded in webView but still without font
my font has Unicode characters
i work on android 2.2
mWebView.loadUrl("file:///android_asset/P_007.html");
my css:
<STYLE type="text/css">
@font-face {
font-family: AQF_P007_HA;
src: url("AQF_P007_HA.TTF");
}
body {
font-family: AQF_P007_HA;
font-style:normal;
font-weight: normal;
color: black;
font-size: medium;
mso-font-charset: 0
}
</STYLE>
A: A solution is document here: How to use custom font with WebView
is this similar to what you tried to use in your html file?
With the url relative to your assets folder in this case?
@font-face {
font-family: 'AQF_P001_HA';
src: url('AQF_P001_HA.TTF');
}
body {font-family: 'AQF_P001_HA';}
A: my problem was MyFont.TTF but it must be MyFont.ttf
ttf is different from TTF in linux/android.
:-)
android : html loaded without font
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555302",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: select next 2 digits starts with XXX but not XXX I'm trying to find about text and width value(so: 50%). To select 50% with regex I have to add width=" inside the regex. So, width="\d{2}% will select width="50% but I need to select only 50% in the first one.
In the second one, I have to select(find) only about text not <td>about.
<tr>
<td width="50%">about</td>
*
*Select the width value with percentage(search with "width" word but not select "width").
*Select only "about" string
A: Well you will find out that using regular expressions to parse HTML is near impossible.
But the basic reg exps would be:
var reWidth = /width="(\d{1,3}%)"/i;
var reCellText = /<td[^>]?>([^<]*)/i;
[EDIT]
Guessing by your comment below, you do not understand capture groups.
var str = '<td width="25%">';
var myMatch = str.match(reWidth);
if(myMatch){
alert( myMatch[1] );
}
A: I think you are looking for look behinds, but unfortunately Javascript does not support look behinds.
This would look like
(?<=width=")\d+
and would match only the digits.
I think you should explain more what you want to achieve (why you want to do this) to get an appropriate answer. I am not sure if regex is the solution here.
A: one shot for your two requirements. tested with grep:
kent$ echo '<td width="50%">about</td>'|grep -oP '(?<=width=")\d+%|(?<=>)[^<>]*(?=<)'
50%
about
(?<=width=")\d+% ->%number after width="
| ->or
(?<=>)[^<>]*(?=<) -> anything(besides < and >) between > and <
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to create a function to save outputs to a text file? I am supposed to create a program that given a file with a .vcf extension, read its data and print out a formatted contact sheet. Provided that i was able to do so, how would i be able to save the output to a text file whose name or path is provided by the user?? Just a beginner trying to figure out how to code.Any help would be appreciated.
A: Take a look at this C file I/O tutorial
Basically one way is to combine fopen and fprintf. Basic jist, open a file, write to it, close it.
A: Here is an example, I wrote you a function. (Your job to include the right includes, header, etc)
void save (char * filename)
{
FILE *output = fopen (filename, "w");
fprintf (output, "This is a test message");
fclose(output);
}
I hope I'm not doing this wrong as this is my first stack overflow answer. But test out this function in your environment of choice as
save("outfile.txt");
And thats generally the 'jist' of how it works on C. You fopen the file for writing (hence the "w", there are plenty of resources online that will show you your options), you fprintf the message to the output file. and then you close it.
hope that helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Method or object constructor not found in f# I have been trying to learn f# over the past few weeks and am having a little trouble with certain aspects. I am trying to use it with XNA and am writing a very simple game.
I have a simple player class that implements DrawableGameComponent and then overrides its methods Draw, Update and LoadContent.
type Player (game:Game) =
inherit DrawableGameComponent(game)
let game = game
let mutable position = new Vector2( float32(0), float32(0) )
let mutable direction = 1
let mutable speed = -0.1
let mutable sprite:Texture2D = null
override this.LoadContent() =
sprite <- game.Content.Load<Texture2D>("Sprite")
override this.Update gt=
if direction = -1 && this.Coliding then
this.Bounce
this.Jumping
base.Update(gt)
override this.Draw gt=
let spriteBatch = new SpriteBatch(game.GraphicsDevice)
spriteBatch.Begin()
spriteBatch.Draw(sprite, position, Color.White)
spriteBatch.End()
base.Draw(gt)
and so on....
The main Game class then makes a new player object etc.
module Game=
type XnaGame() as this =
inherit Game()
do this.Content.RootDirectory <- "XnaGameContent"
let graphicsDeviceManager = new GraphicsDeviceManager(this)
let mutable player:Player = new Player(this)
let mutable spriteBatch : SpriteBatch = null
let mutable x = 0.f
let mutable y = 0.f
let mutable dx = 4.f
let mutable dy = 4.f
override game.Initialize() =
graphicsDeviceManager.GraphicsProfile <- GraphicsProfile.HiDef
graphicsDeviceManager.PreferredBackBufferWidth <- 640
graphicsDeviceManager.PreferredBackBufferHeight <- 480
graphicsDeviceManager.ApplyChanges()
spriteBatch <- new SpriteBatch(game.GraphicsDevice)
base.Initialize()
override game.LoadContent() =
player.LoadContent () //PROBLEM IS HERE!!!
this.Components.Add(player)
override game.Update gameTime =
player.Update gameTime
override game.Draw gameTime =
game.GraphicsDevice.Clear(Color.CornflowerBlue)
player.Draw gameTime
The compiler reports an error saying "Method or object constructor LoadContent not found"
I find this odd as both Draw and Update work ok and are found by intellisense but not LoadContent!
It is probably just a very silly error I have made but if anyone spots the problem I would be much obliged!
Thanks
A: DrawableGameComponent.LoadContent is protected - so you don't have access to call it from your XnaGame class.
It's not clear to me what's meant to end up calling it, but apparently you shouldn't be calling it directly yourself.
A: The error definitely sounds confusing. You're overriding the LoadContent member in the definition of your Player type, but (as Jon pointed out) the member is protected. F# does not allow you to make the member more visible, so even your definition is still protected (you cannot normally define protected members in F#, so that's why the error message is poor).
You can solve the problem by adding additional member that calls LoadContent from inside the Player:
override this.LoadContent() =
sprite <- game.Content.Load<Texture2D>("Sprite")
member this.LoadContentPublic() =
this.LoadContent()
...then the LoadContent member will still be protected (inaccessible from the outside), but the new LoadContentPublic member will be public (this is default for member in F#) and you should be able to call it from your XnaGame.
However, as Jon pointed out - maybe you shouldn't be calling the method yourself because the XNA runtime will call it automatically when it needs to.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555316",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why to pass mutex as a parameter to a function being called by a thread? At some places I have seen people creating a thread pool and creating threads and executing a function with those threads. While calling that function boost::mutex is passed by reference. Why it is done so? I believe you can have a mutex declared in the called function itself or can be declared a class member or global. Can anyone please explain?
e.g.
myclass::processData()
{
boost::threadpool::pool pool(2);
boost::mutex mutex;
for (int i =0; data<maxData; ++data)
pool.schedule(boost::bind(&myClass::getData, boost_cref(*this), boost::ref(mutex)));
}
Then,
myClass::getData(boost::mutex& mutex)
{
boost::scoped_lock(mutex) // Why can't we have class member variable mutex or
//local mutex here
//Do somethign Here
}
A: Mutex's are non-copyable objects, and while they can be members of a class, it would greatly complicate a parent class's copy-ability. Thus one preferred method, should a number of class instances need to share the same data, would be to create the mutex as a static data-member. Otherwise if the mutex only needed to be locked within an instance of the class itself, you could create a pointer to a mutex as a non-static data-member, and then each copy of the class would have it's own dynamically allocated mutex (and remain copyable if that is a requirement).
In the code example above, what's basically taking place is there is a global mutex being passed into the thread pool by reference. That enables all the threads sharing the same memory locations to create an exclusive lock on that memory using the exact same mutex, but without the overhead of having to manage the non-copyable aspect of the mutex itself. The mutex in this code example could have also been a static data-member of class myClass rather than a global mutex that is passed in by reference, the assumption being that each thread would need to lock some memory that is globally accessible from each thread.
The problem with a local mutex is that it's only a locally accessible version of the mutex ... therefore when a thread locks the mutex in order to share some globally accessible data, the data itself is not protected, since every other thread will have it's own local mutex that can be locked and unlocked. It defeats the whole point of mutual exclusion.
A:
I believe you can have a mutex declared in the called function itself or can be declared a class member or global. Can anyone please explain?
creating a new mutex at the entry protects nothing.
if you were considering declaring a static (or global) mutex to protect non-static members, then you may as well write the program as a single threaded program (ok, there are some corner cases). a static lock would block all threads but one (assuming contest); it is equivalent to "a maximum of one thread may operate in this method's body at one time". declaring a static mutex to protect static data is fine. as David Rodriguez - dribeas worded it succinctly in another answer's comments: "The mutex should be at the level of the data that is being protected".
you can declare a member variable per instance, which would take the generalized form:
class t_object {
public:
...
bool getData(t_data& outData) {
t_lock_scope lock(this->d_lock);
...
outData.set(someValue);
return true;
}
private:
t_lock d_lock;
};
that approach is fine, and in some cases ideal. it makes sense in most cases when you are building out a system where instances intend to abstract locking mechanics and errors from their clients. one downside is that it can require more acquisitions, and it typically requires more complex locking mechanisms (e.g. reentrant). by more acquisitions: the client may know that an instance is used in only one thread: why lock at all in that case? as well, a bunch of small threadsafe methods will introduce a lot of overhead. with locking, you want to get in and out of the protected zones asap (without introducing many acquisitions), so the critical sections are often larger operations than is typical.
if the public interface requires this lock as an argument (as seen in your example), it's a signal that your design may be simplified by privatizing locking (making the object function in a thread safe manner, rather than passing the lock as an externally held resource).
using an external (or bound or associated) lock, you can potentially reduce acquisitions (or total time locked). this approach also allows you to add locking to an instance after the fact. it also allows the client to configure how the lock operates. the client can use fewer locks by sharing them (among a set of instances). even a simple example of composition can illustrate this (supporting both models):
class t_composition {
public:
...
private:
t_lock d_lock; // << name and data can share this lock
t_string d_name;
t_data d_data;
};
considering the complexity of some multithreaded systems, pushing the responsibility of proper locking onto the client can be a very bad idea.
both models (bound and as member variable) can be used effectively. which is better in a given scenario varies by problem.
A: Using local mutex is wrong: thread pool may invoke several function instances, and they should work with the same mutex. Class member is OK. Passing mutex to the function makes it more generic and readable. Caller may decide which mutex to pass: class member or anything else.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555321",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Using the latest value from IObservable I've got three IObservable of types Foo, Bar and Baz. In addition, there is a method defined as:
void DoWork(Foo foo);
The IObservable are defined elsewhere as Subject and OnNext is called from time to time.
Whenever new data is available (defined by some Where queries), I want to call the DoWork method with the latest Foo value. If no Foo values were generated the method should not be called.
What is the easiest way to do that?
To be more specific, see the following example. I'd like to call DoWork when bar or baz change, with the latest foo (f.id == 1):
void Wire(IObservable<Foo> foo, IObservable<Bar> bar, IObservable<Baz> baz)
{
foo.Where(f => f.Id == 1)
.Subscribe(f => DoWork(f));
}
A: This works for me:
var ubar = bar.Select(x => Unit.Default);
var ubaz = baz.Select(x => Unit.Default);
ubar.Merge(ubaz)
.CombineLatest(foo.Where(f => f.Id == 1), (u, f) => f)
.Subscribe(f => DoWork(f));
A: You can use the Do extension method on the Observable class to do this:
IObservable<Foo> filteredList = foos.Where(...);
// Invoke DoWork on each instance of Foo.
filteredList.Do(DoWork);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555325",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: PC Lint Warning 537: Repeated include file How to deal with this warning from PC Lint?
I have in several files the #include <GenericTypeDefs.h>. PC Lint shows me the message Warning 537: Repeated include file 'filepath\filename.h' If I delete this declaration I cannot compile.
I would like to suppress this warning if possible.
You can see the same reported here.
This is my code, for which my compiler emits warnings:
checksum.h
#ifndef CHECKSUM_H
#define CHECKSUM_H
#include <GenericTypeDefs.h>
BOOL isCheckSumCorrect(const UINT8 *dataPointer, UINT8 len, UINT8 checkSumByte);
#ifdef __cplusplus
extern "C" {
#endif
cryptography.h
#ifndef CRYPTOGRAPHY_H
#define CRYPTOGRAPHY_H
#include <GenericTypeDefs.h>
UINT8 encrypt(UINT8 c);
UINT8 decrypt(UINT8 c);
#ifdef __cplusplus
extern "C" {
#endif
crc8.h
#ifndef CRC_H
#define CRC_H
#include <GenericTypeDefs.h>
UINT8 generateCRC(const UINT8 *ptr, UINT8 Len);
BOOL isCRCValid(const UINT8 *ptr, UINT8 Len, UINT8 CRCChar);
#ifdef __cplusplus
extern "C" {
#endif
Obviously, I didn't repeat #include <GenericTypeDefs.h> on checksum.c, cryptography.c and crc8.c
A: Just ignore it
If you have include guards, this is a spurious warning and can (should) be ignored. We use include guards because allowing a file to be included multiple times is good practice, enabling more flexible code, prevents human errors, and avoids having order significance in your #include statements. If you want to know why this is the case, read on.
Multiple includes aren't a problem because you have include guards.
Since these .h files are all pretty related, I'm guessing that you include all three in the same file somewhere, perhaps main.c:
#include "checksum.h"
#include "cryptography.h"
#include "crc8.h"
main () { /* Do Stuff */ }
This will be expanded (minus the comments, of course) to:
// CHECKSUM_H is not defined, so the preprocessor inserts:
#include <GenericTypeDefs.h>
BOOL isCheckSumCorrect(const UINT8 *dataPointer, UINT8 len, UINT8 checkSumByte);
// CRYPTOGRAPHY_H is not defined, so the preprocessor inserts:
#include <GenericTypeDefs.h>
UINT8 encrypt(UINT8 c);
UINT8 decrypt(UINT8 c);
// CRC_H is not defined, so the preprocessor inserts:
#include <GenericTypeDefs.h>
UINT8 generateCRC(const UINT8 *ptr, UINT8 Len);
BOOL isCRCValid(const UINT8 *ptr, UINT8 Len, UINT8 CRCChar);
main () { /* Do Stuff */ }
So yes, #include <GenericTypeDefs.h> does appear multiple times at some point in the preprocessor step. Ostensibly, the file looks something like:
#ifndef GENERIC_TYPE_DEFS_H
#define GENERIC_TYPE_DEFS_H
#define UINT8 unsigned char
#ifdef __cplusplus
extern "C" {
#endif
so, after more preprocessing, our previously expanded bit (minus the comments) becomes:
// GENERIC_TYPE_DEFS_H is not defined, so the preprocessor inserts:
#define UINT8 unsigned char
BOOL isCheckSumCorrect(const UINT8 *dataPointer, UINT8 len, UINT8 checkSumByte);
// GENERIC_TYPE_DEFS_H IS defined, so the preprocessor inserts nothing.
UINT8 encrypt(UINT8 c);
UINT8 decrypt(UINT8 c);
// GENERIC_TYPE_DEFS_H IS defined, so the preprocessor inserts nothing.
UINT8 generateCRC(const UINT8 *ptr, UINT8 Len);
BOOL isCRCValid(const UINT8 *ptr, UINT8 Len, UINT8 CRCChar);
main () { /* Do Stuff */ }
Further preprocessing (not shown) copies the #define throughout the code.
You are guaranteed to have include guards if you heed other preprocessor and linter warnings
The linter will warn you (errors 451 and 967) if any .h files lack standard include guards. The compiler will warn about duplicate symbol definitions if the multiply-included GenericTypeDefs.h doesn't have include guards. If it does not, either create your own MyGenericTypeDefs.h or switch to the <stdint.h> header, which is part of the C standard and provides similar functionality as your GenericTypeDefs.h.
Warning: Bad workaround ahead
If you really insist on fixing the warning instead of ignoring it, you will have to remove #include <GenericTypeDefs.h> from each of the .h files and enter it once before one or more of these files are included, like this:
checksum.c
#include <GenericTypeDefs.h>
#include "checksum.h"
cryptography.c
#include <GenericTypeDefs.h>
#include "cryptography.h"
crc.c
#include <GenericTypeDefs.h>
#include "crc.h"
main.c
#include <GenericTypeDefs.h>
#include "checksum.h"
#include "cryptography.h"
#include "crc8.h"
main () { /* Do Stuff */ }
This is Not Recommended, as it results in more work for you and more chances for you to make mistakes (no offense, but you're only human and the preprocessor is not). Instead, just ask the preprocessor to do its job and use the include guards the way they were designed.
A: You can disable the warning just for that header with the option:
-efile(537,GenericTypeDefs.h)
and add that to your Lint config if you have one.
A: The article you linked to explains that it's more of a PCLint oddity, that should be a Note rather than a Warning.
Just ignore it / disable it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Jplayer Circle Player not playing mp3 file I've just downloaded the jplayer circle player and it works great. However when I change the link to my own mp3 file it stops working. Is there something else I should be doing? Thanks
var myCirclePlayer = new CirclePlayer("#jquery_jplayer_1",
{
/*These work fine when not commented out
m4a: "http://www.jplayer.org/audio/m4a/Miaow-07-Bubble.m4a",
oga: "http://www.jplayer.org/audio/ogg/Miaow-07-Bubble.ogg",*/
mp3: "myfolder/mytrack.mp3", //This doesn't work!
}
A: The response from @mgraph is basically "hacking core." If you update circle.player.js, you'll have to remember to re-apply the modification. All that's defined in that file is defaults. It would probably be better to modify the invocation code.
In the circle player demo file(currently demo-05.htm), find the options block, which currently looks like:
cssSelectorAncestor: "#cp_container_1",
swfPath: "js",
wmode: "window"
and add your own value for the supplied parameter, eg.
supplied: "mp3",
cssSelectorAncestor: "#cp_container_1",
swfPath: "js",
wmode: "window"
...which will then override the value set in circle.player.js
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555334",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How to convert a string from CP-1251 to UTF-8? I'm using mutagen to convert ID3 tags data from CP-1251/CP-1252 to UTF-8. In Linux there is no problem. But on Windows, calling SetValue() on a wx.TextCtrl produces the error:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position
0: ordinal not in range(128)
The original string (assumed to be CP-1251 encoded) that I'm pulling from mutagen is:
u'\xc1\xe5\xeb\xe0\xff \xff\xe1\xeb\xfb\xed\xff \xe3\xf0\xee\xec\xf3'
I've tried converting this to UTF-8:
dd = d.decode('utf-8')
...and even changing the default encoding from ASCII to UTF-8:
sys.setdefaultencoding('utf-8')
...But I get the same error.
A: Your string d is a Unicode string, not a UTF-8-encoded string! So you can't decode() it, you must encode() it to UTF-8 or whatever encoding you need.
>>> d = u'\xc1\xe5\xeb\xe0\xff \xff\xe1\xeb\xfb\xed\xff \xe3\xf0\xee\xec\xf3'
>>> d
u'\xc1\xe5\xeb\xe0\xff \xff\xe1\xeb\xfb\xed\xff \xe3\xf0\xee\xec\xf3'
>>> print d
Áåëàÿ ÿáëûíÿ ãðîìó
>>> a.encode("utf-8")
'\xc3\x81\xc3\xa5\xc3\xab\xc3\xa0\xc3\xbf \xc3\xbf\xc3\xa1\xc3\xab\xc3\xbb\xc3\xad\xc3\xbf \xc3\xa3\xc3\xb0\xc3\xae\xc3\xac\xc3\xb3'
(which is something you'd do at the very end of all processing when you need to save it as a UTF-8 encoded file, for example).
If your input is in a different encoding, it's the other way around:
>>> d = "Schoßhündchen" # native encoding: cp850
>>> d = "Schoßhündchen".decode("cp850") # decode from Windows codepage
>>> d # into a Unicode string (now work with this!)
u'Scho\xdfh\xfcndchen'
>>> print d # it displays correctly if your shell knows the glyphs
Schoßhündchen
>>> d.encode("utf-8") # before output, convert to UTF-8
'Scho\xc3\x9fh\xc3\xbcndchen'
A: If d is a correct Unicode string, then d.encode('utf-8') yields an encoded UTF-8 bytestring. Don't test it by printing, though, it might be that it just doesn't display properly because of the codepage shenanigans.
A: If you know for sure that you have cp1251 in your input, you can do
d.decode('cp1251').encode('utf8')
A: I'd rather add a comment to Александр Степаненко answer but my reputation doesn't yet allow it. I had similar problem of converting MP3 tags from CP-1251 to UTF-8 and the solution of encode/decode/encode worked for me. Except for I had to replace first encoding with "latin-1", which essentially converts Unicode string into byte sequence without real encoding:
print text.encode("latin-1").decode('cp1251').encode('utf8')
and for saving back using for example mutagen it doesn't need to be encoded:
audio["title"] = title.encode("latin-1").decode('cp1251')
A: I lost half of my day to find correct answer. So if you got some unicode string from external source windows-1251 encoded (from web site in my situation) you will see in Linux console something like this:
u'\u043a\u043e\u043c\u043d\u0430\u0442\u043d\u0430\u044f \u043a\u0432\u0430\u0440\u0442\u0438\u0440\u0430.....'
This is not correct unicode presentation of your data. So, Tim Pietzcker is right. You should encode() it first then decode() and then encode again to correct encoding.
So in my case this strange line was saved in "text" variable, and line:
print text.encode("cp1251").decode('cp1251').encode('utf8')
gave me:
"Своя 2-х комнатная квартира с отличным ремонтом...."
Yes, it makes me crazy too. But it works!
P.S. Saving to file you should do the same way.
some_file.write(text.encode("cp1251").decode('cp1251').encode('utf8'))
A: I provided some relevant info on encoding/decoding text in this response: https://stackoverflow.com/a/34662963/2957811
To add to that here, it's important to think of text in one of two possible states: 'encoded' and 'decoded'
'decoded' means it is in an internal representation by your interpreter/libraries that can be used for character manipulation (e.g. searches, case conversion, substring slicing, character counts, ...) or display (looking up a code point in a font and drawing the glyph), but cannot be passed in or out of the running process.
'encoded' means it is a byte stream that can be passed around as can any other data, but is not useful for manipulation or display.
If you've worked with serialized objects before, consider 'decoded' to be the useful object in memory and 'encoded' to be the serialized version.
'\xc1\xe5\xeb\xe0\xff \xff\xe1\xeb\xfb\xed\xff \xe3\xf0\xee\xec\xf3' is your encoded (or serialized) version, presumably encoded with cp1251. This encoding needs to be right because that's the 'language' used to serialize the characters and is needed to recreate the characters in memory.
You need to decode this from it's current encoding (cp1251) into python unicode characters, then re-encode it as a utf8 byte stream. The answerer that suggested d.decode('cp1251').encode('utf8') had this right, I am just hoping to help explain why that should work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555335",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
}
|
Q: Error when running Rails with Ruby 1.9.2 under RVM When I try to run a Rails application when using Ruby 1.9.2 under RVM, I get the following error:
/Users/purinkle/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/dependency.rb:247:in `to_specs': Could not find rails (>= 0) amongst [rake-0.9.2] (Gem::LoadError)
from /Users/purinkle/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/dependency.rb:256:in `to_spec'
from /Users/purinkle/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems.rb:1182:in `gem'
from /Users/purinkle/.rvm/rubies/ruby-1.9.2-p290/bin/rails:18:in `<main>'
If I try to run the same command while using Ruby 1.8.7, everything works fine.
Why would this happen?
A: I am a newbie, but I can say you are missing the installation of Rails related to Ruby 1.9.2.
To check :
rails --version
To try solving this, reinstall rails for Ruby 1.9.2:
gem install rails
A: I had this same issue and it was as simple as
gem install rails
then
bundle update
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555338",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why does this Facebook FQL query return empty? The following FQL query is returning empty. There's no reason for it not to, as its quite clearly documented as possible in the FQL Documentation itself.
SELECT eid, uid, rsvp_status FROM event_member WHERE (uid = me() OR uid IN(SELECT uid2 FROM friend WHERE uid1 = me())) LIMIT 10
This should return the first 10 rows of any events that I, or my friends have been invited to.
If I include a condition for a specific event's ID, then I get the result.
(I am using FB.Data.query() to perform the query, in conjunction with query.wait.)
Can anyone else replicate this issue, or know what I'm doing wrong?
A: hi this because of the fact that you have not taken the user_events and friends_events
You can take permission like this
<fb:login-button perms="friends_events,user_events" autologoutlink="true"></fb:login-button>
For Further You can read Manage Permissions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555341",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Jquery and CSS style If I want to add an CSS style for a field in a table that has the value that is equal to the current time or greater than the current time but it is less than the value of the next field, how can I do this using Jquery?
The sample of table looks like this:
-----------------------
field | current time
-----------------------
1 | 05:25
2 | 07:30
3 | 09:18
4 | 10:13
5 | 12:44
If the current time is 09:50 the field No.4 should have a different background color
(If the current time is 05:30 then the field No. 2 , ...)
Thanks for all suggestions.
A: assuming this is ordered...
1)you should have a function ( myFunc) that can compare times and return if left argument bigger or smaller then the right.
2)you should have a function that returns the 'now' time.
3)each time span should be wrap with class .time
then in jQuery : each time should be wrap with class .time
$(".time").each(function (){
if (myfunc ($(this).text(),now())=='bigger')
{
$(this).css('color','red');
return false;
}
});
A: Cobbled this together: http://jsfiddle.net/xVDnj/1/ -- It will assign a class "past" or "future" to each table cell depending on whether the given time is before or after the current time (on the same day).
$(document).ready(function() {
var cdate = new Date();
$('table tbody tr').each(function() {
var $tc = $(this).find('td').eq(1)
var tstr = $tc.text();
var thour = tstr.split(":")[0];
var tmin = tstr.split(":")[1];
var tdate = new Date();
tdate.setHours(thour,tmin);
if (tdate-cdate < 0) {
$tc.addClass('past');
} else {
$tc.addClass('future');
}
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Cycling through a hex colour spectrum I'm working on some code with Arduino, and I'm trying to get a strip of LEDs to cycle through the spectrum of colours in order. I have done this in the past by changing the red green and blue values independently, but the current LEDs I am working with take Hex values (for example, 0xFF0000). How I can do this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555353",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Hibernate - want to put delete and store in one "transaction", if pb occurs, all will be rollbacked I have a method which delete some items, and next insert some others items.
public void refresh() {
if (newitems != null) {
toto.clear();
for (totoDao p : newItems) {
toto.store(p);
}
}
newitems = null;
}
public void clear() {
final Session session = this.getHibernateUtil().getSession();
int n = session.createQuery(DELETE).executeUpdate();
session.clear();
session.flush();
}
public void store(TotoDao object) {
final Session session = this.getHibernateUtil().getSession();
session.saveOrUpdate(object);
session.flush();
}
For the moment I have one flush in clear() method and other one in store() method.
I want to add all of theses stuffs in one "transaction", if somethings appears, a application restart just after the toto.clear(), for example, i want that transaction rollback all the block.
So what are the best solution for perfomances and persistances ?
Thx !
A: session = sessionFactory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
... your add/store/delete/....
tx.commit();
}catch(Throwable(or other type of Exception you like) ex){
tx.rollback();
}
A: Just enclose these two method calls inside a unique transaction.
Flushing doesn't have anything to do with transactions. It just means "really execute all the SQL statements needed to persist the modifications made in the session". But the commit will only be done at the end of the transaction.
Flushing the session manually is almost always unnecessary. Let Hibernate do it when it has to.
Also, note that a DAO is supposed to be a service object allowing to query and update entities. It's not supposed to be a persistent entity.
Read http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#transactions and http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#objectstate-flushing
A: Spring has good solutions for transaction management.
On this page you'll find the way to configure spring/hibernate with XML files.
If you need some explanation, just ask and i'll try to help you asap.
Some exemple:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<aop:config>
<aop:pointcut id="pointcutId" expression="execution(* com.stackoverflow.service.FooService.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcutId"/>
</aop:config>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<!-- all methods starting with 'get' are read-only -->
<tx:method name="get*" read-only="true"/>
<!-- other methods (By example Rollback for NullPointerException)-->
<tx:method name="*" read-only="false" rollback-for="NullPointerException"/>
</tx:attributes>
</tx:advice>
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
...
</beans>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555358",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Cocos2d with GameCenter, OpenGLError I get this error in a particular situation and i dont know how to solve it.
After i invite someone to play with me, i touch the 'uninvite' button then i hit cancell and it calls this method:
// The user has cancelled matchmaking
- (void)matchmakerViewControllerWasCancelled:(GKMatchmakerViewController *)viewController {
[self.presentingViewController dismissModalViewControllerAnimated:YES];
NSLog(@"User cancelled the invitation.");
}
And after that happens i get this error:
OpenGL error 0x0506 in -[EAGLView swapBuffers]
Over and over again.
If i dont invite someone and just hit cancel, it calls that method again but it gets back to the game screen correctly. Have anyone seen something like this before? Do i have to stop the invitation before i dismiss the view or something?
A: I had similar issue and fixed it. It was hard to find a solution.
I had to change my init method in AppDelegate like this:
- (void) applicationDidFinishLaunching:(UIApplication*)application
{
CC_DIRECTOR_INIT();
// Obtain the shared director in order to...
CCDirector *director = [CCDirector sharedDirector];
// Sets landscape mode
[director setDeviceOrientation:kCCDeviceOrientationLandscapeLeft];
if( ! [director enableRetinaDisplay:YES] )
CCLOG(@"Retina Display Not supported");
[[CCDirector sharedDirector] runWithScene: [MainMenuLayer scene]];
[[CCDirector sharedDirector] setDisplayFPS:NO];
[self authenticateLocalPlayer];
}
Dismiss:
-(void)achievementViewControllerDidFinish:(GKAchievementViewController *)viewController{
[tempController dismissModalViewControllerAnimated:YES];
[tempController.view removeFromSuperview];
[[CCDirector sharedDirector] resume];
}
A: Not sure if this will help but maybe pause the CCDirector before displaying the Game Center UI and resume it when all the Game Center actions are done.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: yiic stop to work on dev version (1.1.9) I recently started a new project, however i normally use the dev version (trunk) to get the most recently version of framework, but now in this version (v1.1.9-dev) after created a new app using webapp command when I tried to use any yiic command nothing happened.
I try to run migrate command and yiic shell but the prompt just returns without any error or any message.
have you ever had this problem too?
How can'I debug this problem?
Thanks advance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555364",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How insert value in text field of custom cell from pickerview when user click on textfield? I have a table view in which i am adding a custom cell. In custom cell i have a text field. In that text field i want to insert value from picker view. Picker view will open when user click on text field. I have following code for that purpose but i am not getting value in text field. code..
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *) indexPath
{
NSString *identifier = [NSString stringWithFormat:@"%d-%d",indexPath.section,indexPath.row];
cell_object = (Custom_cell2 *)[tableView dequeueReusableCellWithIdentifier:identifier];
if(cell_object == nil)
{
[[NSBundle mainBundle] loadNibNamed:@"Custom_cell2" owner:self options:nil];
}
// Configure the cell...
cell_object.selectionStyle=UITableViewCellSelectionStyleNone;
cell_object.txt_name.backgroundColor=[UIColor clearColor];
cell_object.txt_name.userInteractionEnabled=NO;
NSArray *array = [array_from objectAtIndex:indexPath.section];
NSString *cellValue = [array objectAtIndex:indexPath.row];
cell_object.txt_name.text = [NSString stringWithFormat:@"%@",cellValue];
cell_object.txt_time.backgroundColor=[UIColor whiteColor];
cell_object.txt_time.textColor=[UIColor blackColor];
//cell_object.txt_time.userInteractionEnabled=NO;
//cell_object.txt_time.text =@"";
return cell_object;
}
above code for custom cell.
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
myPicker.hidden=FALSE;
UIToolbar *tool = [[UIToolbar alloc] initWithFrame:CGRectMake(0,0, 320, 44)]; //better code with variables to support view rotation
tool.tintColor=[UIColor blackColor];
UIBarButtonItem *space=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil] autorelease];
UIBarButtonItem *doneButton =[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(done)] autorelease];
//using default text field delegate method here, here you could call
//myTextField.resignFirstResponder to dismiss the views
[tool setItems:[NSArray arrayWithObjects: space,doneButton,nil] animated:NO];
cell_object.txt_time.inputAccessoryView = tool;
[myPicker addSubview:tool];
//you can -release your doneButton and myToolbar if you like
[[[UIApplication sharedApplication] keyWindow] addSubview:myPicker];
return NO;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent: (NSInteger)component
{
if (pickerView == myPicker)
{
[cell_object.txt_time setText:[NSString stringWithFormat:@"%@",[array_time objectAtIndex: [pickerView selectedRowInComponent:0]]]];
[table_routine reloadData];
}
}
when i click on cell_object.txt_time then appear a picker view but it is not inserting value from picker in text filed.
what is mistake in this code?
Thanks in advance...
A: [pickerView selectRow:1 inComponent:0 animated:NO];
textField.text= [array_name objectAtIndex:[pickerView selectedRowInComponent:0]];
you can try this code for adding text from pickerview selection...
A: Verify that you have set and also add following line to your code when you are going to add the myPicker as subView.
myPicker.delegate = self;
A: Actually You cant set value of UITableViewCell textlLabel like this. for Any change in tableView you have to reload it or reload the Cell individually.
Solution is create an array and store your pickerView Value in that array.
then in cellForRowAtIndexPath:
cell_object.txt_time setText: [array objectAtIndex: indexPath];
try this..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555367",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: File path gwt app hosted mode I'd like to know how to get the path of a file to access to it in hosted mode. My app is reading some files using a servlet. Originally the files are located under the folder "war" (e.g. "war/data/file1.txt"), in development everything works well, the servlet reads the file and sends the data to the client. However, I'm having issues when I deploy the app in Tomcat.
I copied the content of the folder war, and put it in a folder under the "webapps" directory (in Tomcat). In development mode, I access to the data file using the path "data/file1.txt" but this doesn't work in hosted mode because I found out that when using that path, the servlet looks for the file in the "bin" folder of Tomcat installation directory, not in the folder of the application.
So, I'd like to know how to programatically find the correct path to access the file and avoid problems when deploying the application to Tomcat or any other server.
A: Use ServletContext.getRealPath(). You can get instance of ServletContext from Servlet.getServletConfig().getServletContext().
The reason why you saw it working in development mode, but not in Tomcat is that the path normally is relative to working directory. Probably you could also make Tomcat work if you started it when being in your web application directory or modifying Tomcat shortcut to have working directory in you web app. But you definitely shouldn't rely on it.
A: Take a look at GWT.isProdMode(). It returns true if running in production mode, and false if in development mode. You can choose the apropriate path by placing it in an if statement
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555369",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: No hs_err_pid.log file created and core dumped from jvm on Solaris Problem description
After a while of running my java server application I am experiencing strange behaviour of Oracle Java virtual machine on Solaris. Normally, when there is a crash of jvm hs_err_pid.log file gets created (location is determined by -XX:ErrorFile jvm paramter as explained here: How can I suppress the creation of the hs_err_pid file?
But in my case, the file was not created, the only thing left was the core core dump file.
Using pstack and pflags standard Solaris tools I was able to gather more information about the crash (which are included below) from the core file.
Tried solutions
*
*Tried to find all hs_err_pid.log files across the file system, but nothing could be found (even outside the application working directory). i.e.:
find / -name "hs_err_pid*"
*I tried to find jvm bugs related to jvm, but I couldn't find nothing interesting similar to this case.
*The problem looks somewhat similar to: Java VM: reproducable SIGSEGV on both 1.6.0_17 and 1.6.0_18, how to report? but still I cannot confirm this since the hs_err_pid.log file is missing and of course the OS platform is different.
*(EDIT) As suggested in one of the answers to Tool for analyzing java core dump question, I have extracted heap dump from the core file using jmap and analysed it with with Eclipse MAT. I have found a leak (elements added to HashMap, never to be cleansed, at the time of core dump 1,4 M elements). This however does not explain why hs_err_pid.log file was not generated, nor jvm crashing.
*(EDIT2) As suggested by Darryl Miles, -Xmx limitations has been checked (Test contained code that indefinitely added objects to a LinkedList):
*
*java -Xmx1444m Test results with java.lang.OutOfMemoryError: Java heap space,
*java -Xmx2048m Test results with java.lang.OutOfMemoryError: Java heap space,
*java -Xmx3600m Test results with core dump.
The question
Has anyone experienced similar problem with jvm and how to proceed in such cases to find what actually happened (i.e. in what case the core gets dumped from the jvm and no hs_err_pid.log file is created)?
Any tip or pointer to resolving this would be very helpful.
Extracted flags
# pflags core
...
/2139095: flags = DETACH
sigmask = 0xfffffeff,0x0000ffff cursig = SIGSEGV
Extracted stack
# pstack core
...
----------------- lwp# 2139095 / thread# 2139095 --------------------
fb208c3e ???????? (f25daee0, f25daec8, 74233960, 776e3caa, 74233998, 776e64f0)
fb20308d ???????? (0, 1, f25db030, f25daee0, f25daec8, 7423399c)
fb20308d ???????? (0, 0, 50, f25da798, f25daec8, f25daec8)
fb20308d ???????? (0, 0, 50, f25da798, 8561cbb8, f25da988)
fb203403 ???????? (f25da988, 74233a48, 787edef5, 74233a74, 787ee8a0, 0)
fb20308d ???????? (0, f25da988, 74233a78, 76e2facf, 74233aa0, 76e78f70)
fb203569 ???????? (f25da9b0, 8b5b400, 8975278, 1f80, fecd6000, 1)
fb200347 ???????? (74233af0, 74233d48, a, 76e2fae0, fb208f60, 74233c58)
fe6f4b0b __1cJJavaCallsLcall_helper6FpnJJavaValue_pnMmethodHandle_pnRJavaCallArguments_pnGThread__v_ (74233d44, 74233bc8, 74233c54, 8b5b400) + 1a3
fe6f4db3 __1cCosUos_exception_wrapper6FpFpnJJavaValue_pnMmethodHandle_pnRJavaCallArguments_pnGThread__v2468_v_ (fe6f4968, 74233d44, 74233bc8, 74233c54, 8b5b4
00) + 27
fe6f4deb __1cJJavaCallsEcall6FpnJJavaValue_nMmethodHandle_pnRJavaCallArguments_pnGThread__v_ (74233d44, 8975278, 74233c54, 8b5b400) + 2f
fe76826d __1cJJavaCallsMcall_virtual6FpnJJavaValue_nLKlassHandle_nMsymbolHandle_4pnRJavaCallArguments_pnGThread__v_ (74233d44, 897526c, fed2d464, fed2d6d0, 7
4233c54, 8b5b400) + c1
fe76f4fa __1cJJavaCallsMcall_virtual6FpnJJavaValue_nGHandle_nLKlassHandle_nMsymbolHandle_5pnGThread__v_ (74233d44, 8975268, 897526c, fed2d464, fed2d6d0, 8b5b
400) + 7e
fe7805f6 __1cMthread_entry6FpnKJavaThread_pnGThread__v_ (8b5b400, 8b5b400) + d2
fe77cbe4 __1cKJavaThreadRthread_main_inner6M_v_ (8b5b400) + 4c
fe77cb8e __1cKJavaThreadDrun6M_v_ (8b5b400) + 182
feadbd59 java_start (8b5b400) + f9
feed59a9 _thr_setup (745c5200) + 4e
feed5c90 _lwp_start (745c5200, 0, 0, 74233ff8, feed5c90, 745c5200)
System information:
# uname -a
SunOS xxxx 5.10 Generic_137138-09 i86pc i386 i86pc
# java -version
java version "1.6.0_11"
Java(TM) SE Runtime Environment (build 1.6.0_11-b03)
Java HotSpot(TM) Server VM (build 11.0-b16, mixed mode)
# ulimit -a
time(seconds) unlimited
file(blocks) unlimited
data(kbytes) unlimited
stack(kbytes) 10240
coredump(blocks) unlimited
nofiles(descriptors) 256
memory(kbytes) unlimited
Used jvm args:
java -Xms1024M -Xmx2048M -verbose:gc -Xloggc:logs/gc.log -server com.example.MyApplication
Please comment if you find some information missing, I'll try to add them.
A: 6.0_11 is quite old and I have no recent experiences with, really recommend upgrade there...
However, no crash dump may occur with stackoverflow in the native code, i.e. calling some native function (like write of FileOutputStream, sockets use the same impl) with very low stack. So, even though the JVM attempts to write the file, there is not enough stack and the writing code also crashes.
The second stackoverflow just bails out the process.
I did have similar case (no file created) on a production system and it was not pretty to trace it, yet the above explains the reason.
A: As per my comments above. I beleive this issue to be running out of usable heap in 32bit address space by having set too high a -Xmx value. This forced the Kernel to police the limit (by denying requests for new memory) before the JVM could police it (by using controlled OutOfMemoryException mechanism). Unfortunately I do not know the specifics of Intel Solaris to know what is to be expected from that platform.
But as a general rule for Windows a maximum -Xmx might be 1800M and then reduce it by 16M per additional application thread you create. Since each thread needs stack space (both native and Java stack) as well as other per-thread accounting matters like Thread Local Storage etc... The result of this calculation should give you an approximation of the realistic usable heap space of a Java VM on any 32bit bit process whose operating system uses a 2G/2G split (User/Kernel).
It is possible with WinXP and above to use /3G switch on the kernel to get higher split (3G/1G user/kernel) and Linux has a /proc/<pid>/map file to allow you to see exactly how the process address space is laid out of a given process (if you were running this application you could watch over time as the [heap] grows to meet the shared file mappings used for .text/.rodata/.data/etc... from DSOs this results in the kernel denying requests to grow the heap.
This problem goes away for 64bit because there is so much more address space to use and you will run out of physical and virtual (swap) memory before the heap meets the other mappings.
I believe 'truss' on Solaris would have show up a brk/sbrk system-call that returned an error code, shortly before the core dump. Parts of standard native libraries are coded to never check the return code from requests for new memory and as a result crashes can be expected.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How to select a div within a form and alter it's style I have a formpanel and a div inside it with the class 'x-panel-body'
How can I select that div and alter it's style? I've tried using ext.select and setStyle but it tells me that the html has no setstyle method.
Thanks
edit: to add, that is the only form on the page. It also has html id: myform
A: You have several possibilities:
*
*Using a CSS rule should probably be your first choice
#myform .x-panel-body {
background: red;
}
*Apply a bodyStyle config property when creating your panel. See API docs. (Or alternatively bodyCls). Note that this is a config property that is only evaluated once during the construction phase of the panel component and cannot be used to change the style at runtime.
In case you need to change the style programmatically after the component has been created:
*use setStyle but remember that this is a method of Ext.Element and not Ext.Component (or Ext.form.Panel)! You have to call it on the body member of your panel object.
// fetch the body element of your form object which is of
// type Ext.Element and apply the style
myForm.body.setStyle([property], [value]);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555381",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Very strange jQuery selector bug in Firefox 3.6.x Alright, I spent a lot of time turning a non-AJAX shopping cart checkout into an AJAX checkout.
I did this by separating out the various sections into tabs using jQuery UI tabs. I then use AJAX to post changes on one tab and selectively refresh other tabs. The selective refresh simply grabs the result of the post and uses a jQuery selector to grab only the relevant div from the response.
In this particular case, a tab with shipping information is posting and refreshing a tab with a list of shipping methods.
This works flawlessly excepting one browser: Firefox 3.6.x (Mac and Windows)
In Firefox 3, the selector pulls back a truncated result from the result of the POST, which effectively removes crucial buttons and prevents the user from proceeding.
Here is the full html response, with formatting:
http://pastebin.com/aVF6yUba
EDIT: The above is apparently not 100% consistent with the actual output. Here is the truly RAW output:
http://pastebin.com/ChAT1vLf
Here is the relevant line of JavaScript:
jQuery("#shipping-method-section").html(output.html());
Here is what every other browser pulls back with that line:
<!--- shipping method section --->
<h2>Select a shipping method:</h2>
<ul id="shipping-methods">
<li><span><label><input name="shipmethod" value="FedEx+Priority+Overnight" class="shopp shipmethod" type="radio"> FedEx Priority Overnight — <strong>$30.68</strong> <span>Estimated Delivery: September 28, 2011</span> </label> </span> </li>
<li> <span> <label><input name="shipmethod" value="FedEx+Standard+Overnight" class="shopp shipmethod" type="radio"> FedEx Standard Overnight — <strong>$26.46</strong> <span>Estimated Delivery: September 28, 2011</span> </label> </span> </li>
<li> <span> <label><input name="shipmethod" value="FedEx+2Day" class="shopp shipmethod" type="radio"> FedEx 2Day — <strong>$19.10</strong> <span>Estimated Delivery: September 29, 2011</span> </label> </span> </li>
<li> <span> <label><input name="shipmethod" value="FedEx+Express+Saver" class="shopp shipmethod" type="radio"> FedEx Express Saver — <strong>$18.79</strong> <span>Estimated Delivery: September 30, 2011</span> </label> </span> </li>
<li> <span> <label><input name="shipmethod" value="FedEx+Home+Delivery" class="shopp shipmethod" checked="checked" type="radio"> FedEx Home Delivery — <strong>$13.52</strong> <span>Estimated Delivery: September 27, 2011</span> </label> </span> </li>
</ul>
<hr>
<div class="tab-back-button">
<input class="tab-back-button" value="Shipping Address" type="button">
</div>
<input value="Payment Method" name="shipping-method-section-button" class="shipping-method-section-button" type="button">
Here is what Firefox 3.6.x pulls back:
<h2>Select a shipping method:</h2>
<ul id="shipping-methods">
<li><span><label><input name="shipmethod" value="FedEx+Priority+Overnight" class="shopp shipmethod" type="radio"> FedEx Priority Overnight — <strong>$30.68</strong> <span>Estimated Delivery: September 28, 2011</span> </label> </span> </li>
<li> <span> <label><input name="shipmethod" value="FedEx+Standard+Overnight" class="shopp shipmethod" type="radio"> FedEx Standard Overnight — <strong>$26.46</strong> <span>Estimated Delivery: September 28, 2011</span> </label> </span> </li>
<li> <span> <label><input name="shipmethod" value="FedEx+2Day" class="shopp shipmethod" type="radio"> FedEx 2Day — <strong>$19.10</strong> <span>Estimated Delivery: September 29, 2011</span> </label> </span> </li>
<li> <span> <label><input name="shipmethod" value="FedEx+Express+Saver" class="shopp shipmethod" type="radio"> FedEx Express Saver — <strong>$18.79</strong> <span>Estimated Delivery: September 30, 2011</span> </label> </span> </li>
<li> <span> <label><input name="shipmethod" value="FedEx+Home+Delivery" class="shopp shipmethod" checked="checked" type="radio"> FedEx Home Delivery — <strong>$13.52</strong> <span>Estimated Delivery: September 27, 2011</span> </label> </span> </li>
</ul>
I can find no rhyme or reason to this.
As a temporary work around, I wrote some JavaScript that detects Firefox 3 and forces a full refresh to get them to the next tab.
Anyone have any ideas on how to make this work properly?
Thanks!
Clif
EDIT. Here is the full JavaScript:
jQuery.post( url, data, function(output) {
if(error_check_passed(output, "FedEx"))
{
jQuery("#shipping-section").css({ 'opacity' : 1.0 });
update_cart_summary(output);
hide_errors();
output = jQuery("#shipping-method-section", jQuery(output));
jQuery("#shipping-method-section").html(output.html());
allowTabChange = true;
jQuery("#checkout-tabs").tabs('select', 1);
}
else
{
jQuery("#shipping-section").fadeTo('fast', 1.0);
show_errors(output, "FedEx");
}
});
A: It has to do with the two form tags. I copied your pastebin and cut it down to the section that shipping-method-section is contained in, and it worked fine in ff3.6. I then added the sction that that section is in, which is a form section. It then broke. If you change the outer form section to anything other than that, it works fine. That's also why the inner form tag is being stripped out if you browse the DOM with firebug (in newer versions too). If you inspect your page in FF3.6 before a reload, when the buttons are showing correctly, I think you will find that the hr and all tags after it are outside the shipping-method-selection div
I realize the form section can't be changed, so I'm not sure what you could do to work around it. Nested forms aren't allowed, but I know a lot of people use them anyway with no problems.
--edit--
I looked at the site, and the <hr> and on is inside shipping-method-section. However, I took your whole pastebin and did this:
jQuery.post( 'testClifPost.html', function(output) {
var d = document.createElement('div');
d.innerHTML = output;
console.log(d);
}
In this output, <hr> is outside of shipping-method-section. This seems to say that it's not jQuery, but that firefox 3.6 parses things differently when javascript asks for it to parse something that when it loads it into the browser.
A: It may be that FF doesn't like the <hr> tag, and is breaking out there. Have you tried it with <hr /> instead of just <hr> ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I generate the database from .edmx file in Entity Framework? I have had to suddenly switch to working on Code First Entity Framework 4.1. I started off not knowing anything about this framework but in the last 8 hrs I am now much more comfortable having read blogs and articles.
This blog in particular is one of the best blogs I have seen so far on the topic but the steps given do not match with my experience. In particular, I need more focus on the 3rd and 4th steps ('Create the Model' and 'Swap to DbContext Code Generation', respectively). I am unable to generate the database from my defined EntitySet. I am getting the SQL and I can execute but I'm getting the following error:
Could not locate entry in sysdatabases for "MyBD" database . No entry found with that name. Make sure that the name is entered correctly entity framework.
If I execute the SQL again, I get the same error following the names of tables that already exist in database.
If refresh the DataConnection in Server Explorer, there are no such tables created as I defined in Entity Framework.
How can I get rid of this error and successfully generate the tables in my .edmx?
Also I am unable to find the option on right-click in Solution Explorer to "Generate Database" from selected class file that has the context class inherited from the DBContext object. I installed the Entity framework 4.1 from Microsoft, so it should appear there... How can I get the Generate Database option?
A: If you are creating the database from the model, you need to select the empty model first. Here are the other steps to create db:
*
*Select new connection
*Set Server name: if you installed it, just type . to select default. You can also try (local)
*Set new database name
*Copy DDL script to your SQL server management studio's query screen
*Run the script to create your db
After running the script, you will have the initial table. Config file will have connection string named as container name.
Now, when you want to switch to code generation similar to example with TT files, you can right click and add code generation. It will create partial class for the entity model and one file for dbcontext. Similar to this:
using System;
using System.Collections.Generic;
public partial class Contact
{
public int Id { get; set; }
public string Name { get; set; }
}
Context will have only one table.
public partial class PersonModelContainer : DbContext
{
public PersonModelContainer()
: base("name=PersonModelContainer")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<Contact> Contacts { get; set; }
}
You dont need TT model. You can add these files directly. You need one context class inheriting from DbContext and one partial class file for each type of entity. If you make a change to model, EF will detect that. You need to define Db initializer. For the sample demo on that webpage, you can add initializer to another method. If it is a web project, you add this init function to Global.asax->application_Start for the initial development. You have different options for initializers. I use drop and create for initial development.
static void InitDbCheck()
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<PersonModelContainer>());
using (var db = new PersonModelContainer())
{
//accessing a record will trigger to check db.
int recordCount = db.Contacts.Count();
}
}
static void Main(string[] args)
{
using (var db = new PersonModelContainer())
{
// Save some data
db.Contacts.Add(new Contact { Name = "Bob" });
db.Contacts.Add(new Contact { Name = "Ted" });
db.Contacts.Add(new Contact { Name = "Jane" });
db.SaveChanges();
// Use LINQ to access data
var people = from p in db.Contacts
orderby p.Name
select p;
Console.WriteLine("All People:");
foreach (var person in people)
{
Console.WriteLine("- {0}", person.Name);
}
// Change someones name
db.Contacts.First().Name = "Janet";
db.SaveChanges();
}
}
A: Here's the definitive guide from MSDN on
How to: Generate a Database from a Conceptual Model (Entity Data Model Tools) [.edmx] file.
Copy/Pasting here just for the sake of completeness:
To generate a database from a conceptual model
1 - Add an .edmx file to your project.
For information about adding an .edmx file to a project, see How to:
Create a New .edmx File (Entity Data Model Tools) and How to: Add an
Existing .edmx File (Entity Data Model Tools).
2 - Build the conceptual model.
You can use the ADO.NET Entity Data Model Designer (Entity Designer)
to create entities and relationships or you can manually edit the
.edmx file to build a conceptual model. For more information, see
Implementing Advanced Entity Framework Features and CSDL, SSDL, and
MSL Specifications.
NoteNote When you build the conceptual model, warnings about unmapped
entities and associations may appear in the Error List. You can ignore
these warnings because the Create Database Wizard will add the storage
model and mapping information (see step 3).
3 - Right-click an empty space on the Entity Designer surface and select
Generate Database from Model.
The Choose Your Data Connection Dialog Box of the Generate Database
Wizard (Entity Data Model Tools) is displayed.
4 - Click the New Connection button or select an existing connection
button from the drop-down list to provide a database connection.
You must supply a database connection so that column types for the
target database can be determined based on property types in your
model, and so that connection string information can be added to your
application. Note that supplying connection information does not
initiate data definition language (DDL) generation.
5 - Click Next.
The Create Database Wizard generates data definition language for
creating a database. The generated DDL is displayed in the Summary and
Settings Dialog Box (Generate Database Wizard).
6 - Click Finish.
Upon completion, the Create Database Wizard does the following:
Generates the store schema definition language (SSDL) and mapping
specification language (MSL) that correspond to the provided
conceptual schema definition language (CSDL). The .edmx file is
updated with the generated SSDL and MSL. Note that the wizard
overwrites existing SSDL and MSL.
Saves the generated DDL in the location specified in the Save DDL As
text box. For more information about the generated DDL, see Database
Generation Rules (Generate Database Wizard).
NoteNote If a storage model is already defined when you run the Create
Database Wizard, the generated DDL will contain a DROP TABLE statement
and DROP CONSTRAINT statement for each EntitySet and each
AssociationSet (respectively) that are inferred from the storage
model.
Adds connection string information to your App.config or Web.config
file.
It is important to note that the Create Database Wizard does not
execute the generated DDL. To create the database schema that
corresponds to your conceptual model, you must execute the generated
DDL independently (for example, execute the DDL in SQL Server
Management Studio).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: Template Template C++ Function How do I write a template function that operates on a arbitrary container of a arbitrary type? For example how do I generalize this dummy function
template <typename Element>
void print_size(const std::vector<Element> & a)
{
cout << a.size() << endl;
}
to
template <template<typename> class Container, typename Element>
void print_size(const Container<Element> & a)
{
cout << a.size() << endl;
}
Here is a typical usage
std::vector<std::string> f;
print_size(f)
This give error
tests/t_distances.cpp:110:12: error: no matching function for call to ‘print(std::vector<std::basic_string<char> >&)’. I'm guessing I must tell the compiler something more specific about what types that are allowed.
What is this variant of template-use called and how do I fix it?
A: I know that the question was asked long time ago , but i had same problem , and the solution is that you need to write
template <template <typename,typename> class Container, typename element, typename Allocator>
void print_size(Container<element, Allocator> & a)
{
std::cout << a.size() << std::endl;
}
because the vector has two template parameters
A: Why ever use something like
template <template<typename> class Container, typename Element>
void print_size(const Container<Element> & a)
{
cout << a.size() << endl;
}
? Use it in simpler way:
template<typename Container>
void print_size(const Container & a)
{
cout << a.size() << endl;
}
When calling print_size(f), you will call print_size with Container being vector<string>.
A: The problem is that the vector template takes two type arguments, and your template accepts only template arguments that accept a single argument. The simplest solution is lifting a bit of the type safety and just using Container as a type:
template <typename Container>
void print_size( Container const & c ) {
std::cout << c.size() << std::endl;
}
Possibly adding static checks (whatever the type Container is, it must have a value_type nested type that is Element...) The alternative would be to make the template template argument match the templates that are to be passed (including allocator for sequences, allocator and order predicate for associative containers)...
A: Is there a specific reason for you to use a template template? Why not just like this?
template <typename Container>
void print_size(Container const& a)
{
cout << a.size() << endl;
}
In general, template templates aren’t worth the trouble. In your particular case, there certainly is no use for them, and if you really need to access the member type, I suggest you bow to common practice and use a metafunction (typename Container::value_type in this case).
A: For these types of generic algorithms, I always prefer iterators, i.e.
template <typename IteratorType>
void print_size(IteratorType begin, IteratorType end) {
std::cout << std::distance(begin, end) << std::endl;
}
To call:
std::vector<std::string> f;
print_size(f.begin(), f.end());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555391",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: UserControl OnPropertyChanged issue I have OnPropertyChanged method in my UserControl class:
private static void OnColorChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
ColorPicker colorPicker = (ColorPicker)sender;
Color oldColor = (Color)e.OldValue;
Color newColor = (Color)e.NewValue;
colorPicker.Red = newColor.R;
colorPicker.Green = newColor.G;
colorPicker.Blue = newColor.B;
colorPicker._previousColors.Push(oldColor); //don't update if undo command executed
colorPicker.OnColorChanged(oldColor, newColor);
}
_previousColors is:
private Stack<Color> _previousColors = new Stack<Color>();
and i don't want update this stack if undo command executed:
private void UndoCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = _previousColors.Count > 1;
}
private void UndoCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
var color = _previousColors.Pop();
this.Color = color;
}
How can I realize this condition in OnColorChanged method?
A: Seems like you could have private bool (lets call it isUndoing) which gets set true at the begin of the undo execute and is reset to false at the end. In the OnColorChanged, look at the value of isUndoing and take appropriate action. Would this not work?
Also, I agree with Rachel, upvoting and Answer marking are your friends. Every time you give someone credit for good posts, people are that much more likely to help you in the future,
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555394",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to configurate mailto to rtl? In my html I am writting:
<a href="mailto:fromJavaSceript@gmail.com?body=%A0%F9%ED%0D%0A%F9%ED%A0%EE%F9%F4%E7%E4%A0%0D%0A%FA%2E%E6%0D%0A%EE%F1%F4%F8%A0%F4%E5%EC%E9%F1%E4">websitemail@gmail.co.il </a>
the new outlook window TEXT is opened the from the left to the right where I want it to be opened from the right to the left
A: You can add the unicode "mirror" character in front of the text. In html ‮ or url encoded %E2%80%AE
A: Unfortunately, it's not possible.
See this question: Is it possible to add an HTML link in the body of a MAILTO link
The answer there refers to RFC 2368, whose second section reads, in part:
The special hname "body" indicates that the associated hvalue is the
body of the message. The "body" hname should contain the content for
the first text/plain body part of the message. The mailto URL is
primarily intended for generation of short text messages that are
actually the content of automatic processing (such as "subscribe"
messages for mailing lists), not general MIME bodies.
So, according to the standard, the body has to be in plain text. That means that you're at the mercy of the client software: if it conforms to the standard, it will treat your body text like plain text, and behave in the default way.
I tried a lot of things on my local system (Outlook 2003), including changing my Normal.dot to be RTL, and configuring Outlook to use MS Word for new messages, and changing Outlook options to do everything RTL, but nothing worked, even as a workaround.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How do I block php debug output from being committed in svn? I would like to block debug functions var_dump, print_r, etc... from being commited to the repo so that QA can go over things and not report bugs like "There is a huge block of text on all of the pages!!"
I have tried regex (not a great idea... presumably).
I have also tried token_get_all but for some reason, it returns T_STRING for each of the debug functions, which I guess would work, but it seems odd...
Is there a third better way?
A: Based on my new understanding, this is what I have:
$debug_functions = array('print_r', 'var_dump', 'var_export');
foreach($files as $file=>$ext){
$file_contents = file_get_contents($file);
//break the content into tokens
$tokens = token_get_all($file_contents);
foreach($tokens as $t){
//if the token id is an int (sometimes it isn't)
if(is_int($t[0])){
//if it matches our debug stuff...
if($t[0] == T_STRING && (in_array($t[1], $debug_functions) || preg_match('/xdebug_.*?/', $t[1]))){
echo 'Debug output '. $t[1] . ' found on line '. $t[2] . PHP_EOL;
}
}
}
}
A: Maybe not the answer you are looking for, but I highly recommend you remove all the print_r, var_dump etc from your code.
*
*Keep your code clean all the time
*Those tags are for debugging purposes only.
*when you are committing, you should ensure everything works as expected. Altering commit code or having different code on your machine than the live machine ensures of bugs and issues.
So remove those tags, don't keep them in your code, not even on a local machine.
A: You could write a sniff PHP_CodeSniffer and make SVN execute it as a pre-commit hook. This would reject committing such code.
A: Alternative way is not using var_dump and related functions at all.
Coding better practices includes
*
*Unit testing with PHPUnit and
*Using a remote debugger, for example Xdebug
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555402",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: The ConnectionSettingsTask for WP7 is not getting resolved by the compiler I am coding for WP7 Mango ( Windows Phone 7.1 profile). The compiler is not able to resolve the ConnectionSettingsTask class.
According to MSDN it is in
Namespace: Microsoft.Phone.Tasks
Assembly: Microsoft.Phone (in Microsoft.Phone.dll)
I am not able to see this class using ObjectBrowser either.
Any help on this is appreciated, Thanks.
A: The ConnectionSettingsTask class is available in Microsoft.Phone.dll of Windows Phone SDK 7.1 (RC) and NOT available in Windows Phone SDK 7.1 (Beta2).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to leave browser opened even after selenium ruby script finishes I am using a ruby script with selenium web-driver, for automating an web page login. The issue is after script finishes it closes the browser also. I want to keep the browser opened even after the script finishes. Is there any way by which I can keep browser open after the test do something else with the browser window?
I am doing like this.
if browser == "Firefox"
driver = Selenium::WebDriver.for :firefox
end
if stack == "example.com"
driver.get "http://www.example.com/tests/
end
element = driver.find_element :name => "email"
element.clear
element.send_keys username
element = driver.find_element :name => "password"
element.clear
element.send_keys password
element = driver.find_element :name => "commit"
element.submit
===================================================
A: If you run the test with debugging enabled and drop a debugger line at the end it should leave the browser open. Look at the ruby-debug gem. It also might be worth checking out this Railscast about Pry.
A: Here some snippet in Python:
Putting this at the end of your script, will leave the browser windows open and ends the script when it is closed manually (requires some imports at the beginning):
import time
import sys
...
while 1:
time.sleep(5)
try:
b = browser.find_by_tag("body")
except:
sys.exit()
A: Watir's until function will hold the script until a condition returns true. Set the timeout to infinity and check for all the windows to be closed.
Watir::Wait.until(timeout: Float::INFINITY) {@browser.windows.length == 0}
@browser.close
Put this at the end of your script and close all the tabs manually to exit.
A: I've never actually tried using selenium-webdriver in a standalone script like that, but I have run into the same problem using selenium-webdriver within the context of capybara/cucumber.
Looking at the source code for capybara, I found this hook which explicitly closes the browser after your script is finished. If you're not using selenium-webdriver with capybara, then this might not be helpful, but it was helpful for me...
gems/capybara-1.1.1/lib/capybara/selenium/driver.rb registers an at_exit hook, which then calls quit on the browser object:
require 'selenium-webdriver'
class Capybara::Selenium::Driver < Capybara::Driver::Base
...
def browser
unless @browser
@browser = Selenium::WebDriver.for(options[:browser], options.reject { |key,val| SPECIAL_OPTIONS.include?(key) })
main = Process.pid
at_exit do
# Store the exit status of the test run since it goes away after calling the at_exit proc...
@exit_status = $!.status if $!.is_a?(SystemExit)
quit if Process.pid == main
exit @exit_status if @exit_status # Force exit with stored status
end
end
@browser
end
You should be able to monkey-patch the quit method so that it does nothing, like so:
Selenium::WebDriver::Driver.class_eval do
def quit
#STDOUT.puts "#{self.class}#quit: no-op"
end
end
Note: If you are using Selenium::WebDriver.for :chrome and chromedriver
-- which you aren't, but other people might be -- I noticed that it also kills the chromedriver process, and as soon as that "service" process is killed, the Chrome browser process that was connected to it also quits.
So I had to also prevent that service process from stopping, like so:
Selenium::WebDriver::Chrome::Service.class_eval do
def stop
#STDOUT.puts "#{self.class}#stop: no-op"
end
end
There was one other problem I ran into, which probably won't affect you, unless you're using this driver with cucumber... Even after I got it to leave the browser open, it would be left open on the "about:blank" page. It looks like this is triggered by this hook:
gems/capybara-1.1.1/lib/capybara/cucumber.rb:
After do
Capybara.reset_sessions!
end
Which calls gems/capybara-1.1.1/lib/capybara/session.rb:70:in `reset!'"
Which calls gems/capybara-1.1.1/lib/capybara/selenium/driver.rb:80:in `reset!'":
def reset!
...
@browser.navigate.to('about:blank')
...
end
And I solved that with another monkey-patch:
Capybara::Selenium::Driver.class_eval do
def reset!
end
end
A: A quick hack that worked for me:
sleep(9000)
in your test gives you a fair amount of time to play around with the browser before the driver closes it.
A: This is the code that worked for me with Capybara
Capybara::Selenium::Driver.class_eval do
def quit
puts "Press RETURN to quit the browser"
$stdin.gets
@browser.quit
rescue Errno::ECONNREFUSED
# Browser must have already gone
end
end
It's a monkey patching of what I found in gems/capybara-1.1.2/lib/capybara/selenium/driver.rb
I just added the puts and the gets lines. Selenium::WebDriver::Driver was giving me a not found error probably because I'm getting selenium from within capybara.
This is useful to see what's the code that generated an error but there is a downside: the browser stops past the last page and displays a blank screen. I have to click the back button to get to the page with the error which might not always work. Does anybody know why the browser loads that empty page and save me the time to dig into the capybara code? Thanks!
A: This is largely what the other commenters have said already about overriding quit on the driver, but here's the simplified code I ended up using for a standalone Capybara script:
require 'capybara'
session = Capybara::Session.new(:selenium)
session.driver.class.class_eval { def quit; end }
session.visit('http://localhost:3000')
# ... other stuff
Assuming you have a web server running on localhost:3000, this will launch Firefox, navigate to this URL and leave the browser window open.
A: What test framework are you using?
Usually your test framework has some sort of setup and teardown methods that you can define which allows you to start the browser
@driver = Selenium::WebDriver.for :firefox
in the setup method, and destroy the browser
@driver.quit
in teardown.
Just put some logic around the teardown portion of your scripts to only destroy the browser when you want to.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555416",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: How to implement digital zoom with iphone device camera? In iPhone App,
I want to implement digital zooming in my iphone app while capturing photograph using iphone camera.
How can I do that ?
A: UIImagePickerController has a cameraViewTransform that you can use to scale the camera view when the user zooms. After the image has been captured, it is then up to you to crop and resize it according to the zoom setting.
To do that, you would create a new graphics context with the desired size and draw the image you got from the image picker into that context.
A: Once you have captured the image, I think you can do using the scaling and cropping images to the size you want.
But the clarity of the images may not be the same as original one.
- (UIImage *)image
{
if (cachedImage == nil) {
// HERE YOU CAN GIVE THE FRAME YOU WANT THE SIZE OF THE IMAGE TO BE.
CGRect imageFrame = CGRectMake(0, 0, 400, 300);
UIView *imageView = [[UIView alloc] initWithFrame:imageFrame];
[imageView setOpaque:YES];
[imageView setUserInteractionEnabled:NO];
[self renderInView:imageView withTheme:nil];
UIGraphicsBeginImageContext(imageView.bounds.size);
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextGetCTM(c);
CGContextScaleCTM(c, 1, -1);
CGContextTranslateCTM(c, 0, -imageView.bounds.size.height);
[imageView.layer renderInContext:c];
cachedImage = [UIGraphicsGetImageFromCurrentImageContext() retain];
// rescale image
UIImage* bigImage = UIGraphicsGetImageFromCurrentImageContext();
CGImageRef scaledImage = [self newCGImageFromImage:[bigImage CGImage] scaledToSize:CGSizeMake(100.0f, 75.0f)];
cachedImage = [[UIImage imageWithCGImage:scaledImage] retain];
CGImageRelease(scaledImage);
UIGraphicsEndImageContext();
[imageView release];
}
return cachedImage;
}
Hope this helps you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555417",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: the "|=" operator in c++ I have a question about "|=" in c++, how this operator works, for example:
bool result;
result |= callFunctionOne(sig);
result |= callFunctionTwo(sig);
result |= callFunctionThree(sig);
result |= callFunctionFour(sig);
and the function called above, will reutrn "true" if the paramater sig is processed in the function, otherwish, return "false";
the sig can be processed only in one function each time, how the "|=" works?
A: | is bitwise OR.
|= says take what is returned in one of your function and bitwise OR it with the result, then store it into result. It is the equivalent of doing something like:
result = result | callFunctionOne(sig);
Taking your code example:
bool result;
result |= callFunctionOne(sig);
result |= callFunctionTwo(sig);
result |= callFunctionThree(sig);
result |= callFunctionFour(sig);
and your logic of
will reutrn "true" if the paramater sig is processed in the function,
otherwish, return "false";
So that means that if you don't define result, it will be by default FALSE.
result = false;
callFunctionOne returns TRUE
result = result | callFunctionOne;
result equals TRUE.
result = false;
callFunctionOne returns FALSE
result = result | callFunctionOne
result equals FALSE.
While it may seem that this is a boolean OR, it still is using the bitwise OR which is essentially OR'ing the number 1 or 0.
So given that 1 is equal to TRUE and 0 is equal to FALSE, remember your truth tables:
p q p ∨ q
T T T
T F T
F T T
F F F
Now, since you call each function after another, that means the result of a previous function will ultimately determine the final result from callFunctionFour. In that, three-quarters of the time, it will be TRUE and one-quarter of the time, it will be FALSE.
A: a |= b is equivalent to a = a | b.
A: To put it simple, it will assign true to result if any of those functions return true, and false otherwise. But there is one problem - result must be initialized, otherwise this bit operation will be performed on random initial value and could return true even if all of the functions returns false.
The operator itself is called "bitwise inclusive or".
A: The | operator is bitwise OR (if you know the boolean logic, on a bool variable it acts as a boolean OR). If one or many calls return true, result will be true. If all calls are returning false, the result is false.
Each time, it's the equivalent of result = result | callFunctionXXX(sig);
Remark: in your sample code, the variable result is not initialized. It should be "bool result = false;"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Get information of element that called function with jQuery I was wondering how I'd go about finding with jQuery, the element id that called an onClick method? my code is:
JS
function getInfo(event)
{
console.log(event.target.id + " ... ");
}
HTML
<div class="menu-content" id="thisismyid">
This is some placeholder text.<br>
<a onClick="getInfo()" id="thisisthelinksid">Click on me</a>
</div>
<div class="menu-content" id="thisismysecondid">
This is some more placeholder text.<br>
<a onClick="getInfo()" id="thisistheotherlinksid">Click on me</a>
</div>
I can't put anything inside the parentheses of the function, because I want a function passed to it later, I just want to be able to tell which called this function.
I know this has been asked many times, and a lot of the questions have answers, but I have read through a lot of them and none have helped me.
Thanks guys
-EDIT-
In regards to the answers below at time of this edit, I cannot use the jQuery method like:
$("div.menu-content a").click(function() {
some content here..
});
because I need it to only be run on certain links being clicked, not all of them. Does that help clarify?
A: $("div.menu-content a").click(function() {
var $elemId = $(this).attr("id");
console.log($elemId + " .... ");
);
Is a much more "jQuery style" solution to do it.
A: Try:
function getInfo(event)
{
var id = $(event.target).attr('id');
console.log(id);
}
A: Don't use the onclick attributes, use event handlers instead.
$(function(){
$('a', 'div.menu-content').click(function(){
console.log(this.id+'...');
});
}):
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Using "path" and "asset" for non-template data When creating templates with Twig, it's easy to use the path and asset functions.
<a href="{{ path('my_route') }}"><img src="{{ asset('bundles/acmedemo/my_image.png') }}" /></a>
However, some of my data come from non-twig files or from database. What would be the right way to address these functions from there?
So far, I'm using regex replace (preg_replace_callback) for the path function. But isn't there a nicer way?
A: I am proud to present my first public mini-project, the StaticBundle. It pretty much lets you include any file in a bundle straight into a template.
Setup
EDIT The bundle can now be installed using composer, please see the instructions on readme.
Add the following to deps:
[KGStaticBundle]
git=git://github.com/kgilden/KGStaticBundle.git
target=bundles/KG/StaticBundle
Run bin/vendors install.
Register the namespace in app/autoload.php:
'KG' => __DIR__.'/../vendor/bundles',
Register the bundle in app/AppKernel.php:
new KG\StaticBundle\KGStaticBUndle(),
Basic usage
Suppose we have a file src/Acme/Bundle/DemoBundle/Static/hello.txt ready to be included in a template. We'd have to use a file function:
{# src/Acme/Bundle/DemoBundle/Resources/views/Demo/index.html.twig #}
{{ file('@AcmeDemoBundle/Static/hello.txt') }}
The logical name gets resolved into the actual path and a simple file_get_contents retrieves the data.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Can I write multiple messages to a database using log4j? Pretty new to all this so excuse any beginner mistakes.
I was wondering if I was able to get log4j to write multiple messages to the same db record in a single log write. example
log.debug("Message 1" , "Message 2");
or
log.debug("Message 1" , 7);
Can log4j only take a single message for writing?
Thanks
A: There exists a predefined appender for it (org.apache.log4j.jdbc.JDBCAppender), but it has limits, check the API.
As for the second part of your question, each call to Logger.debug/info/warn, etc., causes a LoggingEvent object to be created in log4j internals, which is a "unit of logging". Log4j does not append anything to this object later, just logs it and forgets it.
If you need to merge a complicated text and log it as one, you should use this technique, or better use log4j with slf4j, which can construct log strings with {} placeholders, sort of like C function printf.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555423",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I distinguish left/right/double click in the handler if $.live('click')? ....live('click', function(){
/*How do I distinguish left/right/double click*/
});
It seems event.button can be used to distinguish left and right click, but how to distinguish double click?
And I don't know if event.button is supported by all major browsers..
A: This seems to solve the left and right click issue:
$("#element").live('click', function(e) {
if( e.button == 0 ) {
// Left mouse button was clicked (non-IE)
}
});
For IE
$("#element").live('click', function(e) {
if( e.button == 1 ) {
// Left mouse button was clicked (IE only)
}
});
See the link for more details
jQuery live click binds
A: well there is a separate event handler for doubleclick.. The event is dblclick
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Most efficient algorithm for parsing nested blocks with escapes or delimiters I define a nested block as something with separate opening and closing characters. I.e. { and }, [ and ], etc. An algorithm must ignore opening and closing characters if they are enclosed in a delimiter (such as '{' or "{"), or explicitly escaped such as in a comment block.
This is not homework (I'm not a student) or idle speculation. My immediate goal is to alphabetically reorder function declarations in ActionScript code files to assist in debugging / comparing different versions. But the real question and more useful for other readers is the general algorithm as described above. In my case the plug-in parameters are just opening = {, closing = }, delimiter = ", escape = //..[end of line].
Please see the following for existing questions that explain why regular expressions are not an option for parsing arbitrarily deep nested expressions:
*
*Can regular expressions be used to match nested patterns?
*How can I parse nested blocks using Regex? [closed]
The obvious blunt solution is to chug through character-by-character and build a context stack and state variables ("inQuote", "inComment", etc). I've done this before. I'm just wondering if there is a more formal or efficient solution; or if this is irreducable.
A: Depending on what you want to do you can either go with your context stack solution or you can build expression trees from the statements. From what I'm reading it looks like the context stack is the easiest to use if you just want some simple parsing but if you require complicated expression handling or just multi level expression handling then you may want to consider an expression tree otherwise known as a parse tree (http://en.wikipedia.org/wiki/Parse_tree). In your case the tree will not get very complicated if done right. As I said though from what I read it shouldn't be complicated as long as you can get the entire function block and encapsulate that somehow and just sort by name.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555432",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Main Differences between android 1.x and 2.x Can't find the answer for the long time. Can someone help me to find differences?
A: Android API levels
Click on a version for a changelog.
A: There is no simple answer. Many things have been changed up and updated and added throughout all of the various different releases.
See here, for an overview of what happened with each release
Another good breakdown of it.
Current version spread.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Facebook Pay Dialog Not Calling Callback After Confirmation I have implemented a servlet in Java that handles the credits communications with Facebook (as per the API). I implemented the servlet to perform the same functionality as the example php code and following the guidelines in the API.
I send FB the id of the item and get a response with the method "payments_get_items". I respond correctly which creates a popup dialog asking for payment confirmation (with all the product data). When I click confirm, Facebook does not make another call to my servlet but instead tells me my app is not responding. I find this strange and have found no way to resolve this issue.
Below is the JSON i am sending back to FB when i am asked to perform "payments_get_items". image_URL is an actual URL which has works. Am i possibly missing something in my response?
{"content":[{"description":"test","image_url":image_URL,"item_id":"siPremiumShotgun","price":2,"product_url":image_URL,"title":"Premium Shotgun"}],"method":"payments_get_items"}
Many thanks
A: Ensure your SSL is a non-free version really authentic SSL cert.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Hook Rails Engine into global layout I'm currently writing a modular rails app where every functionality is inside a rails engine. I've set up my first engine and everything's working fine so far. now I'm wondering what is the best way to hook the engine into my global navigation that is currently rendered in app/views/layouts/application.html.haml, like this:
%nav#main-nav
%ul
%li
= link_to "Users", users_path, :class => "no-submenu settings"
%ul
%li ...
The closest thing I found was the HookListener of spree, which uses the deface gem. unfortunately deface only works with html/erb output since it parses the DOM with nokogiri, which isn't the best idea anyway.
A: for the record, i've solved it like this:
*
*move the base app to an engine/gem as well to make it easily require'able
*add a Navigation class
*register into this class from MyEngine
core/lib/navigation.rb:
class Navigation
@registered_blocks = {}
class << self
def register(name, &block)
@registered_blocks[name] ||= block
end
def bind(root)
@registered_blocks.each do |name, block|
block.call(root)
end
end
end
end
myext/lib/myext/engine.rb:
Navigation.register :myext do |root|
root.item :mylink, "My Link", "/"
end
config/navigation.rb (for simple-navigation):
navigation.items do |root|
Navigation.bind(root)
end
A: create a module in your app, which you'll include in every engine, e.g. MyAppModule
class CmsModule::Railtie < ...
include MyAppModule
end
then use the included hook to register your navigation etc with your application. you can encapsulate all your hooks etc within the MyAppModule, providing a consistent integration for all your engines.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555440",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Move an element to another parent after changing its ID I have HTML like this:
<span class="file-wrapper" id="fileSpan">
<input type="file" name="photo[]" id="photo" />
<span class="button">Click to choose photo</span>
</span>
I want to extract the input field from there, change its ID and put it in an other div.
How can I do that? If jQuery is needed that's okay, but if it can be without that would be great.
A: It's certainly easy in jQuery:
// jQuery 1.6+
$("#photo").prop("id", "newId").appendTo("#someOtherDiv");
// jQuery (all versions)
$("#photo").attr("id", "newId").appendTo("#someOtherDiv");
Working demo: http://jsfiddle.net/AndyE/a93Az/
If you want to do it in plain ol' JS, it's still fairly simple:
var photo = document.getElementById("photo");
photo.id = "newId";
document.getElementById("someOtherDiv").appendChild(photo);
Working demo: http://jsfiddle.net/AndyE/a93Az/1/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555442",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
}
|
Q: Extjs 4 MessageBox prompt mandatory Is there any way to make the input mandatory on a prompt messagebox in extjs 4, like add an allowBlank config to the textarea...
A: Ext.MessageBox unfortunately does not support controlling the close-behavior based on the return value of the login handler (at least in Ext 4.0.2a the return value is not evaluated at all).
As a workaround you can just re-open another MessageBox in your callback handler with the same (or updated) config.
Ext.Msg.prompt('Name', 'Please enter your name:', function(btn, text, cfg) {
if(btn == 'ok' && Ext.isEmpty(text)) {
var newMsg = '<span style="color:red">Please enter your name:</span>';
Ext.Msg.show(Ext.apply({}, { msg: newMsg }, cfg));
}
});
In some cases the user could experience a slight flickering. In my tests, however, it was not noticeable at all.
If the user has dragged the MessageBox to a different position it will recenter again.
A: By mandatory do you simply mean force the user to select one of the available buttons?
If so, you can use
'closable: false'
to prevent the user closing the box without clicking on a button.
A: I created custom function for set prompt input required with prompt window as argument
setPromptRequired: function(promptWin) {
const field = promptWin.down('textfield');
const button = promptWin.down('#ok');
button.disable();
field.on({
change: function(item, value) {
if(value && value.trim() !== '') {
button.enable();
} else {
button.disable();
}
}
});
promptWin.on({
beforehide: function(){
button.enable();
field.resumeEvent('change');
},
beforeclose: function(){
button.enable();
field.resumeEvent('change');
}
});
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Binary files in java I Know that binary files connot be read by text editors, thay can be read only by programs.
but when I create binary files using java(bytes), I can open files and read it ? why that happens?
In other words, I see a plain text rather than a sequence of zeros and ones.
I know that in java there are byte-based streams and character-based streams. when I use byte-based streams such as FileOutputStream, the output is characters not bytes.
File file = new File("Myfile.dat"); // .txt or .bin
FileOutputStream fos = new FileOutputStream(file);
String data = "Hello, world";
fos.write(data.getBytes());
fos.close();
when I open Myfile.dat using notepad, I expect to see special characters or 0s and 1s but I can read the content "hello world". So I do not undrstand how byte-based streams store characters in binary format?
A: It's not that "binary files" can't be read by text editors, it's that "binary files containing characters useless to a text editor can't be read/edited in a meaningful way". After all, all files are binary: it just depends on what's contained in them.
A: Binary files can be opened by most text editors too, it just depends on what the binary values are and how the editor interpret them as text values. There is no reason why you couldn't open the output of your Java program in Notepad or any simple text editor - you'll just see gibberish and special characters! If you wan to see the contents as binary then you'll need a binary file editor/viewer such as hexEdit.
A: What exactly do you mean by "binary file"? There is no magic tag that marks a file as either a "binary file" or a "text file" (at least not in any OS in common use these days).
A file is nothing but a stream of bytes with a name and some metadata (creation date, permissions, ...) attached.
Whether the content can be interpreted as text or bytes depends entirely on the content.
So if you write a file only using binary values less than 128 (and avoid some low values), then the result is valid ASCII and might look (roughly) like a text file when opened in a text editor.
If, however, you write random bytes to a file, then opening it with a text editor will not result in sane output.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to Compress an ASPX Page? I followed the sample from here to compress my page:
http://www.codeproject.com/KB/aspnet/Aspx_Compression.aspx
But the result I get is a page full of odd characters:
���I�%&/m�{J�J��t��$ؐ@�������iG#)�*��eVe]f@�흼��{����{����;�N'
Not sure what's wrong with that code?
I tried the code both in Page_Load and Page_Render events.
Any idea?
Thanks,
Update:
just an update; my code was wrong! debugged it with FireBug/Net tab and it was revealed that a wrong Header was added.
A: Use SquishIt to compress the CSS and JavaScript. It is a very good tool
See a good article on SquishIt
You can dowload the SquishIt from GitHub
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there anything special in developing mobile applications in phonegap? Am a android application developer and am new to phonegap.
I heard of phonegap framework and my doubt is developing with phonegap have any other advantage than cross platform.
Am going to develop application only for android is there any other special use of phonegap for me.
A: Well, with PhoneGap you write your applications in HTML5 and Javascript and get access to some stuff like GPS, Sensors, etc that you wouldn't get with a "simple" web application running in Mobile Safari or the Android Browser (does that have a special name?).
So, if you do not plan to port your applications to another platform and you already know Java and the Android SDK, there's not a real advantage for you moving to PhoneGap.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Access ASP.NET session variable from JavaScript When the code var accNo = '<%=Session["hdnAccession"]%>'; will be executed ?. I change the session variable in the Page_LoadComplete event, but when I access it using var accNo = '<%=Session["hdnAccession"]%>';, it always return the value which I set FIRST. In Page_LoadComplete, I do like the following... Session["hdnAccession"] = GetNewAccession(), When I debugged, I saw that the Session["hdnAccession"] updated each time. But why it do not get updated in JavaScript ?. I am in a situation where I can not use HiddenField instead of Seession.
A: You need to create a PostBack to access session variables from JS. Like so:
<script type="text/javascript">
<!--
function setSessionVariable(valueToSetTo)
{
__doPostBack('SetSessionVariable', valueToSetTo);
}
// -->
</script>
private void Page_Load(object sender, System.EventArgs e)
{
// Insure that the __doPostBack() JavaScript method is created...
this.GetPostBackEventReference(this, string.Empty);
if ( this.IsPostBack )
{
string eventTarget = (this.Request["__EVENTTARGET"] == null) ? string.Empty : this.Request["__EVENTTARGET"];
string eventArgument = (this.Request["__EVENTARGUMENT"] == null) ? string.Empty : this.Request["__EVENTARGUMENT"];
if ( eventTarget == "SetSessionVariable" )
{
Session["someSessionKey"] = eventArgument;
}
}
}
See here: http://forums.asp.net/post/2230824.aspx
A: You must use some server-side control to do it(such as HiddenField or hidden span with runat="server").
<%=Session["hdnAccession"]%> will only evaluate the first time you enter the page, not during postbacks.
A: Your code block is getting its values when the page is rendered, and therefore any values set in Page_Load or Page_LoadCompleted should be seen properly in the client side.
If it isn't, there must be a different problem - try testing this by adding a temporary property to the page, initialize it in Page_Load and write it into the client side (i.e, var test = "<%=SomeProperty%>";).
If the problem occurs only after performing a postback (it is not very clear from your question), you will probably have to use hidden fields after all. There may be other ways to handle this, but I can't see a situation where you will be able to implement them and not be able to add hidden fields.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Optimal SQL Query when ORDERing BY SUMs Just as a note, this question is an extension of one of my previous questions. The parameters have changed, so I need a new answer.
I have a MySQL Table that has four fields post_id(unique int), user_id(int), category(varchar), score(int).
My goal is to end up with two values, one being what percent of a user's posts are in "x" category. The second is the sum of all the scores in that "x" category. To do this I've assumed that I need to get three values from MySQL:
*
*SUM(score) GROUP BY category
*COUNT(post_id) GROUP BY category
*COUNT (post_id)
So that's a simple enough query to write. Here's the difficult part: I need to get the top 50 users, ordered by some calculation like (percent + sum). I guess I could write a query that does all the above math in a subquery/JOIN, and then just put an ORDER BY and LIMIT in the main query, but this seems inefficient. I'm planning for 2million users, and each user could have 5000 posts. If I did my query like that (I think) it would take forever to run through each of those records.
What is the most efficient way to run a query like this? I've read about MySQL views which seem like a nice idea, but I've also read they have huge performance problems. Is it worth it?
Or is it impossible? Should I settle for running a CRON job a couple times a day, and just storing faux-realtime numbers?
A: Do you already have a large user database and a lot of posts?
If you don't you could create a meta-table that keeps track of these sums and counts. These would be easy to update in real time when the user adds a post or a score. You wouldn't have to scan the DB every time you needed to recount posts and scores for the statistics because you'd already have them in a table. It would be easy to do the calculations on this table instead.
There's a little extra work in the beginning when you create the functions that add everything to the meta-table. But it would probably pay off in the long run.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: gcc -finline-functions option I have a question regarding the -finline-function options
We are testing whether the function which we have implemented is getting successfully inlined.
Here are the observation
*
*The functions are getting inlined for -01,-O2 and -O3 optimization levels.
*The functions are not getting inlined for optimization level -O0, which is expected.
When we tried compiling using -O0 and -finline-functions together, we still observed that the functions are not getting inlined. we even tried for a very simple method(one line return statement) and observed the same result.
So it seems that usage of -finline-functions flag along with -O0 is redundant(It will not make functions inline). I am still searching if this behavior is documented somewhere in gcc/g++ manual. Please let us know if anyone has exact idea about how g++ works specify -finline-functions and -O0 together.
Regards
A: From the gcc manual ( http://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html ):
Most optimizations are only enabled if an -O level is set on the command line. Otherwise they are disabled, even if individual optimization flags are specified.
A: define your function like this inline void foo (const char) __attribute__((always_inline));
From website (https://gcc.gnu.org/onlinedocs/gcc/Inline.html)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555458",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Animate NSWindow I would like to animate a custom NSWindow (just containing an image) with a scale transform.
I was using previously an CGSPrivate function but I would like to publish my app to teh appstore, so it no more an option.
Do you know how I can achieve the same result?
A: If you only need to scale an NSWindow instance, you should look into the setFrame:display:animate: function.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555468",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why is shouldAutorotateToInterfaceOrientation not called in rotation 5,6? Everything is fine and the method "shouldAutorotateToInterfaceOrientation" gets called for standard orientations like portrait, portrait-down, landscaperight and landscapeleft. However, I have noticed that it's not get called on orientations that is when iphone is lying on the table face down or face up. In my code [UIDevice currentDevice].orientation returns some values like 5 and 6 for that but, as I said, the rotation event method isn't called for those orientations. Am I missing something?
A: Why would it? How should the interface orientation react if the user places the devices flat on a table? There is no way for the device to tell which orientation would be the "correct" one.
Device orientation ≠ Interface orientation
A:
interfaceOrientation The orientation of the application’s user
interface after the rotation. The possible values are described in
UIInterfaceOrientation.
typedef enum {
UIInterfaceOrientationPortrait = UIDeviceOrientationPortrait,
UIInterfaceOrientationPortraitUpsideDown = UIDeviceOrientationPortraitUpsideDown,
UIInterfaceOrientationLandscapeLeft = UIDeviceOrientationLandscapeRight,
UIInterfaceOrientationLandscapeRight = UIDeviceOrientationLandscapeLeft
} UIInterfaceOrientation;
As you can see the orientations are interface orientations, not device orientations.
You may want to take a look at: Reading the accelerometer
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Export to Excel - JSP Page I have a simple table which I would like to export to an Excel file on click of a button.
I wrote a function in JavaScript, but I am not sure what is going wrong.
function CreateExcelSheet()
{
var x=myTable.rows
var xls = new ActiveXObject("Excel.Application")
xls.visible = true
xls.Workbooks.Add
for (i = 0; i < x.length; i++)
{
var y = x[i].cells
for (j = 0; j < y.length; j++)
{
xls.Cells( i+1, j+1).Value = y[j].innerText
}
}
}
This is the button on the JSP page:
</table>
<input type="button" onclick="CreateExcelSheet()" value="Export"></input>
</form>
It used to work earlier but it is not working now. Is there any other way to do this?
A: You can use Apache POI. This is one example.
http://www.koders.com/java/fid8624B82721FCB1B8C982E6BA5D17D2C7DD87D09C.aspx?s=HSSF+main+excel#L19
It creates "Workbook" , then inside a method called make2 it creates a "Sheet" and add the rows and cells. The values of the cells are passed to the method as Vector.
Another option is that you can use displaytag. The display tag has a feature that allow the user to export the html table to excel file.
A: A really simple alternative is to call a servlet, that servlet returns an xls created from html table tags (this is suitable for really simple tables for complex ones you might want to use POI). From this CodeRanch resource.
in your jsp you have this:
<form method="post"
action="DownloadAsExcel"> <input
type="submit" name="submit" value="Download
as Excel" /> </form>
in your backend :
public class DownloadAsExcel extends HttpServlet {
public void doPost(HttpServletRequest req,HttpServletResponse res)
{
res.setContentType("application/vnd.ms-excel");
PrintWriter out=res.getWriter();
out.println("<table>");
out.println("<tr bgcolor=lightblue><td>Hello </td><td>James</td></tr>");
out.close();
}
}
A: <script language="javascript">
function runApp()
{
var x=myTable.rows;
var Excel = new ActiveXObject("Excel.Application");
Excel.visible = true;
var Book = Excel.Workbooks.Add();
for (i = 0; i < x.length; i++)
{
var y = x[i].cells;
for (j = 0; j < y.length; j++)
{
Book.ActiveSheet.Cells( i+1, j+1).Value = y[j].innerText;
}
}
}
</script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Making Android's ZoomButtonsController and GestureDetector get along I've been stuck on this for a while now, and though I found a workaround I don't quite understand why it works and I should to implement it properly! There also seems to be a dearth of information on the ZoomButtonsController out there.
Per other articles here, I've implemented "swipe" gesture functionality in my app. However, on a single tap, I also wanted the zoom buttons to appear programmatically. I had the GestureDetector-based OnTouchListener already for this ScrollView, and so I added a ZoomButtonsController as the OnZoomListener for it as well (along with code to handle onSingleTapConfirmed and other such things).
Things worked fine - until the zoom buttons appeared. From that point forward (assuming constant visibility), no gestures work, not even tapping, even after the zoom buttons fade away! You can click the zoom buttons while they are onscreen and scroll still works fine but the gestures are gone.
I finally came up with a "fix": if OnZoomListener.onVisibilityChanged() fires to invisible I call myScrollView's setOnTouchListener() to restore the gestureListener (like I did in onCreate()). The gestures work fine again.
Edit: if you do this when onVisibilityChanged() fires to visible, you get gestures working right away BUT it disables the zoom buttons so it's not that great! It'd be nice to have both...
So, is what I'm doing the right way to use ZoomButtonsController and if not, what is? More importantly, why is it when the zoom buttons appear they seem to replace my OnTouchListener permanently? Is ZoomButtonsController supposed to hijack the gestures currently after it fires? Is this somehow more basic than that (some general property of listeners)?
A: I've struggled with this issue for a while before I've found a solution. I'm not sure if it's the most correct one, but it's functioning perfectly.
Concept:
1 - Don´t add the ZoomButtonsController widget directly to the view where you need them. The onTouch events will conflict. Instead, you need to add the ZoomButtonsController widget to a new view and add this view to the same layout where is the view you want to add the zoom buttons to.
2 - The view where the ZoomButtonsController have been added must be the last being added to the parent layout. This way it will be the first being called, and if the zoom buttons are not pressed the onTouch event is passed to your view for you to process.
Code with example:
//First my view where I need the zoom buttons
imageView = new ImageView(context);
LayoutParams layoutParams = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
imageView.setLayoutParams(layoutParams);
imageView.setOnTouchListener(onTouchListener);
relativeLayout.addView(imageView);
//Secondly the view where the buttons are added
View zoomView = new View(context);
LayoutParams layoutParamsZoom = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
zoomView.setLayoutParams(layoutParamsZoom);
relativeLayout.addView(zoomView);
zoomButtonsController = new ZoomButtonsController(zoomView);
zoomButtonsController.setOnZoomListener(onZoomListener);
Finally, you just need to add the listener to the zoom widget:
ZoomButtonsController.OnZoomListener onZoomListener = new ZoomButtonsController.OnZoomListener() {
@Override
public void onZoom(boolean zoomIn) {
Log.d(TAG, "onZoom: " + zoomIn);
if(zoomIn){
setZoom(currentZoom +1);
}else{
setZoom(currentZoom -1);
}
}
@Override
public void onVisibilityChanged(boolean visible) {
// TODO Auto-generated method stub
}
};
Good luck,
Luis
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Automate download and install of root certificate Currently we manually go to a url to download a root cert.
However there is now a need to automate it. I am looking for C# examples of how to accomplish this. I would like to give the url as a parameter, and then the program must take over and open this url in the background, download and install the requested certificate, without the user having to do anything, or know what happened. There is no prompt for a user name and password, when you do it manually, so this library should enable me to make such a call.
Please give me some advice on what to do, or some handy articles I can read to get me going?
A: Here's example how to get a root certificate from Certification Authority
// address - CA address
public static void InstallRootCert(string address)
{
// getting root cert
ICertRequest2 objRequest = new CCertRequest();
string rootCert = objRequest.GetCACertificate(0, address, 0);
byte[] buffer = Encoding.UTF8.GetBytes(rootCert);
// installing
var store = new X509Store("Root", StoreLocation.CurrentUser);
store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite);
var root = new X509Certificate2(buffer);
store.Add(root);
}
A: Since the information you provide is rather general some general pointers on how you could implement this:
The download can be achieved via a WebClient and/or HttpWebRequest .
As for the installation you can do that via X509Store together with StoreName.Root - for details and sample source see http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509store.aspx
A: Download with whatever http request method you like. Install it like:
app.ClientCertificates.Add(
new System.Security.Cryptography.X509Certificates.X509Certificate2(
@"c:\Downloads\testcert.pfx", "password"));
See here for more info on managing certificates: http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate2.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Get data from a database that is between two dates I am writing a system that will show data from a selected month. The user can select the month they want to look at, this then creates a URL something like this .com/page.php?month=03 the page as you can guess will take the idea and then use it to get data from the database from that month.
Now based on the month in the URL i am making to vars, $startdate $enddate start date based on this example is 2011-03-01, i then add 29 or 30 on to the days part of the date depending if the month has 31 or 30 days. Okay so i do the dates like this:
$startdate = mktime(0,0,0,date("$month"),date("01"),date("2011"));
if( $month==04 || $month==06 || $month==9 || $month==11)
{
$enddate = mktime(0,0,0,date("$month"),date("01")+29,date("2011"));
}
else
{
$enddate = mktime(0,0,0,date("$month"),date("01")+30,date("2011"));
}
Now when i try to get the data from the database with these variables it doesn't seem to work, this is the query:
$getresults = mysql_query("SELECT * FROM table1 WHERE date BETWEEN $startdate AND $enddate ORDER BY date ASC");
The thing is if i change the vars to hard coded dates its works a treat... Anyone got any ideas? i was thinking it had something to do with the way the day is formatted? in my database its "Y-m-d" and is also the same in the php.
thank for any help people im really stuck on this one.
A: mktime produces dates as Unix timestamps (eg. '1317046059') but your table stored dates in a different format (eg. '2011-09-26'). To make your queries work, you will need to convert your timestamps into the appropriate format:
$enddate = date( 'Y-m-d', mktime(0,0,0,date("$month"),date("01")+29,date("2011")) );
Update:
Based on your new comment that your dates are stored as timestamps in your database, you will need to format your dates in this manner:
$enddate = date( 'Y-m-d h:i:s', mktime(0,0,0,date("$month"),date("01")+29,date("2011")) );
A: You should use a couple var_dump statements in key places to evaluate you code. This way, you can know EXACTLY what your data looks like, including its format, then you can figure out how to format that date the way you need to.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: NHibernate Multiple Parents with same Child Entity Reference-to-Parent I have a data structure with two parents, that can have children of the same class (entity) type.
public class Parent1 : BaseParent
{
public Parent1()
{
Childs1 = new List<Child>();
}
public virtual IList<Child> Child1 { get; set; }
}
public class Parent2 : BaseParent
{
public Parent2()
{
Childs2 = new List<Child>();
}
public virtual IList<Child> Child2 { get; set; }
}
public class Child
{
public virtual BaseParent Parent { get; set; }
}
The Child should have a reference to its parent, whose collection it belongs to. That means, if Child is in the collection of Parent1.Childs1, Child.Parent should reference to Parent1. If Child is in the collection of Parent2.Childs2, Child.Parent should reference to Parent2.
I tried with
public class Parent1Map: ClassMap<Parent1>
{
public Parent1Map()
{
Table("PARENT1");
:
HasMany<Child>(x => x.Child1).KeyColumn("PARENT1REF");
}
}
public class Parent2Map: ClassMap<Parent2>
{
public Parent2Map()
{
Table("PARENT2");
:
HasMany<Child>(x => x.Child1).KeyColumn("PARENT2REF");
}
}
public class ChildMap: ClassMap<Child>
{
public ChildMap()
{
Table("CHILD");
:
References<Parent1>(c => c.Parent).Column("PARENT1REF");
References<Parent2>(c => c.Parent).Column("PARENT2REF");
}
}
But this does not work. I geht the error Tried to add many-to-one 'Parent' when already added.
How can I do the mapping, so that the parent references of the childs are loaded correctly from the database?
A: i had a similar problem and went with referenceany. It's only applicable if child is never in more than one collection.
// ChildMap
ReferencesAny(result => result.Parent)
.EntityTypeColumn("discriminator")
.EntityIdentifierColumn("Parent_id")
.IdentityType<long>()
.AddMetaValue<Parent1>("parent1")
.AddMetaValue<Parent2>("parent2");
// parent1map
HasMany(part => part.Childs)
.Where("discriminator = 'parent1'");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: controller & model name ambiguity in code igniter 2.0.2 Following is the scenario:
I've integrated HMVC in CodeIgniter 2.0.2. Created a module with following structure.
/application/modules/login
/application/modules/login/controllers
/application/modules/login/controllers/login.php
/application/modules/login/models/login.php
/application/modules/login/views/login_form.php
controller/login.php code
class Login extends CI_Controller{
public function index(){
//load login form view
}
public function authenticate(){
$model = $this->load->model('login'); //tried with Login
$model->validate(); //shows error here
}
}
/views/login_form.php
<form name='LoginForm' method='post' action='/login/authenticate'>
/models/login.php
class Login extends CI_Model{
public function validate(){
echo $this->input->post('EmailId');
echo $this->input->post('Pword');
}
}
output:
got error indicating undefined method Login::validate()
When created validate() method in controller Login it works. But it shouldn't happen.. even though I'm loading a model with name Login why it points to Login Controller.
Can anyone could help me out. The way I did is it correct? Suggestions welcomed...
A: You are loading and accessing your model incorrectly. Take a look at the documentation for more examples.
Change your authenticate() method to:
public function authenticate() {
$this->load->model('login');
$this->login->validate();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Problem with installing assemblies to the GAC I'm trying to deploy a couple of third party assemblies in the GAC with WiX. Some of these assemblies are mixed assemblies. The common way of doing this seems to be setting the assembly-attribute of the corresponding file to "net". However, doing it that way yields in an error during the installation:
Error 1938. An error occurred during the installation of assembly ...One or more modules of the assembly could not be found. HRESULT: 0x80131042. assembly interface: IAssemblyCacheItem, function : Commit, component: ... MSI (s) (A8:B0) [12:32:39:085]:.... assembly .... One or more modules of the assembly could not be found. HRESULT: 0x80131042. assembly interface: IAssemblyCacheItem, function: Commit, component:...
The instructions I got from the vendor for installing the assembly to the gac is:
*
*Place all the dlls (d1, d2, d3,..., dn) in the same directory.
*Run gacutil on a subset of these dlls.
If I take a "raw" look in the gac, one of the folders contents looks like this:
gac_32\d1\0.0.0.0_271E3736135E91A2\d1.dll
gac_32\d1\0.0.0.0_271E3736135E91A2\d2.dll
gac_32\d1\0.0.0.0_271E3736135E91A2\d3.dll
gacutil has found out that d2.dll an d3.dll need to be placed in the same directory as d1.dll and has automaticaly done so.
How can I do this with wix? The only way I see right now is calling gacutil as a custom action, but this does not seem like a good solution.
Thank you
Stefan
A: In case anyone else is struggling with this:
To install a multifile assembly that is made up of one managed assembly and one or more native or mixed dlls that are referenced by the managed assembly, create the following structure in your WixSetup:
<Component Id="MyMultifileAssembly" Guid="abc">
<File Id="ManagedAssembly" KeyPath="yes" Source="$(var.ThirdParty)\Managed.dll" Assembly=".net"/>
<File Id="UnmanagedAssembly1" KeyPath="no" Source="$(var.ThirdParty)\Unmanaged1.dll" />
<File Id="UnmanagedAssembly2" KeyPath="no" Source="$(var.ThirdParty)\Unmanaged2.dll" />
</Component>
Both unmanaged assemblies will go to the GAC-folder where the managed dll is installed to.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: swfupload jquery plugin file upload list Was just wondering if anyone knows if you can set the limit of upload files to display on the list after selecting the files? (NOT the max amount of images you can upload)
eg. I choose to upload 10 images, normally it will display a list with all 10 images in the queue... instead i want it to display only 5 images and as each uploads and leaves the queue list at the bottom the next one shows up...
OR
another option is to display the overall upload progress instead of individual files... is this possible with this plugin?
Thanks in advance for any help!!
A: You might be having code like this
jQuery('#swfupload-control').swfupload({
upload_url: "progress/upload-file.php?uid="+uid,
file_post_name: 'uploadfile',
file_size_limit : "25600",
file_types : "*.mpeg;*.flv;*.mp4;*.mpg;*.wmv;*.3gp;",
file_types_description : "Video files",
file_upload_limit : 10000,
flash_url : "progress/js/swfupload/swfupload.swf",
button_image_url : 'progress/js/swfupload/upload_btn.png',
button_width : 74,
button_height : 23,
button_placeholder : jQuery('#button')[0],
debug: false
})
In that change value of this attribute to 5
file_upload_limit : 5,
with regards
Wasim
A: Well found one solution to this issue adding a max-height to the css file and overflow: auto this way atleast it doesnt grow when theres alot of files in the queue list just has a scrollbar. The other two options i was looking for I still havent found a solution to. If anyone knows these ways or any other way please share!! Thanks!
A: Ok you can do one thing
Make your height of the division such that it can only show 10 uploads
Add some attribute id to var listitem='<li id="'+file.id+'" >'+
In
.bind('uploadSuccess', function(event, file, serverData){
//instead use $("#"+file.id).remove() to remove the list item which got completed
item.addClass('success').find('p.status').html();
})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555501",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What is the alternative for CollabNet's python svn bindings? What is the alternative for the python svn bindings provided by CollabNet (this where you have 2 directories: svn and libsvn, the second with a lot of pre-compiled libraries)? The problem with it is that it just can't be configured to run with Windows version on Python. We've done what was written on various fora, but it just didn't work.
At best would be the package written fully in python - no compilation issues. I know of pysvn, but it seems to have client-side functionality (based on checkouted code) not server-side (based on provided repository path, such as svnlook).
A: Apache Subversion is written in C and provides native libraries for the OS. On Windows, this means DLL's. Subversion provides "bindings" for a number of different languages, including Python. This gives you a shim that lets you write code in your language and the bindings handle making calls into the native libraries.
To use the Python bindings, you need to install them into your Python system but you ALSO need to make sure the appropriate Subversion native library are on PATH. Your Python code will load the Python bindings, but that code will load and make calls into the native DLL's. So they have to be on the PATH and they have to be a matching version.
There is no "pure Python" version of Subversion.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: PHP file execution txt doc
Possible Duplicate:
PHP run code from txt file
Php... is it possible to execute a txt in a server that contains a php script?
I need to execute this somehow
The file is in txt extension.. Please tell me if
It's possible
A: Just use include, but be aware that this is very insecure.
This is of course assuming the .txt file also includes the PHP open tags. If not, you could read the file to a string and use eval to execute the code...
A: The ending txt is for text files. If you are saying that you wish to display the content of a text file, then you have to create a php program that will do it.
You might want to look at file_get_contents in php.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555525",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: which command equivalent in Python I have the following code which i am using to check if the program class-dump exists on a system. The program only returns a blank.
cmd = ["which","class-dump"]
process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
print process.stdout.read()
This code always returns a blank. Technically it should work right ?
A: I tried the following on my machine and its working perfectly.
import subprocess
cmd = ["which","java"]
process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
print process.communicate()
this is the output
('/usr/bin/java\n', None)
A: which is a shell built-in. You need to pass shell=True to the Popen.
A: Hmmm, it looks like the class-dump does not exists (in the PATH used by your python interpreter)
A: Does it work if you use communicate instead? See this warning:
Warning
Use communicate() rather than .stdin.write, .stdout.read or
.stderr.read to avoid deadlocks due to any of the other OS pipe
buffers filling up and blocking the child process.
Also, is it possible that your script runs under another PATH than your shell? Dump os.environ["PATH"] and check.
A: This code does the same thing as the shell which command programatically, except that it does not "find" symbolic links. To support that, you can enhance the isx function.
import os.path, itertools
isx = lambda program: lambda folder: (lambda p: \
os.access(p, os.X_OK) and os.path.isfile(p))(os.path.join(folder, program))
def which(program):
try:
return itertools.ifilter(isx(program), os.environ['PATH'].split(':')).next()
except StopIteration:
raise ValueError, 'no executable file named %s found in search path' % (program,)
Example use:
>>> which('ls')
'/bin'
>>> which('foo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in which
ValueError: no executable file named foo found in search path
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: NPE When running Netbeans using the GTK LAF Recently, I got a weird stack trace in the netbeans logs (I added it to the end of this post). I was able to track it down to the LAF. This error happens, when running Netbeans using the GTK LAF, but works fine in Metal, and using the native Windows LAF.
It seems, that the PropertyChangeSupport instance is NULL, so it throws an error when adding a Property change listener. Here's the abbreviated source of my custom component:
public class EnterprisePicker extends javax.swing.JPanel implements ActionListener, KeyListener, ListSelectionListener, UnitContainer {
private static final Logger logger = IdeUiUtil.initLogger(EnterprisePicker.class.getName());
protected InfoPanelStyle infoPanelStyle = InfoPanelStyle.FULL;
private final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
public static final String PROP_INFOPANELSTYLE = "infoPanelStyle";
/** Creates the new component */
public EnterprisePicker() {
// [... snip ...]
}
// [ ... snip ... ]
/**
* Add PropertyChangeListener.
*
* @param listener
*/
@Override
public void addPropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(listener);
}
// [ ... snip ... ]
}
Obviously I could simply protect these calls using if (propertyChangeSupport == null)... But would that not break properties later on in the application? Assuming that no listener will ever be attached as the instance is null...?
Stack Trace
INFO [org.netbeans.modules.form.BeanSupport]: Cannot create default instance of: org.statec.ide.ui.components.EnterprisePicker
java.lang.NullPointerException
at org.statec.ide.ui.components.EnterprisePicker.addPropertyChangeListener(EnterprisePicker.java:654)
at javax.swing.plaf.synth.SynthPanelUI.installListeners(SynthPanelUI.java:49)
at javax.swing.plaf.synth.SynthPanelUI.installUI(SynthPanelUI.java:38)
at javax.swing.JComponent.setUI(JComponent.java:662)
at javax.swing.JPanel.setUI(JPanel.java:136)
at javax.swing.JPanel.updateUI(JPanel.java:109)
at javax.swing.JPanel.<init>(JPanel.java:69)
at javax.swing.JPanel.<init>(JPanel.java:92)
at javax.swing.JPanel.<init>(JPanel.java:100)
at org.statec.ide.ui.components.EnterprisePicker.<init>(EnterprisePicker.java:39)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at java.lang.Class.newInstance0(Class.java:355)
at java.lang.Class.newInstance(Class.java:308)
at org.netbeans.modules.form.CreationFactory.createDefaultInstance(CreationFactory.java:168)
[catch] at org.netbeans.modules.form.BeanSupport.createBeanInstance(BeanSupport.java:83)
at org.netbeans.modules.form.BeanSupport.getDefaultInstance(BeanSupport.java:109)
at org.netbeans.modules.form.GandalfPersistenceManager.restoreComponent(GandalfPersistenceManager.java:769)
at org.netbeans.modules.form.GandalfPersistenceManager.loadComponent(GandalfPersistenceManager.java:1007)
at org.netbeans.modules.form.GandalfPersistenceManager.loadForm(GandalfPersistenceManager.java:527)
at org.netbeans.modules.form.GandalfPersistenceManager.loadForm(GandalfPersistenceManager.java:299)
at org.netbeans.modules.form.FormEditor$3.run(FormEditor.java:337)
at org.netbeans.modules.form.FormLAF$2.run(FormLAF.java:293)
at org.openide.util.Mutex.doEventAccess(Mutex.java:1361)
at org.openide.util.Mutex.readAccess(Mutex.java:320)
at org.netbeans.modules.form.FormLAF.executeWithLookAndFeel(FormLAF.java:276)
at org.netbeans.modules.form.FormEditor.loadFormData(FormEditor.java:334)
at org.netbeans.modules.form.FormEditor.loadFormDesigner(FormEditor.java:232)
at org.netbeans.modules.form.FormDesigner.finishComponentShowing(FormDesigner.java:1932)
at org.netbeans.modules.form.FormDesigner.access$1100(FormDesigner.java:107)
at org.netbeans.modules.form.FormDesigner$PreLoadTask$1.run(FormDesigner.java:1897)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:641)
at java.awt.EventQueue.access$000(EventQueue.java:84)
at java.awt.EventQueue$1.run(EventQueue.java:602)
at java.awt.EventQueue$1.run(EventQueue.java:600)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:611)
at org.netbeans.core.TimableEventQueue.dispatchEvent(TimableEventQueue.java:148)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
INFO
org.openide.ErrorManager$AnnException: msg
at org.openide.ErrorManager$AnnException.findOrCreate(ErrorManager.java:866)
at org.openide.ErrorManager$DelegatingErrorManager.annotate(ErrorManager.java:653)
at org.netbeans.modules.form.GandalfPersistenceManager.annotateException(GandalfPersistenceManager.java:237)
at org.netbeans.modules.form.GandalfPersistenceManager.annotateException(GandalfPersistenceManager.java:247)
at org.netbeans.modules.form.GandalfPersistenceManager.restoreComponent(GandalfPersistenceManager.java:865)
at org.netbeans.modules.form.GandalfPersistenceManager.loadComponent(GandalfPersistenceManager.java:1007)
at org.netbeans.modules.form.GandalfPersistenceManager.loadForm(GandalfPersistenceManager.java:527)
at org.netbeans.modules.form.GandalfPersistenceManager.loadForm(GandalfPersistenceManager.java:299)
at org.netbeans.modules.form.FormEditor$3.run(FormEditor.java:337)
at org.netbeans.modules.form.FormLAF$2.run(FormLAF.java:293)
at org.openide.util.Mutex.doEventAccess(Mutex.java:1361)
at org.openide.util.Mutex.readAccess(Mutex.java:320)
at org.netbeans.modules.form.FormLAF.executeWithLookAndFeel(FormLAF.java:276)
at org.netbeans.modules.form.FormEditor.loadFormData(FormEditor.java:334)
at org.netbeans.modules.form.FormEditor.loadFormDesigner(FormEditor.java:232)
at org.netbeans.modules.form.FormDesigner.finishComponentShowing(FormDesigner.java:1932)
at org.netbeans.modules.form.FormDesigner.access$1100(FormDesigner.java:107)
at org.netbeans.modules.form.FormDesigner$PreLoadTask$1.run(FormDesigner.java:1897)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:641)
at java.awt.EventQueue.access$000(EventQueue.java:84)
at java.awt.EventQueue$1.run(EventQueue.java:602)
at java.awt.EventQueue$1.run(EventQueue.java:600)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:611)
at org.netbeans.core.TimableEventQueue.dispatchEvent(TimableEventQueue.java:148)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
msg
Caused: java.lang.NullPointerException
at org.statec.ide.ui.components.EnterprisePicker.addPropertyChangeListener(EnterprisePicker.java:654)
at javax.swing.plaf.synth.SynthPanelUI.installListeners(SynthPanelUI.java:49)
at javax.swing.plaf.synth.SynthPanelUI.installUI(SynthPanelUI.java:38)
at javax.swing.JComponent.setUI(JComponent.java:662)
at javax.swing.JPanel.setUI(JPanel.java:136)
at javax.swing.JPanel.updateUI(JPanel.java:109)
at javax.swing.JPanel.<init>(JPanel.java:69)
at javax.swing.JPanel.<init>(JPanel.java:92)
at javax.swing.JPanel.<init>(JPanel.java:100)
at org.statec.ide.ui.components.EnterprisePicker.<init>(EnterprisePicker.java:39)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at java.lang.Class.newInstance0(Class.java:355)
at java.lang.Class.newInstance(Class.java:308)
at org.netbeans.modules.form.CreationFactory.createDefaultInstance(CreationFactory.java:168)
at org.netbeans.modules.form.RADComponent.createBeanInstance(RADComponent.java:252)
at org.netbeans.modules.form.RADComponent.initInstance(RADComponent.java:191)
at org.netbeans.modules.form.GandalfPersistenceManager.restoreComponent(GandalfPersistenceManager.java:851)
at org.netbeans.modules.form.GandalfPersistenceManager.loadComponent(GandalfPersistenceManager.java:1007)
at org.netbeans.modules.form.GandalfPersistenceManager.loadForm(GandalfPersistenceManager.java:527)
at org.netbeans.modules.form.GandalfPersistenceManager.loadForm(GandalfPersistenceManager.java:299)
at org.netbeans.modules.form.FormEditor$3.run(FormEditor.java:337)
at org.netbeans.modules.form.FormLAF$2.run(FormLAF.java:293)
at org.openide.util.Mutex.doEventAccess(Mutex.java:1361)
at org.openide.util.Mutex.readAccess(Mutex.java:320)
at org.netbeans.modules.form.FormLAF.executeWithLookAndFeel(FormLAF.java:276)
at org.netbeans.modules.form.FormEditor.loadFormData(FormEditor.java:334)
[catch] at org.netbeans.modules.form.FormEditor.loadFormDesigner(FormEditor.java:232)
at org.netbeans.modules.form.FormDesigner.finishComponentShowing(FormDesigner.java:1932)
at org.netbeans.modules.form.FormDesigner.access$1100(FormDesigner.java:107)
at org.netbeans.modules.form.FormDesigner$PreLoadTask$1.run(FormDesigner.java:1897)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:641)
at java.awt.EventQueue.access$000(EventQueue.java:84)
at java.awt.EventQueue$1.run(EventQueue.java:602)
at java.awt.EventQueue$1.run(EventQueue.java:600)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:611)
at org.netbeans.core.TimableEventQueue.dispatchEvent(TimableEventQueue.java:148)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Error in loading component: [JDialog]->enterprisePicker1
Cannot create instance of org.statec.ide.ui.components.EnterprisePicker.
The component cannot be loaded.
And for reference:
malbert@dredg:~/.netbeans/7.0/var/log$ java -version
java version "1.6.0_26"
Java(TM) SE Runtime Environment (build 1.6.0_26-b03)
Java HotSpot(TM) Server VM (build 20.1-b02, mixed mode)
malbert@dredg:~/.netbeans/7.0/var/log$ cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=11.04
DISTRIB_CODENAME=natty
DISTRIB_DESCRIPTION="Ubuntu 11.04"
A: Just a guess, but the problem could be that during initialization of some super class addPropertyChangeListener(...) is called (javax.swing.JPanel.<init> might be the culprit), thus this call happens before propertyChangeSupport is initialized.
The initialization sequence of instance fields would be:
*
*Object
*Component
*Container
*JComponent
*JPanel
*EnterprisePicker
If during initialization of JPanel the addPropertyChangeListener(...) method is called, it would actually be the overridden version of EnterprisePicker, but EnterprisePicker's fields would not have been initialized yet.
To fix this you'd check for null in that method and initialize as needed (or call super.addPropertyChangeListener(...). Is there any need to have your own implementation (to add your own PropertyChangeSupport)?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Rails AR Search across multiple non-associated tables What is the Rails way to unify separate queries into a single one? Currently I am running separate queries, which i combine into one big results page afterwards:
@events = Event.where("name LIKE ?", "#{params[:search]}%")
@cars = Car.where("name LIKE ?, "#{params[:search]}%")
I would like to retrieve only one @results set and work from there.
In addition, how would you go about scoring those results and sort them by importance? I'd like to deliberately leave out any kind of plugins like Thinking Sphinx or Sunspot/Solr. thanks!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Accessing svn repository from KDevelop I have successfully installed Subversion and set up repository for my project. Then added project to repository, checked it out and opened it in KDevelop.
I can see Subversion menu items but every time I'm trying to operate with svn within KDevelop (either add, commit or update) I've got the same error message:
Could not start process Unable to create io-slave: klauncher said: Unknown protocol 'svn+http'.
Listing /usr/share/services shows me http.protocol but none of svn / svn+http presents.
Is there a way I can follow to resolve this issue?
Thanks!
A: At least in KDE3 you need the kdesvn-kio-plugins package.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Defining copy constructor in a class inherited from POD struct As you know compiler defines default constructor, copy constructor, assignment operator and destructor for POD structures if it weren't defined manually. Usually (or maybe should I say always) it's a bit copy operation. So I've decided to inherit my class from Win structure BITMAP to provide memory allocation in constructor and freeing in destructor. I haven't used composition 'coz I want to allow using it with some WinAPI functions. Here is a some piece of code:
class CPreviewFrame : public BITMAP
{
public:
CPreviewFrame( );
CPreviewFrame( std::size_t width, std::size_t height, UCHAR bytesPerPixel = 3 );
CPreviewFrame( const CPreviewFrame& frame );
~CPreviewFrame( );
.....
};
And copy constructor is defined something like that:
CPreviewFrame::CPreviewFrame( const CPreviewFrame& frame ):
BITMAP( static_cast<BITMAP>(frame) ), //question is here
m_bufferSize( frame.m_bufferSize )
{
bmBits = new uint8_t[ m_bufferSize ];
memcpy( bmBits, frame.bmBits, m_bufferSize );
}
So my question is: Is it proper way to call compiler defined copy constructor from inherited structure or should I copy all fields manually in constructor body? Both variants look somewhat strange for me because POD structs can't have constructors despite compiler defines them. How can you call constructor for POD data type if it doesn't exist by definition?
P.S. Code mentioned above compiles well on VS2010.
P.P.S. There is related question to this theme posted by me here.
A: BITMAP(frame) will do the trick with no cast needed as the compiler will know the type of the parent and be able to implicitly convert the argument. Note that if you want to use a cast to explicit show what you're doing, cast as a reference type: BITMAP( static_cast<const BITMAP&>(frame) ),
Also, seriously consider this inheritance. Sometime a year or two from now someone's going to delete one of your CPreviewFrame objects as a BITMAP. Best case they leak memory, worst case you spend days or weeks debugging why the app isn't working right. Composition (with an appropriate interface that may call WinAPI function behinds the scene) isn't typically that complicated to implement and it will more accurately and correctly model your problem here.
Alternately you could use composition and just provide a getter to the bitmap portion (as suggested in a comment). This exposes implementation details of your class but might make it easier to code to the Win API in the short term.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555545",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to use GROUP BY (date) in MySQL to start at a given day of the week If I have a MySQL query to aggregate totals by week, e.g.:
select sum(keyword1), sum(keyword2), sum(keyword3), dateTime
from myTable
group by week(dateTime)
order by dateTime asc
I find that the weeks appear to begin on a Sunday.
Can this be changed to a Monday?
Column dateTime is in MySQL Timestamp format 2011-09-26 12:34:32.
A: You want the sunday to belong to the previous week so remove one day from it
select sum(keyword1), sum(keyword2), sum(keyword3), week(DATE_SUB(dateTime, INTERVAL 1 DAY)) my_week
from myTable
group by week(DATE_SUB(dateTime, INTERVAL 1 DAY))
order by my_week asc
A: mysql> select week('2011-09-25', 1);
+-----------------------+
| week('2011-09-25', 1) |
+-----------------------+
| 38 |
+-----------------------+
mysql> select week('2011-09-25', 0);
+-----------------------+
| week('2011-09-25', 0) |
+-----------------------+
| 39 |
+-----------------------+
So, http://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html#sysvar_default_week_format
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555550",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Adding files to a GitHub repository How do I add files to my GitHub repository? I'm using Windows and all my project files are in one folder and I just need to upload it to my repo.
A: You can use Git GUI on Windows, see instructions:
*
*Open the Git Gui (After installing the Git on your computer).
*Clone your repository to your local hard drive:
*After cloning, GUI opens, choose: "Rescan" for changes that you made:
*You will notice the scanned files:
*Click on "Stage Changed":
*Approve and click "Commit":
*Click on "Push":
*Click on "Push":
*Wait for the files to upload to git:
A: The general idea is to add, commit and push your files to the GitHub repo.
First you need to clone your GitHub repo.
Then, you would git add all the files from your other folder: one trick is to specify an alternate working tree when git add'ing your files.
git --work-tree=yourSrcFolder add .
(done from the root directory of your cloned Git repo, then git commit -m "a msg", and git push origin master)
That way, you keep separate your initial source folder, from your Git working tree.
Note that since early December 2012, you can create new files directly from GitHub:
ProTip™: You can pre-fill the filename field using just the URL.
Typing ?filename=yournewfile.txt at the end of the URL will pre-fill the filename field with the name yournewfile.txt.
A: Open github app.
Then, add the Folder of files into the github repo file onto your computer (You WILL need to copy the repo onto your computer. Most repo files are located in the following directory: C:\Users\USERNAME\Documents\GitHub\REPONAME)
Then, in the github app, check our your repo. You can easily commit from there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "50"
}
|
Q: Can't Selecting Multiple fields in django admin In My django admin form I have one Image Upload field and also It has been done for the preview support.Also I has clear option to clear that image in the object.If i need to select another image with also clicking the clear option "It does't do that" At a time it says only one option will be done.What I should have to do for the both operations?
Also What could do to have multiple ImageFields in django admin form?What are the ways to do it?
A: Use django inline model admin here
earlier question on SO: go here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555552",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can . (period) be part of the path part of an URL? Is the following URL valid?
http://www.example.com/module.php/lib/lib.php
According to https://www.rfc-editor.org/rfc/rfc1738 section the hpath element of an URL can not contain a '.' (period). There is in the above case a '.' after "module" which is not allowed according to RFC1738.
Am I reading the RFC wrong or is this RFC succeed by another RFC? Some other RFC's allows '.' in URLs (https://www.rfc-editor.org/rfc/rfc1808).
A: I don't see where RFC1738 disallows periods (.) in URLs. Here are some excerpts from there:
hpath = hsegment *[ "/" hsegment ]
hsegment = *[ uchar | ";" | ":" | "@" | "&" | "=" ]
uchar = unreserved | escape
unreserved = alpha | digit | safe | extra
safe = "$" | "-" | "_" | "." | "+"
So the answer to your question is: Yes, http://www.example.com/module.php/lib/lib.php is a valid URL.
A: Nothing wrong with a period in a url. If you look at the makeup in the grammar in the link you provided a period is mentioned via the 'safe' group, which is included via uchar a
Ignore my answer, Adams is better
A: As others have noted, periods are allowed in URLs, but be careful. If a single or double period is used in part of a URL's path, the browser will treat it as a change in the path, and you may not get the behavior you want.
For example:
*
*www.example.com/foo/./ redirects to www.example.com/foo/
*www.example.com/foo/../ redirects to www.example.com/
Whereas the following will not redirect:
*
*www.example.com/foo/bar.biz/
*www.example.com/foo/..biz/
*www.example.com/foo/biz../
A: Periods are allowed. See section "2.3 Unreserved Characters" in this document:
https://www.rfc-editor.org/rfc/rfc3986
"Characters that are allowed in a URI but do not have a reserved purpose are called unreserved. These include uppercase and lowercase letters, decimal digits, hyphen, period, underscore, and tilde".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "44"
}
|
Q: Drupal 7: How to create a text field with php default value? I've been searching for quite a while now and still wasn't able to find an answer yet.
I'm using Drupal 7.4 and I created a new content type. There i want to add a simple text field that has a Default value where I can add PHP. Normally, the Default value shows only plain text.
To be more specific:
For the users I defined a field_city that they must complete when they sign up.
So for example i would have a user "john" from "Bucharest".
I need to assign the value of field_city - namely Bucharest - to the default value of the text field via PHP (I know how to do this part).
So when john adds new content, he would already have Bucharest printed in that text field but still be able to write whatever other city there.
How could I achieve this?
Can I get away without making a custom module?
Thanx.
A: Are you using the CCK module for Drupal 7? Although it is still in development status, it will do the trick.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555554",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to delete a character? Hi I am developing a code in which I need to perform a delete a last character from a uitextview
I tried like this
-(IBAction)delete:(id)sender{
uitextview.text =[NSString stringWithFormat:@"%@%@",uitextview.text,@"\b"];
}
on a delete button action i gave this code but this is not performing the deletion.
please help to doing this work and thanks in advanceO
A: For remove last character use something like this:
-(IBAction)delete:(id)sender{
uitextview.text =[uitextview.text substringToIndex:[uitextview.text length] - 1];
}
A: To remove 1st character from the string try the following:
-(IBAction)delete:(id)sender{
uitextview.text =[uitextview.text substringFromIndex:1];
}
To remove last one:
-(IBAction)delete:(id)sender{
uitextview.text = [uitextview.text substringToIndex:[uitextview.text length]-1];
}
You may also need to check if your string is not empty otherwise "index out of bounds" exception may occur
A: This would work also
- (IBAction)delete:(id)sender {
[uitextview deleteBackward];
}
A: You will want to use the substringFromIndex method like so:
uitextview.text = [uitextview.text substringFromIndex:1];
Make sure to check the length before doing this, else the substringFromIndex call will throw an exception.
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/substringFromIndex:
A: if ([string length] >0)
{
string = [string SubstringToIndex: [sting length] -1];
}
A: Following up on the above answers, to make a string drop the first character it needs to be
substringfromindex says: make a new string starting at index (1 here) until the end
bevNoMoney = [totalBevSales substringFromIndex:1];
A: Several answers are susceptible to index out of bounds exceptions. Here is a safer implementation:
-(IBAction)delete:(id)sender{
if (uitextview.text.length > 0) {
uitextview.text =[uitextview.text substringToIndex:[uitextview.text length] - 1];
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How are notifications such as "xxxx commented on your post" get pushed to the front end in Facebook?
Possible Duplicate:
How does facebook, gmail send the real time notification?
For example, I am on Facebook and I see this little notification being displayed that some one commented on a post I made. What is the technology used here?
Is it AJAX? If so how can data be PUSHED to the front using AJAX?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555561",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: iPhone Web based apllication back ,forward and refresh button In my iphone web based application i want to add backword,Forward,Refresh and Action button like the native Webview,How i implement this in my app.
Thanks,
Arun
A: Use what HTML gives you to draw this navigation. Or look for ready code for that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What is the recommended way to make a numeric TextField in JavaFX? I need to restrict input into a TextField to integers. Any advice?
A: I want to help with my idea from combining Evan Knowles answer with TextFormatter from JavaFX 8
textField.setTextFormatter(new TextFormatter<>(c -> {
if (!c.getControlNewText().matches("\\d*"))
return null;
else
return c;
}
));
so good luck ;) keep calm and code java
A: TextField text = new TextField();
text.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable,
String oldValue, String newValue) {
try {
Integer.parseInt(newValue);
if (newValue.endsWith("f") || newValue.endsWith("d")) {
manualPriceInput.setText(newValue.substring(0, newValue.length()-1));
}
} catch (ParseException e) {
text.setText(oldValue);
}
}
});
The if clause is important to handle inputs like 0.5d or 0.7f which are correctly parsed by Int.parseInt(), but shouldn't appear in the text field.
A: javafx.scene.control.TextFormatter
Updated Apr 2016
This answer was created some years ago and the original answer is largely obsolete now.
Since Java 8u40, Java has a TextFormatter which is usually best for enforcing input of specific formats such as numerics on JavaFX TextFields:
*
*Numeric TextField for Integers in JavaFX 8 with TextFormatter and/or UnaryOperator
*Java 8 U40 TextFormatter (JavaFX) to restrict user input only for decimal number
*String with numbers and letters to double javafx
See also other answers to this question which specifically mention TextFormatter.
Original Answer
There are some examples of this in this gist, I have duplicated one of the examples below:
// helper text field subclass which restricts text input to a given range of natural int numbers
// and exposes the current numeric int value of the edit box as a value property.
class IntField extends TextField {
final private IntegerProperty value;
final private int minValue;
final private int maxValue;
// expose an integer value property for the text field.
public int getValue() { return value.getValue(); }
public void setValue(int newValue) { value.setValue(newValue); }
public IntegerProperty valueProperty() { return value; }
IntField(int minValue, int maxValue, int initialValue) {
if (minValue > maxValue)
throw new IllegalArgumentException(
"IntField min value " + minValue + " greater than max value " + maxValue
);
if (!((minValue <= initialValue) && (initialValue <= maxValue)))
throw new IllegalArgumentException(
"IntField initialValue " + initialValue + " not between " + minValue + " and " + maxValue
);
// initialize the field values.
this.minValue = minValue;
this.maxValue = maxValue;
value = new SimpleIntegerProperty(initialValue);
setText(initialValue + "");
final IntField intField = this;
// make sure the value property is clamped to the required range
// and update the field's text to be in sync with the value.
value.addListener(new ChangeListener<Number>() {
@Override public void changed(ObservableValue<? extends Number> observableValue, Number oldValue, Number newValue) {
if (newValue == null) {
intField.setText("");
} else {
if (newValue.intValue() < intField.minValue) {
value.setValue(intField.minValue);
return;
}
if (newValue.intValue() > intField.maxValue) {
value.setValue(intField.maxValue);
return;
}
if (newValue.intValue() == 0 && (textProperty().get() == null || "".equals(textProperty().get()))) {
// no action required, text property is already blank, we don't need to set it to 0.
} else {
intField.setText(newValue.toString());
}
}
}
});
// restrict key input to numerals.
this.addEventFilter(KeyEvent.KEY_TYPED, new EventHandler<KeyEvent>() {
@Override public void handle(KeyEvent keyEvent) {
if(intField.minValue<0) {
if (!"-0123456789".contains(keyEvent.getCharacter())) {
keyEvent.consume();
}
}
else {
if (!"0123456789".contains(keyEvent.getCharacter())) {
keyEvent.consume();
}
}
}
});
// ensure any entered values lie inside the required range.
this.textProperty().addListener(new ChangeListener<String>() {
@Override public void changed(ObservableValue<? extends String> observableValue, String oldValue, String newValue) {
if (newValue == null || "".equals(newValue) || (intField.minValue<0 && "-".equals(newValue))) {
value.setValue(0);
return;
}
final int intValue = Integer.parseInt(newValue);
if (intField.minValue > intValue || intValue > intField.maxValue) {
textProperty().setValue(oldValue);
}
value.set(Integer.parseInt(textProperty().get()));
}
});
}
}
A: I know this is a rather old thread, but for future readers here is another solution I found quite intuitive:
public class NumberTextField extends TextField
{
@Override
public void replaceText(int start, int end, String text)
{
if (validate(text))
{
super.replaceText(start, end, text);
}
}
@Override
public void replaceSelection(String text)
{
if (validate(text))
{
super.replaceSelection(text);
}
}
private boolean validate(String text)
{
return text.matches("[0-9]*");
}
}
Edit: Thanks none_ and SCBoy for your suggested improvements.
A: Starting with JavaFX 8u40, you can set a TextFormatter object on a text field:
UnaryOperator<Change> filter = change -> {
String text = change.getText();
if (text.matches("[0-9]*")) {
return change;
}
return null;
};
TextFormatter<String> textFormatter = new TextFormatter<>(filter);
fieldNport = new TextField();
fieldNport.setTextFormatter(textFormatter);
This avoids both subclassing and duplicate change events which you will get when you add a change listener to the text property and modify the text in that listener.
A: Try this simple code it will do the job.
DecimalFormat format = new DecimalFormat( "#.0" );
TextField field = new TextField();
field.setTextFormatter( new TextFormatter<>(c ->
{
if ( c.getControlNewText().isEmpty() )
{
return c;
}
ParsePosition parsePosition = new ParsePosition( 0 );
Object object = format.parse( c.getControlNewText(), parsePosition );
if ( object == null || parsePosition.getIndex() < c.getControlNewText().length() )
{
return null;
}
else
{
return c;
}
}));
A: The TextInput has a TextFormatter which can be used to format, convert and limit the types of text that can be input.
The TextFormatter has a filter which can be used to reject input. We need to set this to reject anything that's not a valid integer. It also has a converter which we need to set to convert the string value to an integer value which we can bind later on.
Lets create a reusable filter:
public class IntegerFilter implements UnaryOperator<TextFormatter.Change> {
private final static Pattern DIGIT_PATTERN = Pattern.compile("\\d*");
@Override
public Change apply(TextFormatter.Change aT) {
return DIGIT_PATTERN.matcher(aT.getText()).matches() ? aT : null;
}
}
The filter can do one of three things, it can return the change unmodified to accept it as it is, it can alter the change in some way it deems fit or it can return null to reject the change all together.
We will use the standard IntegerStringConverter as a converter.
Putting it all together we have:
TextField textField = ...;
TextFormatter<Integer> formatter = new TextFormatter<>(
new IntegerStringConverter(), // Standard converter form JavaFX
defaultValue,
new IntegerFilter());
formatter.valueProperty().bindBidirectional(myIntegerProperty);
textField.setTextFormatter(formatter);
If you want don't need a reusable filter you can do this fancy one-liner instead:
TextFormatter<Integer> formatter = new TextFormatter<>(
new IntegerStringConverter(),
defaultValue,
c -> Pattern.matches("\\d*", c.getText()) ? c : null );
A: This one worked for me.
public void RestrictNumbersOnly(TextField tf){
tf.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue,
String newValue) {
if (!newValue.matches("|[-\\+]?|[-\\+]?\\d+\\.?|[-\\+]?\\d+\\.?\\d+")){
tf.setText(oldValue);
}
}
});
}
A: If you want to apply the same listener to more than one TextField here is the simplest solution:
TextField txtMinPrice, txtMaxPrice = new TextField();
ChangeListener<String> forceNumberListener = (observable, oldValue, newValue) -> {
if (!newValue.matches("\\d*"))
((StringProperty) observable).set(oldValue);
};
txtMinPrice.textProperty().addListener(forceNumberListener);
txtMaxPrice.textProperty().addListener(forceNumberListener);
A: I don't like exceptions thus I used the matches function from String-Class
text.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue,
String newValue) {
if (newValue.matches("\\d*")) {
int value = Integer.parseInt(newValue);
} else {
text.setText(oldValue);
}
}
});
A: This method lets TextField to finish all processing (copy/paste/undo safe).
Does not require to extend classes and allows you to decide what to do with new text after every change
(to push it to logic, or turn back to previous value, or even to modify it).
// fired by every text property change
textField.textProperty().addListener(
(observable, oldValue, newValue) -> {
// Your validation rules, anything you like
// (! note 1 !) make sure that empty string (newValue.equals(""))
// or initial text is always valid
// to prevent inifinity cycle
// do whatever you want with newValue
// If newValue is not valid for your rules
((StringProperty)observable).setValue(oldValue);
// (! note 2 !) do not bind textProperty (textProperty().bind(someProperty))
// to anything in your code. TextProperty implementation
// of StringProperty in TextFieldControl
// will throw RuntimeException in this case on setValue(string) call.
// Or catch and handle this exception.
// If you want to change something in text
// When it is valid for you with some changes that can be automated.
// For example change it to upper case
((StringProperty)observable).setValue(newValue.toUpperCase());
}
);
For your case just add this logic inside. Works perfectly.
if (newValue.equals("")) return;
try {
Integer i = Integer.valueOf(newValue);
// do what you want with this i
} catch (Exception e) {
((StringProperty)observable).setValue(oldValue);
}
A: Here is a simple class that handles some basic validations on TextField, using TextFormatter introduced in JavaFX 8u40
EDIT:
(Code added regarding Floern's comment)
import java.text.DecimalFormatSymbols;
import java.util.regex.Pattern;
import javafx.beans.NamedArg;
import javafx.scene.control.TextFormatter;
import javafx.scene.control.TextFormatter.Change;
public class TextFieldValidator {
private static final String CURRENCY_SYMBOL = DecimalFormatSymbols.getInstance().getCurrencySymbol();
private static final char DECIMAL_SEPARATOR = DecimalFormatSymbols.getInstance().getDecimalSeparator();
private final Pattern INPUT_PATTERN;
public TextFieldValidator(@NamedArg("modus") ValidationModus modus, @NamedArg("countOf") int countOf) {
this(modus.createPattern(countOf));
}
public TextFieldValidator(@NamedArg("regex") String regex) {
this(Pattern.compile(regex));
}
public TextFieldValidator(Pattern inputPattern) {
INPUT_PATTERN = inputPattern;
}
public static TextFieldValidator maxFractionDigits(int countOf) {
return new TextFieldValidator(maxFractionPattern(countOf));
}
public static TextFieldValidator maxIntegers(int countOf) {
return new TextFieldValidator(maxIntegerPattern(countOf));
}
public static TextFieldValidator integersOnly() {
return new TextFieldValidator(integersOnlyPattern());
}
public TextFormatter<Object> getFormatter() {
return new TextFormatter<>(this::validateChange);
}
private Change validateChange(Change c) {
if (validate(c.getControlNewText())) {
return c;
}
return null;
}
public boolean validate(String input) {
return INPUT_PATTERN.matcher(input).matches();
}
private static Pattern maxFractionPattern(int countOf) {
return Pattern.compile("\\d*(\\" + DECIMAL_SEPARATOR + "\\d{0," + countOf + "})?");
}
private static Pattern maxCurrencyFractionPattern(int countOf) {
return Pattern.compile("^\\" + CURRENCY_SYMBOL + "?\\s?\\d*(\\" + DECIMAL_SEPARATOR + "\\d{0," + countOf + "})?\\s?\\" +
CURRENCY_SYMBOL + "?");
}
private static Pattern maxIntegerPattern(int countOf) {
return Pattern.compile("\\d{0," + countOf + "}");
}
private static Pattern integersOnlyPattern() {
return Pattern.compile("\\d*");
}
public enum ValidationModus {
MAX_CURRENCY_FRACTION_DIGITS {
@Override
public Pattern createPattern(int countOf) {
return maxCurrencyFractionPattern(countOf);
}
},
MAX_FRACTION_DIGITS {
@Override
public Pattern createPattern(int countOf) {
return maxFractionPattern(countOf);
}
},
MAX_INTEGERS {
@Override
public Pattern createPattern(int countOf) {
return maxIntegerPattern(countOf);
}
},
INTEGERS_ONLY {
@Override
public Pattern createPattern(int countOf) {
return integersOnlyPattern();
}
};
public abstract Pattern createPattern(int countOf);
}
}
You can use it like this:
textField.setTextFormatter(new TextFieldValidator(ValidationModus.INTEGERS_ONLY).getFormatter());
or you can instantiate it in a fxml file, and apply it to a customTextField with the according properties.
app.fxml:
<fx:define>
<TextFieldValidator fx:id="validator" modus="INTEGERS_ONLY"/>
</fx:define>
CustomTextField.class:
public class CustomTextField {
private TextField textField;
public CustomTextField(@NamedArg("validator") TextFieldValidator validator) {
this();
textField.setTextFormatter(validator.getFormatter());
}
}
Code on github
A: This is what I use:
private TextField textField;
textField.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
if(!newValue.matches("[0-9]*")){
textField.setText(oldValue);
}
}
});
The same in lambda notation would be:
private TextField textField;
textField.textProperty().addListener((observable, oldValue, newValue) -> {
if(!newValue.matches("[0-9]*")){
textField.setText(oldValue);
}
});
A: Very old thread, but this seems neater and strips out non-numeric characters if pasted.
// force the field to be numeric only
textField.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue,
String newValue) {
if (!newValue.matches("\\d*")) {
textField.setText(newValue.replaceAll("[^\\d]", ""));
}
}
});
A: Starting from Java SE 8u40, for such need you can use an "integer" Spinner allowing to safely select a valid integer by using the keyboard's up arrow/down arrow keys or the up arrow/down arrow provided buttons.
You can also define a min, a max and an initial value to limit the allowed values and an amount to increment or decrement by, per step.
For example
// Creates an integer spinner with 1 as min, 10 as max and 2 as initial value
Spinner<Integer> spinner1 = new Spinner<>(1, 10, 2);
// Creates an integer spinner with 0 as min, 100 as max and 10 as initial
// value and 10 as amount to increment or decrement by, per step
Spinner<Integer> spinner2 = new Spinner<>(0, 100, 10, 10);
Example of result with an "integer" spinner and a "double" spinner
A spinner is a single-line text field control that lets the user
select a number or an object value from an ordered sequence of such
values. Spinners typically provide a pair of tiny arrow buttons for
stepping through the elements of the sequence. The keyboard's up
arrow/down arrow keys also cycle through the elements. The user may
also be allowed to type a (legal) value directly into the spinner.
Although combo boxes provide similar functionality, spinners are
sometimes preferred because they don't require a drop-down list that
can obscure important data, and also because they allow for features
such as wrapping from the maximum value back to the minimum value
(e.g., from the largest positive integer to 0).
More details about the Spinner control
A: The preferred answer can be even smaller if you make use of Java 1.8 Lambdas
textfield.textProperty().addListener((observable, oldValue, newValue) -> {
if (newValue.matches("\\d*")) return;
textfield.setText(newValue.replaceAll("[^\\d]", ""));
});
A: Mmmm. I ran into that problem weeks ago. As the API doesn't provide a control to achieve that,
you may want to use your own one. I used something like:
public class IntegerBox extends TextBox {
public-init var value : Integer = 0;
protected function apply() {
try {
value = Integer.parseInt(text);
} catch (e : NumberFormatException) {}
text = "{value}";
}
override var focused = false on replace {apply()};
override var action = function () {apply()}
}
It's used the same way that a normal TextBox,
but has also a value attribute which stores the entered integer.
When the control looses the focus, it validates the value and reverts it (if isn't valid).
A: this Code Make your textField Accept only Number
textField.lengthProperty().addListener((observable, oldValue, newValue) -> {
if(newValue.intValue() > oldValue.intValue()){
char c = textField.getText().charAt(oldValue.intValue());
/** Check if the new character is the number or other's */
if( c > '9' || c < '0'){
/** if it's not number then just setText to previous one */
textField.setText(textField.getText().substring(0,textField.getText().length()-1));
}
}
});
A: This code works fine for me even if you try to copy/paste.
myTextField.textProperty().addListener((observable, oldValue, newValue) -> {
if (!newValue.matches("\\d*")) {
myTextField.setText(oldValue);
}
});
A: A little late, but if you also what to include decimals:
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
if (!newValue.matches("\\d{0,7}([\\.]\\d{0,4})?")) {
textField.setText(oldValue);
}
}
A: Another very simple solution would be:
TextField tf = new TextField();
tf.addEventFilter(KeyEvent.ANY, event -> {
if (!event.getCharacter().trim().matches("\\d?")) {
event.consume();
}
});
A: In recent updates of JavaFX, you have to set new text in Platform.runLater method just like this:
private void set_normal_number(TextField textField, String oldValue, String newValue) {
try {
int p = textField.getCaretPosition();
if (!newValue.matches("\\d*")) {
Platform.runLater(() -> {
textField.setText(newValue.replaceAll("[^\\d]", ""));
textField.positionCaret(p);
});
}
} catch (Exception e) {
}
}
It's a good idea to set caret position too.
A: I would like to improve Evan Knowles answer: https://stackoverflow.com/a/30796829/2628125
In my case I had class with handlers for UI Component part. Initialization:
this.dataText.textProperty().addListener((observable, oldValue, newValue) -> this.numericSanitization(observable, oldValue, newValue));
And the numbericSanitization method:
private synchronized void numericSanitization(ObservableValue<? extends String> observable, String oldValue, String newValue) {
final String allowedPattern = "\\d*";
if (!newValue.matches(allowedPattern)) {
this.dataText.setText(oldValue);
}
}
Keyword synchronized is added to prevent possible render lock issue in javafx if setText will be called before old one is finished execution. It is easy to reproduce if you will start typing wrong chars really fast.
Another advantage is that you keep only one pattern to match and just do rollback. It is better because you can easily abstragate solution for different sanitization patterns.
A: rate_text.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
String s="";
for(char c : newValue.toCharArray()){
if(((int)c >= 48 && (int)c <= 57 || (int)c == 46)){
s+=c;
}
}
rate_text.setText(s);
}
});
This works fine as it allows you to enter only integer value and decimal value (having ASCII code 46).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "101"
}
|
Q: Webview loading dialog My code below loads a progress dialogue into webview on the initial load but I'd like it to appear every time webview is loading a URL!
I think I need to use onpagestarted() before the progressbar but I'm a bit of a noob at all this and having trouble getting it working. Can anyone advise please?
//need to set progress bar condition here!
progressBar = ProgressDialog.show(MyActivity.this, "Loading title", "Loading...");
myWebView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
Log.i(TAG, "Finished loading URL: " +url);
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
});
//web site load
myWebView.loadUrl("http://www.google.com");
A: boolean loadingFinished = true;
boolean redirect = false;
mWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
if (!loadingFinished) {
redirect = true;
}
loadingFinished = false;
webView.loadUrl(urlNewString);
return true;
}
@Override
public void onPageStarted(WebView view, String url) {
loadingFinished = false;
//SHOW LOADING IF IT ISNT ALREADY VISIBLE
}
@Override
public void onPageFinished(WebView view, String url) {
if(!redirect){
loadingFinished = true;
}
if(loadingFinished && !redirect){
//HIDE LOADING IT HAS FINISHED
} else{
redirect = false;
}
}
});
As shown here: How to listen for a WebView finishing loading a URL?
A: You should use the onPageStarted() method to show the ProgressDialog:
myWebView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progressBar.show();
}
public void onPageFinished(WebView view, String url) {
progressBar.hide();
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Problem with MAX_FILE_SIZE in PHP I have a flex-based image upload form, and I've lost its source code. Now there appeared a problem with uploading big images (about 10MB), but with the same images an old html-based form works correctly. In my php-file there's
ini_set("post_max_size","64M");
ini_set("upload_max_filesize","64M");
Flex-based form returns file[error] = 2, that's MAX_FILE_SIZE error. It seems somewhere in flex there's an auto-generated field MAX_FILE_SIZE that it sends to server at the time it sends a file. I can't change this value in flex, so that's my question - is there a way to rewrite MAX_FILE_SIZE variable from php before php processes MAX_FILE_SIZE variable and generates error?
A: You can't change that values using ini_set that's probably the problem in the first place.
They can be set per directory so you can try to change their value in your .htaccess file
php_value upload_max_filesize 64M
php_value post_max_size 64M
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Problem with CSS transitions on a tags in Safari I'm having trouble with a -webkit-transition effect in a HTML page. The page is here:
http://www.newerawrestling.co.uk/new/
Basically, the colour of the links within the main sections (marked up in a <section> tag respectively) seem to be broken. They should be an off-white (#F5F5F5) and transition to a gold (#FFCC00) on hover, but they display as grey and flicker between both white and gold on hover but don't act as they should.
I've validated both the HTML and the CSS; the HTML passed with the CSS failed for containing CSS3 selectors and declarations (as far as could see) and I've inspected the links using Chrome's Web Inspector, but couldn't see any conflicting rules.
Has any one had this problem, or able to see where I've gone wrong?
A: Crap. As if by sod's law, I've just spotted the mistake after posting this question: I had a rule:
footer a:link, a:visited {
color: #999;
}
D'oh!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555571",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: android monkey runner scripts I was trying to run a a sample python program using monkey runner but unfortunately throwing an error of this type :
Can't open specified script file
Usage: monkeyrunner [options] SCRIPT_FILE
-s MonkeyServer IP Address.
-p MonkeyServer TCP Port.
-v MonkeyServer Logging level (ALL, FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE, OFF)
Exception in thread "main" java.lang.NullPointerException
so any one can guide me how to resolve this and how to use monkey runner to execute this type of things
A: I've found that making the path to the script absolute helped monkeyrunner.
I am invoking the runner from a Python script where a helper class has a startMonkey method:
def startMonkey(self, monkeyScript):
command = [ self.env + '\\tools\\monkeyrunner.bat' ]
command.append( os.path.abspath( monkeyScript ) )
return startProcess( command )
This seems to be working for me.
A: Script file should be a full path file name try below monkeyrunner c:\test_script\first.py
So go to the folder \ sdk \ tools
and press shift and right click to open command prompt and type monkeyrunner c:\test_script\python_file_name.py
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Sharing data between services and activities I have a ListView with a custom ArrayAdapter, that shows orders from an ArrayList. These orders are supposed to be synced with my server. There I have an API, which I am requesting for new orders, and if there are any, I get an XML of the order back. What is the best approach to dynamically update the listView? I do not want to use SQLite to store the orders, because only last ten are supposed to be displayed. With a ContentProvider I am not able to store my custom Order object. And if I wrap the ArrayList into a singleton class and use it in the service as well as in the Activity class for the ArrayAdapter, the ListView is not dynamically updated (probably, because the arrayAdapter makes a copy of the arraylist?). Thank you very much.
Filip
A: use Intent or Bundle
A: i'm no sure what you mean regarding the ArrayAdapter not being updated, but i can give you a solution we used in my company.
I have a DataMaanger which is a bridge between the Activities and the Networking or SQLite.
The dataMaanger keeps it's data in memory so it's not in DB or on disk. the disadvantage of it is if your app gets killed for lack of memory and reconstructs itself, the dataManager will be empty, which leaves you with two options, either on every Activitie's death or you main task's activities death you serialize your DataManager's data, or if you are not dependant on any previous data, just make arequest again and update the data manager.
I use broadcasts to notify my activities.
To get an access to the DataManager i don't use a sigletone. i use the Application object, you can extend it and in the Manifest.xml give it's name in the tag, then it will be used instead of the regualr Application object.
You can access it later by using getApplication() method in Activity class.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP & GD: Storing files created during session to then delete once session expires I am creating an online multi-layered GD image creation tool. Users can upload new images to the server to add to the GD produced image. I want to be able to store the gd image and all user uploaded files throughout the php session duration. The user can then choose to save these files permantly to their account but the default behaviour will be to delete the unused files after the session expires.
Does anyone have any pointers for me to explore?
Thanks
A: I see 2 possibilities here.
*
*Set a custom session handler which will define a garbage collection function to remove old images.
*Another easy solution would be to use a CRON. You run it every 10 minutes and delete old images.
Disadvantage of the first solution will be that sometimes a user will get a longer load time because your garbage collection ran.
Disadvantage of the 2nd solution is you may not have access to this on a non-dedicated server.
You can also combine both solutions. I would probably do that.
A: You don't get notified when a session expires. This just happens in the background. What you can do is have a task running in some sort of regular interval (let's say every hour) chat checks all files in the temporary directory and deletes all files that haven't been touched in a certain amount of time. filemtime() is your friend here.
A: I know this question is pretty old already, but I am working on a similar project at the moment and wanted to share my solution as reference for others.
What I do is that I upload the image, convert it to base64 (base64_encode()) and then save it in a session variable, so I can delete the original images from the disk again.
When you want to make GD Operations with it, you need to grab the saved session data, decode it (base64_decode()) and create an image object (imagecreatefromstring())
This is just a quick idea and it works for my application...
Heads Up!
base64-data can get a lot for big images, and the Session-Memory (memory_limit) is shared space with every other user on the page. So don't overdo this - because if a lot of people use your application at the same time, your memory_limit can exceed...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MediaPlay won't play a sound, why? Here's my code
MediaPlayer mp = new MediaPlayer();
...
try {
mp.setDataSource( getString(R.raw.click));
mp.prepare();
mp.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
yet strangely it give me
09-26 16:06:39.316: INFO/ActivityManager(110): Displayed Constructor.rob.com/.constr: +7s443ms
09-26 16:06:40.445: INFO/StagefrightPlayer(76): setDataSource('res/raw/click.mp3')
09-26 16:06:40.453: ERROR/MediaPlayer(21990): error (1, -2147483648)
09-26 16:06:40.457: WARN/System.err(21990): java.io.IOException: Prepare failed.: status=0x1
any ideas what might be wrong?
Thanks!
A: Add mp.reset() before mp.setDataSource().
EDIT: Wait, what are you doing with getString? You can't do that; to set a data source you need a FileDescriptor. Try this:
AssetFileDescriptor afd = getAssets().openRawResourceFd(R.raw.click);
mp.reset();
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mp.prepare();
mp.start();
A: Try this :
mp= MediaPlayer.create(context, R.raw.click);
mp.start();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555589",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Does Goertzel algorithm works over analog signal? My SIP phone is getting a tone(ringback) in regular rtp packet in PCMU payload (not using the rfc 2833 supported payload formats). To detect if tone or speech is present in rtp data Goertzel algorithm should be used. I am new to this domain and not able to understand how to provide input from received rtp packet to Goertzel algo? or does this algo takes analog signal as input?
A: Decode the PCMU to signed 16-bit linear PCM and pass each packet to the Goertzel algorithm.
Depending on the library you are using you may need to convert to unsigned or perhaps even float, but signed 16-bit is most likely.
Standard code to convert to signed 16-bit linear PCM can be found here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555601",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery.get the success parameter I am using jQuery.get to send a message to the server and it works.
I now want to action on the reply I get from jQuery.get and having no luck.
My simple test code to test it works is-
jQuery.get("/www", function(data){alert("it works");});
What do i have to be aware off to get the "success" to work
A: You are messing up in path I think
jQuery.get("/www/some_script_file", function(data){alert("it should works");});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: SQL Server table league I would like to build a table league from matches (scores and rounds).
I succceeded from my SQL Server database to calculate points for each teams and matches but I would like now to generate a table league.. (football)
Some one can help me please?
SELECT TOP (100) PERCENT dbo.jos_joomleague_matches.match_id, dbo.jos_joomleague_clubs.name AS Team, jos_joomleague_clubs_1.name AS Team2,
dbo.jos_joomleague_matches.match_date, dbo.jos_joomleague_matches.matchpart1_result, dbo.jos_joomleague_matches.matchpart2_result,
dbo.jos_joomleague_rounds.name,
CASE WHEN dbo.jos_joomleague_matches.matchpart1_result > dbo.jos_joomleague_matches.matchpart2_result THEN 3 WHEN dbo.jos_joomleague_matches.matchpart1_result
= dbo.jos_joomleague_matches.matchpart2_result THEN 1 ELSE 0 END AS ptsclub1HOME,
CASE WHEN dbo.jos_joomleague_matches.matchpart2_result > dbo.jos_joomleague_matches.matchpart1_result THEN 3 WHEN dbo.jos_joomleague_matches.matchpart2_result
= dbo.jos_joomleague_matches.matchpart1_result THEN 1 ELSE 0 END AS ptsclub2AWAY
FROM dbo.jos_joomleague_rounds INNER JOIN
dbo.jos_joomleague_clubs AS jos_joomleague_clubs_1 INNER JOIN
dbo.jos_joomleague_matches INNER JOIN
dbo.jos_joomleague_clubs ON dbo.jos_joomleague_matches.matchpart1 = dbo.jos_joomleague_clubs.id ON
jos_joomleague_clubs_1.id = dbo.jos_joomleague_matches.matchpart2 ON dbo.jos_joomleague_rounds.id = dbo.jos_joomleague_matches.round_id
ORDER BY dbo.jos_joomleague_matches.match_date
`
A: Start with an natural language description of your problem before you create tables. Think about the relationships:
A league has many teams. A match has two teams that play on a given date and has a specific outcome.
I see three tables: league, team, and match. Start with those.
You're premature if you're thinking about queries already. Get the basic table structure right first.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-5"
}
|
Q: MEF - notify when plugins are loaded / unloaded I have a simple asp mvc app which uses MEF, and there is a route which can be accessed by admins to refresh the directory catalog and compose parts, however one thing I am trying to find out how to do is notify some code when a plugin is loaded / unloaded.
The scenario is that when plugins are loaded they register the routes they need, however when they are unloaded I need them to unload their routes, as subsequent refreshes try to re-register the routes and it bombs.
Are there any events which I can hook into from the MEF objects?
The plugin container is something like:
[ImportMany(typeof(ISomePluginInterface))]
IEnumerable<ISomePluginInterface> Plugins {get; private set;}
Each ISomePluginInterface has something like:
public interface ISomePluginInterface
{
public void PluginLoaded();
public void PluginUnloaded();
}
A: This is similar in theory to this Stackoverflow question and this was my answer. In your case, you have a similar need, you want to fire an event when the plugin is started, and clean up when it is no longer needed.
Using the same concept, you can use the InterceptingCatalog to register routes, but I wouldn't make it an explicit part of the interface definition to do so, instead, you need to look at how your components fit together as a whole, e.g., if the operations for registering routes won't be used for all plugins, what is the purpose of them existing in the interface definition. You could break out the route registration into a separate interface, the IRouteRegistrar, and use intercepting strategies to automatically call the appropriate registration method when the plugin is used for the first time, e.g., I could break out the interface into:
public interface IPlugin
{
void SomeOperation();
}
public interface IRouteRegistrar : IDisposable
{
void RegisterRoutes();
}
The latter interface does the work of registering routes, and we use the Dispose pattern to ensure that it is cleaned up after it is finished with. Therefore, A sample plugin could resemble:
[Export(typeof(IPlugin))]
public class MyPlugin : IPlugin, IRouteRegistrar
{
public void SomeOperation() { }
public void RegisterRoutes()
{
// Register routes here...
}
protected virtual Dispose(bool disposing)
{
if (disposing)
{
// Unregister routes here...
}
}
void IDisposable.Dispose()
{
Dispose(true);
}
}
I only export as an IPlugin, but I ensure my plugin also implements the IRouteRegistrar. The way we use that, is with a strategy:
public class RouteRegistrarStrategy : IExportedValueInteceptor
{
public object Intercept(object value)
{
var registrar = value as IRouteRegistrar;
if (registrar != null)
registrar.RegisterRoutes();
return value;
}
}
Now, only if the plugin supports that interface will it register routes. This also enables you to apply the route registration interface to other plugins which could be used in a different way. You gain a bit more flexibility. To use that strategy in code, you need to add the MefContrib project to your app, and do a little more wire up:
var catalog = new DirectoryCatalog(".\bin");
var config = new InterceptionConfiguration().AddInterceptor(new RouteRegistrarStrategy());
var interceptingCatalog = new InterceptingCatalog(catalog, configuration);
var container = new CompositionContainer(interceptingCatalog);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555612",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Calling a function with incremented values If I call a function like this:
var n = 0; f(n, n += 100)
the values of it's arguments are 0 and 100, not 100 and 100 as I would have expected. This behavior does what I currently need in my program but I don't understand why it works this way and it troubles me.
Can someone explain why it happens so and whether it's safe to pass arguments like this?
A: The first parameter value is evaluated before the second one.
A: Unlike C (and like Java), Javascript does in fact have a defined order of argument evaluation: left-to-right. So, somewhat surprisingly, it is safe to write the code as you have. However, I would consider it very poor style and in fact almost unreadable since not many people know off the top of their heads whether the evaluation order is in fact defined (case in point: I had to look it up to answer this question).
Edit: See section 11.2.4 http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
A: The variable n is a primitive type in JavaScript (the primitive types include numbers, string, and boolean values). Primitive types are passed by value, explaining the behavior you observed. If n were a non-primitive type, it would be passed by reference and any modifications made to it would be reflected in all references to n.
See JavaScript: Passing by Value or by Reference for additional information.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Highlight the searched text in UITableView using UISearchBar Using UISearchBar searching text in UITableView. I just want to know how to highlight searched text. Highlighting could be make text bold or change text color.
E.g. If I'm searching text "Stack" using UISearchBar in UITableView which contains a row with string "Stackoverflow", now my search result should appear this way "Stackoverflow".
Thanks in advance..
Happy coding..
A: Usually it's enough to filter cells in UITableView conforming your search term. Hope you understand how that could be arranged. If you want highlight search term in a cell, your cell needs to support such highlight, than you could highlight calling something like [mycell highlightText:searchBar.text]. Ready cells don't support such highlight, you need to build your custom cell which will do that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Calling batch file from code I'm attempting to call a batch file in code. I run it when the program starts and then every 10 minutes ( for testing purposes ). However, when the function is called through the timer it takes about 5 minutes to process it, but when I do it through start up it only takes 30 seconds.Its copying images from point A to point B on the local computer. The amount to be copied is 400 files or so.
net use t: "image source" /persistent:yes
xcopy t: "c:\images" /C /Q /I /Y
net use /delete t:
Here is the code for the batch file.Doing net use because of problems with permissions
System.Diagnostics.ProcessStartInfo p = new ProcessStartInfo(@"c:\getDiscImages.bat");
System.Diagnostics.Process proc = new Process();`
p.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo = p;
proc.Start();
proc.WaitForExit();
This is the code in c#. It works its just a tad bit slow. Any help is greatly appreciated as always.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Java Generics. Why does it compile? abstract class Type<K extends Number> {
abstract <K> void use1(Type<K> k); // Compiler error (Type parameter K is not within its bounds)
abstract <K> void use2(Type<? extends K> k); // fine
abstract <K> void use3(Type<? super K> k); // fine
}
The method generic type K shadows the class generic type K, so <K> doesn't match <K extends Number> in use1().The compiler doesn't know anything usefull about new generic type <K> in use2() and use3() but it is still legal to compile . Why <? extends K> (or <? super K>) match <K extends Number>?
A: The problem you have is that There are two K types. It may be clearer if you rename one.
abstract class Type<N extends Number> {
abstract <K extends Number> void use1(Type<K> k); // fine
abstract <K> void use2(Type<? extends K> k); // fine
abstract <K> void use3(Type<? super K> k); // fine
}
There are cases where you have to provide duplicate information the compiler can infer, and other places where you don't. In Java 7 it has added a <> diamond notation to tell the compiler to infer types it didn't previously.
To illustrate what I mean. Here is different ways to create an instance of a generic class. Some requires the type be given twice, others only once. The compiler can infer the type.
In general, Java doesn't infer types when it might do in most other languages.
class Type<N extends Number> {
private final Class<N> nClass;
Type(Class<N> nClass) {
this.nClass = nClass;
}
static <N extends Number> Type<N> create(Class<N> nClass) {
return new Type<N>(nClass);
}
static void main(String... args) {
// N type is required.
Type<Integer> t1 = new Type<Integer>(Integer.class);
// N type inferred in Java 7.
Type<Integer> t2 = new Type<>(Integer.class);
// type is optional
Type<Integer> t3 = Type.<Integer>create(Integer.class);
// type is inferred
Type<Integer> t4 = create(Integer.class);
}
A: When you define the method like this:
abstract <K> void use1(Type<K> k);
You're effectively hiding the type K in your class definition. You should be able to define the methods like this:
abstract void use1(Type<K> k);
A: First of all, let's rewrite it to avoid shadowing:
abstract class Type<N extends Number> {
abstract <K> void use1(Type<K> k);
abstract <K> void use2(Type<? extends K> k);
abstract <K> void use3(Type<? super K> k);
}
In the first method K acts as a type parameter of Type<N extends Number>, thus its value sould comply to the bound of Type's N. However, method declaration doesn't have any restrictions on value of K, therefore it's not legal. It would be legal if you add a necessary restriction on K:
abstract <K extends Number> void use1(Type<K> k);
In the following methods, the actual type parameter of Type is unknown (?), and K imposes additional bound on it, so that there is nothing illegal in these declarations.
Here is a more practical example with the similar declarations:
class MyList<N extends Number> extends ArrayList<N> {}
<K> void add1(MyList<K> a, K b) {
a.add(b); // Given the method declaration, this line is legal, but it
// violates type safety, since object of an arbitrary type K can be
// added to a list that expects Numbers
// Thus, declaration of this method is illegal
}
<K> void add2(MyList<? extends K> a, K b) {
// a.add(b) would be illegal inside this method, so that there is no way
// to violate type safety here, therefore declaration of this method is legal
}
<K> void add3(MyLisy<? super K> a, K b) {
a.add(b); // This line is legal, but it cannot violate type safey, since
// you cannot pass a list that doesn't expect K into this method
}
A: This is a gray area; javac 7 and 6 disagree; JLS3 is outdated; no idea where's the new spec.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: If just the index.php loads as its generic unparsed self, what exactly is [not] happening? I visited a client's site today, and I'm getting the actual content of their index.php file itself rather than their website. The function of the index.php file says:
This file loads and executes the parser. *
Assuming this is not happening, what would be some common reasons for that?
A: If the apache and php are configured correctly, so that .php files go through the php interpreter, the thing I would check is whether the php files are using short open tags "<?"
instead of standard "<?php" open tags. By default newer php versions are configured to not accept short tags as this feature is deprecated now. If this is the case, look for "short_open_tag" line in php.ini and set it to "on" or, preferrably and if time allows, change the tags in the code. Although the second option is better in the long run, it can be time consumming and error-prone if done manually.
I have done such a thing in the past with a site-wide find/replace operation and the general way is this.
*
*Find all "<?=" and replace with "~|~|~|~|" or some other unusual string that is extremely unlikely to turn up in real code.
*Find all "<?php" and replace with "$#$#$#"
*Find all "<?" in the site and replace with "$#$#$#"
*Find all "$#$#$#" and replace with "<?php " The trailing space is advised
*Find all "~|~|~|~|" and replace with "<?php echo " The trailing space is neccessary
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Predefining list capacity To prevent many re-allocations I have something like this in my code:
List<T> result = new List<T>(100);
Do I need to call TrimExcess before I return the new list or not?
result.TrimExcess();
return result;
The aim is to make the allocations quicker for the first 100 items, for example. Is this the correct way of doing this or do I need to do anything else?
A: You do not need to trim. The list keeps track of how many items have actually been added, which is different than the initial capacity, which is simply a pre-allocation.
A: its ok ..
if you dont intend to add more items then you can leave it like you wrote.
A: If your application is using a lot of memory or more than it should then I would call TrimExcess() but it's probably not worth it unless the list contains very little items like less than 30 or so, even then you probably can just leave it as is. But yes if you want allocation to be faster for the first 100 then make the initial size 100 or even larger if you know you're going to be adding more than 100 items.
A: By defining the initail capacity, you did the necessary optimization.
If you the call the TrimExcess() method you might cause more allocation work than you really want.
The MSDN documentation for TrimExcess() says:
The cost of reallocating and copying a large List can be
considerable, however, so the TrimExcess method does nothing if the
list is at more than 90 percent of capacity
What I understand of this is that you might not even change anything on your list with that call.
This looks to me that you really do not gain much with it.
A: Let's make it clear, doing so will not reserve memory for allocation of 100 T but just for 100 'pointer' to T. So it is ok but probably does not help a lot.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555633",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Directory Separators Ignored on Inserting into mySQL I have been trying to insert a directory Path into a mySQL table (reportPath column). The inserting works OK but the directory separator is ignored on insert. E.g A path of D:\public_html\Testman\config is inserted as D:public_htmlTestmanconfig. What am I missing?
Below is my code
<?php
include "config.php" ;
$dir = "csvreports";
$files = scandir($dir);
$fLocation=dirname(__FILE__).DIRECTORY_SEPARATOR;
foreach ($files as $key => $value)
{
if (substr($value, -4) == ".CSV" )
{
mysql_query("INSERT INTO tableReports (reportPath, reportName) VALUES('$fLocation.$value','$value')");
}
}
?>
A: You forgot to escape the slashes:
$sql = sprintf("INSERT INTO tableReports (reportPath, reportName) VALUES('%s','%s')",
mysql_real_escape_string($fLocation.$value),
mysql_real_escape_string($value)
);
mysql_query($sql);
A: Escape the data before inserting it into the database: mysql_real_escape_string
mysql_query("
INSERT INTO tableReports (reportPath, reportName)
VALUES(
'". mysql_real_escape_string($fLocation.$value) ."',
'". mysql_real_escape_string($value) ."'
)
");
A: When using Windows, the DIRECTORY_SEPARATOR is set to \ (backslash). But backslash is a special character in PHP, which causes PHP to interpret the next subsequent character as a special character (a character with another meaning). So you can use addslashes() to escape the backslash characters.
However, you'd better use mysql_real_escape_string().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555637",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Drawing text with transparent background I use code like below to update text (in a bitmap) dynamically into a texture:
public void UpdateTexture(GL10 gl, int x, int y, int textureId, Bitmap bitmap)
{
gl.glBindTexture(GL10.GL_TEXTURE_2D, textureId);
GLUtils.texSubImage2D(GL10.GL_TEXTURE_2D, 0, x, y, bitmap);
}
The problem is that texSubImage2D function does not completely replace the existing pixels in the texture but it keeps the existing information and draws the new bitmap over it. And because the new bitmap has transparent pixels the old bitmap is displayed underneath it when the texture is rendered. Is there a way to completely erase the old information from the target area from the texture before texSubImage2D call?
A: The answer is quite simple. Your drawing a new texture over the old one which is the desired behavior (since you would want to create a texture out of combinitions).
You should delete the old texture first (quote from this doc).
Cleaning Up Texture Objects
As you bind and unbind texture objects, their data still sits around somewhere among your texture resources. If texture resources are limited, deleting textures may be one way to free up resources.
void glDeleteTextures(GLsizei n, const GLuint *textureNames):
Deletes n texture objects, named by elements in the array textureNames. The freed texture names may now be reused (for example, by glGenTextures()).
If a texture that is currently bound is deleted, the binding reverts to the default texture, as if glBindTexture() were called with zero for the value of textureName. Attempts to delete nonexistent texture names or the texture name of zero are ignored without generating an error.
A: There was actually a bug elsewhere in the code.
texSubImage2D actually replaces all the texture data in the given region. The drawing of the new texture over the old one was occurring on the bitmap/canvas side.
canvas.drawColor() call was used by mistake to clear the bitmap when bitmap.eraseColor() should have been used.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: EF - Cascade Delete Not Working, Can't Delete Object I get this error:
System.Data.SqlClient.SqlException The DELETE statement conflicted
with the REFERENCE constraint "FK_comments_postId__164452B1". The
conflict occurred in database "awe", table "dbo.comments", column
'postId'. The statement has been terminated.
I have this structure:
public class Post
{
public long Id { get; set; }
public string Body { get; set; }
public long? ParentId { get; set; }
public virtual Post Parent { get; set; }
public virtual ICollection<Post> Posts { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
public class Comment
{
public long Id { get; set; }
public long PostId { get; set; }
public virtual Post Post { get; set; }
public string Body { get; set; }
}
my delete method:
public void Delete(long id)
{
var p = context.Set<Post>().Get(id);
if(p == null) throw new MyEx("this post doesn't exist");
if (p.Posts.Count > 0) throw new MyEx("this post has children and it cannot be deleted");
context.Set<Post>().Remove(p);
context.SaveChanges();
}
my DbContext:
public class Db : DbContext
{
public DbSet<Post> Posts { get; set; }
public DbSet<Comment> Comments { get; set; }
}
A: It sounds like the Post that you are trying to delete has child Comments.
Entity Framework will not take responsibility for cascading a delete in the database – it expects that you will achieve this by setting a cascading delete on the foreign key relationship in the RDBMS.
Having said this, if you delete a parent entity in Entity Framework, it will attempt to issue delete statements for any child entities which have been loaded into the current DbContext, but it will not initialize any child entities which have not yet been loaded. This may lead to the RDBMS throwing foreign key constraint violation exceptions if a cascading delete has not been specified, like the one you are seeing. For more details about how cascade delete “works” in Entity Framework, see this blog post.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: HibernateOptimisticLockingFailureException while updating an object I am getting following exception while updating an object.
HibernateOptimisticLockingFailureException: Object of class [User]
with identifier [25614]: optimistic locking failed; nested exception
is org.hibernate.StaleObjectStateException: Row was updated or deleted
by another transaction (or unsaved-value mapping was incorrect):
[User#25614]
Situation :- Reason why i am facing this error is that I have a form where users are displayed and I have two buttons there one for updating the password and one for editing the detail of the users. when I click on updating the password then it just query the object and updates its password and keep the object in hibernate session. And then I click on edit button and modify the information and then save it then it gives upper mentioned exception because the object, that I am trying to save, is not hibernate session object but an object with same identifier was queried by hibernate while updating the password. Now I have two objects with same identifier one is in hibernate session and another is not persisted (not detached object) yet. I want to update save the changes from not persisted object into the database but because there is an object with same identifier is in hibernate session so hibernate gives an exception.
How I can merge changes from not persisted objects to persisted one?
A: The answer is in the question: when changing the password in the first transaction, the version field of the user entity is updated, but you keep an obsolete version of your user object in the HTTP session and try to update the user with this obsolete version in a second transaction.
Just make sure to refresh the user object you keep in the HTTP session each time the password is changed.
You might also manually copy each property of the modified user to the attached user object, but then you wouldn't benefit from optimistic locking anymore.
// first transaction:
User refreshedUser = userService.updateUserPassword(userId, newPassword);
request.getSession().setAttribute("user", refreshedUser);
// ...
// second transaction:
User modifiedUser = (User) request.getSession().getAttribute("user");
modifiedUser = userService.updateUser(modifiedUser);
request.getSession().setAttribute("user", modifiedUser);
A: I was facing the same issue and found the record I am deleting was having a foreign key associated and it was deleting all related entries from another table and in the second transaction I have to update the record on another table. So this might be also I use case of the "HibernateOptimisticLockingFailureException while updating an object"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Any way to unfriend or delete a friend using Facebook's PHP SDK or API? I want to be able to authenticate the user, list out all their friends and give them the ability to unfriend / remove some of those friends with without going through the process on the Facebook.com website.
Is this possible via the API?
A: There is no API available to add or remove friends programmatically.
What is available is a dialog box your app can use to help users send friend requests, but this still requires direct user interaction
A: Currently no way to remove friends programmatically but fb's mobile design can be easily manipulated by a php spider.
A: What you can do its create a popup to m.facebook/userid for each friend.
When the user clicks on a friend the popup opens and there they can unfriend that person, that is a few clicks and its totally allowed by facebook.
<a href="http://m.facebook.com/userid"
onClick="window.open(this.href, this.target, 'width=500,height=600');
return false;">
Friend Name</a>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Why doesn't the diamond operator work within a addAll() call in Java 7? Given this example from the generics tutorial.
List<String> list = new ArrayList<>();
list.add("A");
// The following statement should fail since addAll expects
// Collection<? extends String>
list.addAll(new ArrayList<>());
Why does the last line not compile, when it seems it should compile. The first line uses a very similar construct and compiles without a problem.
Please explain elaborately.
A: First of all: unless you're using Java 7 all of this will not work, because the diamond <> has only been introduced in that Java version.
Also, this answer assumes that the reader understands the basics of generics. If you don't, then read the other parts of the tutorial and come back when you understand those.
The diamond is actually a shortcut for not having to repeat the generic type information when the compiler could find out the type on its own.
The most common use case is when a variable is defined in the same line it's initialized:
List<String> list = new ArrayList<>(); // is a shortcut for
List<String> list = new ArrayList<String>();
In this example the difference isn't major, but once you get to Map<String, ThreadLocal<Collection<Map<String,String>>>> it'll be a major enhancement (note: I don't encourage actually using such constructs!).
The problem is that the rules only go that far. In the example above it's pretty obvious what type should be used and both the compiler and the developer agree.
On this line:
list.addAll(new ArrayList<>());
it seems to be obvious. At least the developer knows that the type should be String.
However, looking at the definition of Collection.addAll() we see the parameter type to be Collection<? extends E>.
It means that addAll accepts any collection that contains objects of any unknown type that extends the type of our list. That's good because it means you can addAll a List<Integer> to a List<Number>, but it makes our type inference trickier.
In fact it makes the type-inference not work within the rules currently laid out by the JLS. In some situations it could be argued that the rules could be extended to work, but the current rules imply don't do it.
A: The explanation from the Type Inference documentation seems to answer this question directly ( unless I'm missing something else ).
Java SE 7 and later support limited type inference for generic instance creation; you can only use type inference if the parameterized type of the constructor is obvious from the context. For example, the following example does not compile:
List<String> list = new ArrayList<>();
list.add("A");
// The following statement should fail since addAll expects
// Collection<? extends String>
list.addAll(new ArrayList<>());
Note that the diamond often works in method calls; however, for greater clarity, it is suggested that you use the diamond primarily to initialize a variable where it is declared.
In comparison, the following example compiles:
// The following statements compile:
List<? extends String> list2 = new ArrayList<>();
list.addAll(list2);
A: When compiling a method invocation, javac needs to know the type of the arguments first, before determining which method signature matches them. So the method parameter type isn't known before the argument type is known.
Maybe this can be improved; as of today, the type of the argument is independent of the context.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: JQuery Mobile select menu change event fires multiple times I have a JQuery Mobile Multi-Page layout and I want to trigger a function when a select menu on my site is changed.
Currently when the menu is changed three events fire.
I have put together an example that should show you what i'm facing.
*
*From the main menu click Web Settings
*Change the Theme option on the page
Notice the three alerts
Here is my code to register the event
$(document).bind("pagecreate", function() {
$("#settings-theme").bind("change", function(event) {
alert(event.target);
});
});
Things I have tried:
*
*Changing the data-native-menu="false" to true removed one of the event firings.
*Removed all other pages except web settings and that also reduced the number of events firing to two.
*In JSFiddle, Framework Options > Head (nowrap) changed to DomReady also removed a event fire.
Update
It appears that pagecreate is fired every time a page is 'first-viewed' as well as twice when the homepage is loaded.
So by the time the settings page is loaded the event has been binded three times.. still no solution.
A: $(document).bind("ready", function() {
$("#settings-theme").live("change", function() {
alert("changed");
});
});
or
$(document).bind("ready", function() {
$("#pg-settings").delegate("#settings-theme", "change", function() {
alert("changed");
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PK Violation on a history table This is in SQL Server 2005.
I have an address table:
dbo.Address
(
AddressID INT IDENTITY(1, 1) PRIMARY KEY
LastUpdateBy VARCHAR(30)
<bunch of address columns>
)
I also have a history table:
dbo.AddressHistory
(
AddressID INT,
AsOf DATETIME,
UpdateBy VARCHAR(30)
<all the address columns>
CONSTRAINT PK_dbo_AddressHistory PRIMARY KEY CLUSTERED (AddressID, AsOf)
)
I have a trigger on dbo.Address to create history entries on both INSERT and UPDATE which will basically do this:
INSERT INTO dbo.AddressHistory(AddressID, AsOf, UpdateBy, <address columns>)
SELECT AddressID, CURRENT_TIMESTAMP, @UpdateBy, <address columns>
FROM INSERTED
But, every once in while, I'll get a PK violation on dbo.AddressHistory complaining about a duplicate PK being inserted. How is this possible if part of the PK for AddressHistory is the current timestamp of the insertion?
Even executing this will insert two rows into the history table successfully:
INSERT INTO dbo.Address
(LastUpdateBy, <address columns>)
SELECT 'test', <address columns>
FROM dbo.Address
WHERE AddressID < 3
And the only update sproc I have for the dbo.Address table will update a row for a given AddressID. So it should only be updating one row at a time. My insert sproc only inserts one row at a time as well.
Any idea what conditions cause this to occur?
A: Based on your description two concurrent executions of the stored procedure with the same parameter would seem likely.
datetime only has a precision of 1/300 second so conflicts can occur if these executions happen very close together.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555654",
"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.