text
stringlengths 8
267k
| meta
dict |
---|---|
Q: How to select user input from a shell script in PHP? I've this shell script running from a PHP site.
In the shell script (Audit shell script),
I have 3 options:
1) Process script
2) Display results
3) Exit
Tried the codes below and doesn't seem to work, the PHP site displayed blanks.
<?php
session_start();
exec('/Desktop/test.sh');
exec('1');
$output = exec('2');
echo "<pre>$output</pre>";
?>
Any help will be greatly appreciated.
A: <?php
session_start();
// This line executes '/Desktop/test.sh' as if it had been called from the
// command line
// exec('/Desktop/test.sh');
// This line attempts to execute a file called '1', which would have to be
// in the same directory as this script
// exec('1');
// This line attempts to execute a file called '2', which would have to be
// in the same directory as this script, and capture the first line of the
// output in $output
// $output = exec('2');
// I think you want to be doing something more like this - this executes the
// shell script, passing "1" and "2" as arguments, and captures the whole
// output as an array in $output
exec('/Desktop/test.sh "1" "2"', $output);
// Loop the output array and echo it to the browser
echo "<pre>";
foreach ($output as $lineno => $line) echo "Line $lineno: $line\n";
echo "</pre>";
?>
It seems to me that you could do with reading the manual page for exec() properly...
A: Try using proc_open instead of exec; it gives you more control of process input/output. Something like:
<?php
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("file", "/dev/null", "a") // stderr is a file to write to
);
$cwd = '/Desktop';
$env = array();
$process = proc_open('/Desktop/test.sh', $descriptorspec, $pipes, $cwd, $env);
if (is_resource($process)) {
// $pipes now looks like this:
// 0 => writeable handle connected to child stdin
// 1 => readable handle connected to child stdout
// Any error output will be sent to /dev/null (ie, discarded)
fwrite($pipes[0], "1\n");
fwrite($pipes[0], "2\n");
fclose($pipes[0]);
$output = stream_get_contents($pipes[1]);
fclose($pipes[1]);
// It is important that you close any pipes before calling
// proc_close in order to avoid a deadlock
$return_value = proc_close($process);
echo $output;
}
?>
Note: I've lifted this code from the PHP Manual's proc_open page
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633453",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to let user to input just once using asp.net? i have a question here about asp.net
how to let user to change their ID only once after they make changes and submit and when they login again they could not make changes to their ID? However they can modify their other personal details.
how this can be done??
and how's it is like that shows the user already make changes and already submit one time and cannot make changes for second time?
A: Make the user id control readonly.
tbusername.Enabled = false;
//OR
tbusername.ReadOnly = true;
A: If you're saying that they can enter an ID when they're registering, but cannot change it afterwards, then simply disable the field in the edit form/control.
If they are allowed to change their ID only once after registering, just create a flag in the database and set it accordingly the first time the ID is updated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Date in IST in SQL Server My server is hosted in US or so with some other time zone. Is there an option to get the current date in SQL Server in Indian Standard Time.
select getdate()
What should I write to get the current time in India(or some other country as such).
A: You should use the DATETIMEOFFSET datatype which includes the timezone, and the SWITCHOFFSET method to switch between timezones. Also: to get the current time, use SYSDATETIMEOFFSET() instead of GETDATE()
-- gets current date/time in the current timezone
SELECT
SYSDATETIMEOFFSET()
-- get the current date/time in your preferred timezone +05:30 UTC being Indian Std. Time
SELECT
SWITCHOFFSET(SYSDATETIMEOFFSET(), '+05:30')
A: According to this link India's time is 9:30 hours ahead from US. So in-order to get the Indian time, you need to add 9.30 hours to US time.
SELECT DATEADD(hh,9.30,getdate())
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Jquery Filter showing erratic results I'm trying to set up a filter using jQuery. I'll have a certain amount of divs, each with a numeric value (let's say price).
The code below works fine, until you enter a value less than 10. Then you get results that shouldnt be there. (enter 4 for example)
Any help on fixing this would be great! thanks!
http://jsfiddle.net/SUWxn/
<script>
function sortmebaby()
{
var divList = $('#containerMonkey div[id^="monkey_"]');
$.each(divList, function(index, value)
{
console.log($(value).attr('xprice'));
if ( $(value).attr('xprice') > $('#mankipower').val())
$(value).hide();
else
$(value).show();
//alert(index + ': ' + value);
});
}
</script>
<div id="containerMonkey">
<div id="monkey_1" xprice="10">10</div>
<div id="monkey_2" xprice="20">20</div>
<div id="monkey_3" xprice="30">30</div>
<div id="monkey_4" xprice="40">40</div>
<div id="monkey_5" xprice="50">50</div>
</div>
<input type="text" name="mankipower" id="mankipower">
<input type="button" value="PUSH" onclick="sortmebaby()">
Thanks!
A: The condition in your if statement is comparing strings, not integers as you're expecting. You can use parseInt to convert the strings to numbers:
var val1 = parseInt($(value).attr('xprice'), 10),
val2 = parseInt($('#mankipower').val(), 10);
if(val1 > val2)
$(value).hide();
else
$(value).show();
Here's an updated example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: rails password update validation issue I have the following validation:
validates :password, :presence => true, :confirmation => true, :length => { :within => 6..40 }, :format => { :with => pass_regex }, :unless => :nopass?
Then, when I try to update without password (nopass? is true) the following errors appear:
There were problems with the following fields:
Password is too short (minimum is 6 characters)
Password is invalid
Notice that the :unless works on :presence and :confirmation but not in :lenght or :format.
How could I fix this?
A: I've had some strange issues with the :confirmation flag as well, which I never figured out, but that's how I solved the problem in my Rails 3.0.x app:
attr_accessor :password_confirmation
validates :password, :presence => true, :length => {:within => PASSWORD_MIN_LENGTH..PASSWORD_MAX_LENGTH}
validate :password_is_confirmed
def password_is_confirmed
if password_changed? # don't trigger that validation every time we save/update attributes
errors.add(:password_confirmation, "can't be blank") if password_confirmation.blank?
errors.add(:password_confirmation, "doesn't match first password") if password != password_confirmation
end
end
I realise this is not an explanation why your code isn't working, but if you're looking for a quick temporary fix - I hope this will help.
A: You might use conditional validations
class Person < ActiveRecord::Base
validates :surname, :presence => true, :if => "name.nil?"
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633460",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MYSQL Cluster (NDB) versus MongoDB How does MYSQL Cluster (NDB) compare against MongoDB? It seems that while both NDB and Mongo supports scale out over commodity machine nodes, NDB also provides all the relational capabilities such as JOINs, transactions, etc...
Therefore, under what situations would one choose Mongo over NDB?
A: Even though MYSQL Cluster NDB is a shared-nothing approach that scales a relational database across commodity machines, there are limitations and impacts to performance. You can read the full details at the link below, but some of the more important features are just not supported in NDB, such a foreign keys, which may make you question why you would cluster a RDBMS in the first place if you have to give up some of the features you're expecting to leverage.
18.1.5.1 Differences Between the NDB and InnoDB Storage Engines
What are the limitations of implementing MySQL NDB Cluster?
I come from a relational background, and things like MongoDB did not initially click with me, but after tinkering with it for a few weeks, I was surprised at how much is possible while not being subject to traditional schema guidelines and transactional overhead that comes with relational databases. If you really want true, horizontal scalability and are willing to give up the luxury of joins and foreign keys, you should seriously consider using Mongo or something similar that falls under the NoSQL category.
A: If you want to keep your sql/ relational database structure then go with NDB.
If you want to build data that is a little more heirarchial in structure you should go with mongodb.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633464",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: how can i delete dynamic elements from My html page using Jquery? I have my code here
http://jsfiddle.net/NT4Zr/5/
In above code i am able to add new row but cant delete added row by clicking Delete link.
How can i do that?
In hobbies section i want to add hobbies by writing into text box and add hobby button and it should be reflected to label
<label>Your Hobbies:</label>
and by clicking delete button it should be deleted.
How can i do that?
Please refer this link
http://jsfiddle.net/NT4Zr/28/
as it works well but when i am adding school by typing school name and selecting year it will add new elements with same name.
how can i create blank elements like this http://viralpatel.net/blogs/demo/dynamic-add-delete-row-table-javascript.html
How can i pass textbox value to the label in hobby section?
A: event handlers do not get attached to the dynamically added elements to the DOM try using live
$('.deleteEl a').live("click",function () {
DEMO
A: As the element does not exist when you bind the click event, it is not associated.
You need live to bind the event to dynamic elements.
http://jsfiddle.net/NT4Zr/19/
$('.deleteEl a').live('click', function () {
$(this).parent().parent().remove();
});
A: Working example using delegate here: http://jsfiddle.net/jkeyes/KYrAE/1/
$("#Education").delegate(".deleteEl a", "click", function(){
$(this).parent().parent().remove();
});
delegate is more efficient than live.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633467",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I typecast an NSArray element to double? An other way please.
I have an array whole elements are doubles. How can I get the content out as double?e.g.
coordinate.latitude = [coords objectAtIndex:0];// value inside it is 61.2180556;
A: You can't store primitive doubles in NSArray. You have either stored them as NSNumber or NSString. In either case use:
coordinate.latitude = [[coords objectAtIndex:0] doubleValue];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using quotes inside html attribute I haven't coded with PHP in a while and cannot remember how to do this..
I'm using a jquery plugin that requires some rel parameters to be set.
$imgtag = '<a href="'.carturl($img->id,'images').'/'.$img->filename.'" class = "zoom" id="zoom1" rel="adjustX: 10, adjustY:-4, zoomWidth:150, zoomHeight:150">
<img src="'.$src.'"'.$titleattr.' alt="'.$alt.'" width="'.$width_a.'" height="'.$height_a.'" '.$classes.' /></a>';
Now I need to add , position: "inside" to the rel bit, however, every time I do it, it outputs in HTML as quotes all over the place. The plugin must retail the quotes around the word "inside" to work, however, I need to use these quotes within the "rel=" quotes.
How do I go about this?
HTML Output should look like this:
<a style="position: relative; display: block;" href="http://www.URL.com/theimage.jpg" class="cloud-zoom" id="zoom1" rel="adjustX: 10, adjustY:-4, zoomWidth:150, zoomHeight:150, position:"inside"">
<img style="display: block;" src="http://www.URL.com/theimage.jpg" alt="product-picture" height="450" width="360"></a>
Thanks!
A: use single quote
rel="adjustX: 10, adjustY:-4, zoomWidth:150, zoomHeight:150, position:'inside'"
or reverse
rel='adjustX: 10, adjustY:-4, zoomWidth:150, zoomHeight:150, position:"inside"'
A: Try with:
$imgtag = '<a href="'.carturl($img->id,'images').'/'.$img->filename.'" class = "zoom" id="zoom1" rel="adjustX: 10, adjustY:-4, zoomWidth:150, zoomHeight:150, position:\'inside\' ">
<img src="'.$src.'"'.$titleattr.' alt="'.$alt.'" width="'.$width_a.'" height="'.$height_a.'" '.$classes.' /></a>';
A: You can escape quotes using the following syntax:
\"your stuff\"
This will render wrapped in ", assuming you have also the outer quotes round the rel element
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to check if referenced table is not empty? For example, I have 2 tables:
CREATE TABLE IF NOT EXISTS master(
master_id INT NOT NULL AUTO_INCREMENT,
master_name VARCHAR(15) NOT NULL,
PRIMARY KEY(master_id)
) TYPE=InnoDB CHARACTER SET=UTF8;
and
CREATE TABLE IF NOT EXISTS slave(
slave_id INT NOT NULL AUTO_INCREMENT,
slave_name VARCHAR(15) NOT NULL,
master_id INT
PRIMARY KEY (slave_id),
FOREIGN KEY (master_id) REFERENCES master(master_id)
) TYPE=InnoDB CHARACTER SET=UTF8;
How can I check if the master table is connected to the slave table and then, if it is, I want to know if slave is empty?
A: I'm not sure I quite understand your question, but I'll try to answer. The master table must be 'connected' to the slave table if you created the slave table with the foreign key reference FOREIGN KEY (master_id) REFERENCES master(master_id).
As for whether the slave table is empty: it's empty if this query returns a column with zero in it:
SELECT COUNT(*) FROM slave
A: You can check if the two tables are connected by doing a join.
SELECT COUNT(*) as number_of_connections
FROM master m
INNER JOIN slave s ON (s.master_id = m.master_id)
UNION ALL
SELECT COUNT(*) as rows_in_slave
FROM slave s2
UNION ALL
SELECT COUNT(*) as rows_in_master
FROM master m2
This query will return exactly 3 rows, that will tell you the number of connections, whether the slave table is empty and whether the master table is empty respectively.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ClassCastException: android.widget.EditText I always get the error:
10-03 09:55:44.517: ERROR/AndroidRuntime(819): Caused by: java.lang.ClassCastException: android.widget.EditText
In my code I don't have the word EditText so why does that error occur?
The MultiAutoCompleteTextView was a EditText before. Please help
Code:
public class AddPizza extends Activity {
private ImageView iv;
private MultiAutoCompleteTextView name;
private RatingBar rating;
private SQLiteDatabase myDB;
final String MY_DB_NAME = "PizzaCounter";
final String MY_DB_TABLE = "Pizza";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.addpizza);
iv = (ImageView) findViewById(R.id.imageViewPizza);
name = (MultiAutoCompleteTextView) findViewById(R.id.multiAutoCompleteTextView1);
rating = (RatingBar) findViewById(R.id.ratingBar1);
Button bt = (Button) findViewById(R.id.bt_addform);
iv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE),1337);
}
});
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
addData();
finish();
}
});
addAutoSuggest();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1337) {
iv.setImageBitmap((Bitmap) data.getExtras().get("data"));
}
}
private void addData() {
myDB = this.openOrCreateDatabase(MY_DB_NAME, MODE_PRIVATE, null);
//myDB.execSQL("DROP TABLE " + MY_DB_TABLE);
myDB.execSQL("CREATE TABLE IF NOT EXISTS " + MY_DB_TABLE
+ " (_id integer primary key autoincrement, name varchar(100), rate integer(1), eattime varchar(100),image BLOB)"
+";");
if(!name.getText().equals("") && rating.getRating()!=0.0)
{
Log.e("XXX", "Enter_Insert");
Calendar cal = Calendar.getInstance();
DateFormat formatter = new SimpleDateFormat();
ByteArrayOutputStream out = new ByteArrayOutputStream();
Bitmap bt = ((BitmapDrawable)iv.getDrawable()).getBitmap();
bt.compress(Bitmap.CompressFormat.PNG, 100, out);
ContentValues cv = new ContentValues();
cv.put("image", out.toByteArray());
cv.put("name", name.getText().toString());
cv.put("eattime", formatter.format(cal.getTime()));
cv.put("rate", rating.getRating());
myDB.insert(MY_DB_TABLE, null, cv);
//myDB.execSQL("INSERT INTO "+ MY_DB_TABLE + "(name,rate,eattime,image) VALUES +" + + ", " ++ " , datetime('now', 'localtime'), " );
}
}
void addAutoSuggest ()
{
myDB = this.openOrCreateDatabase(MY_DB_NAME, MODE_PRIVATE, null);
ArrayList<String> list = new ArrayList<String>();
Cursor cursor = this.myDB.query(MY_DB_TABLE, new String[] {"name"},null,null,null,null,null,null);
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0));
}
while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
name.setAdapter( new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, list));
}
}
Layout:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:orientation="vertical">
<TextView android:text="Name" android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
<MultiAutoCompleteTextView android:id="@+id/multiAutoCompleteTextView1" android:layout_height="wrap_content" android:text="MultiAutoCompleteTextView" android:layout_width="fill_parent"></MultiAutoCompleteTextView>
<TextView android:text="Bewertung" android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
<RatingBar android:id="@+id/ratingBar1" android:layout_width="wrap_content" android:layout_height="wrap_content"></RatingBar>
<TextView android:text="Foto hinzufügen" android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
<ImageView android:layout_height="wrap_content" android:src="@drawable/icon" android:layout_width="wrap_content" android:id="@+id/imageViewPizza"></ImageView>
<RelativeLayout android:id="@+id/relativeLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent">
<Button android:text="hinzufügen" android:layout_height="wrap_content" android:id="@+id/bt_addform" android:layout_alignParentBottom="true" android:layout_width="fill_parent"></Button>
</RelativeLayout>
</LinearLayout>
A: *
*Clean project
*Save files
*Build & Run
have fun ^^!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Insert string at the beginning of each line How can I insert a string at the beginning of each line in a text file, I have the following code:
f = open('./ampo.txt', 'r+')
with open('./ampo.txt') as infile:
for line in infile:
f.insert(0, 'EDF ')
f.close
I get the following error:
'file' object has no attribute 'insert'
A: You can't modify a file inplace like that. Files do not support insertion. You have to read it all in and then write it all out again.
You can do this line by line if you wish. But in that case you need to write to a temporary file and then replace the original. So, for small enough files, it is just simpler to do it in one go like this:
with open('./ampo.txt', 'r') as f:
lines = f.readlines()
lines = ['EDF '+line for line in lines]
with open('./ampo.txt', 'w') as f:
f.writelines(lines)
A: Python comes with batteries included:
import fileinput
import sys
for line in fileinput.input(['./ampo.txt'], inplace=True):
sys.stdout.write('EDF {l}'.format(l=line))
Unlike the solutions already posted, this also preserves file permissions.
A: For a file not too big:
with open('./ampo.txt', 'rb+') as f:
x = f.read()
f.seek(0,0)
f.writelines(('EDF ', x.replace('\n','\nEDF ')))
f.truncate()
Note that , IN THEORY, in THIS case (the content is augmented), the f.truncate() may be not really necessary. Because the with statement is supposed to close the file correctly, that is to say, writing an EOF (end of file ) at the end before closing.
That's what I observed on examples.
But I am prudent: I think it's better to put this instruction anyway. For when the content diminishes, the with statement doesn't write an EOF to close correctly the file less far than the preceding initial EOF, hence trailing initial characters remains in the file.
So if the with statement doens't write EOF when the content diminishes, why would it write it when the content augments ?
For a big file, to avoid to put all the content of the file in RAM at once:
import os
def addsomething(filepath, ss):
if filepath.rfind('.') > filepath.rfind(os.sep):
a,_,c = filepath.rpartition('.')
tempi = a + 'temp.' + c
else:
tempi = filepath + 'temp'
with open(filepath, 'rb') as f, open(tempi,'wb') as g:
g.writelines(ss + line for line in f)
os.remove(filepath)
os.rename(tempi,filepath)
addsomething('./ampo.txt','WZE')
A: Here's a solution where you write to a temporary file and move it into place. You might prefer this version if the file you are rewriting is very large, since it avoids keeping the contents of the file in memory, as versions that involve .read() or .readlines() will. In addition, if there is any error in reading or writing, your original file will be safe:
from shutil import move
from tempfile import NamedTemporaryFile
filename = './ampo.txt'
tmp = NamedTemporaryFile(delete=False)
with open(filename) as finput:
with open(tmp.name, 'w') as ftmp:
for line in finput:
ftmp.write('EDF '+line)
move(tmp.name, filename)
A: f = open('./ampo.txt', 'r')
lines = map(lambda l : 'EDF ' + l, f.readlines())
f.close()
f = open('./ampo.txt', 'w')
map(lambda l : f.write(l), lines)
f.close()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: how to omit columns having null value in select query in mysql? Select Header1,Header2,Header3,ExtraHeader from tbl_likeinfo where HotelID=2
Here Header3 and ExtraHeader may have null values.In that case I don't need only that null value in my query result but that row containing other column values should be given.
How to achieve that?
A: You can't dynamically change the columns selected in the result set based on the data the query is selecting. If you don't want to handle nulls, you could use a CASE statement on the header values to change them to a value of your choosing that represents you could treat the same way, but I wouldn't recommend that approach.
You may want to change your approach. It appears you have your table layout using columns to represent each unique header. If you changed your layout so the table was:
hotel_id NUMBER
header_name VARCHAR2(50)
header_value VARCHAR2(100)
Then when you're inserting the headers, do one insert per header received at that time. Then change your select to:
SELECT header_name, header_value FROM headers WHERE hotel_id = 2;
If you happen to be storing header values that were null and when you pull them out, you want to eliminate those, then:
SELECT header_name, header_value
FROM headers
WHERE hotel_id = 2 AND header_value is not null;
If order is important to you, then add a column to the table to store the order as you insert them. This layout also allows you to store any amount of header information without having to change the layout of the table in the future.
Hope this helps.
A: AND Header3 IS NOT NULL AND ExtraHeader IS NOT NULL
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: WordPress change content without reload I have a wordpress theme in which i have to create a page that has a movie that goes loop.
it has 3 menu points which change the div text without reloading the page.
So far no problem.
<a href="javscript:void(0);" onclick="getdata('text.php','content2');">Click here – put it in content box 2</a>
But when im on a different page and i click for example the second link, it should go to the video page and change the text to the second one.
How can i do this?
Is there a way to do that with?
url/wordpressname/#1
A: Found a Solution: i found a solution here: http://www.deluxeblogtips.com/2010/05/how-to-ajaxify-wordpress-theme.html
which i changed to fit my needs:
jQuery(document).ready(function($) {
var $mainContent = $("#text"),
siteUrl = "http://" + top.location.host.toString(),
url = '';
$(document).delegate("a[href^='"+siteUrl+"']:not([href*=/wp-admin/]):not([href*=/wp-login.php]):not([href$=/feed/])", "click", function() {
//location.hash = this.pathname;
//return false;
});
$("#searchform").submit(function(e) {
location.hash = '?s=' + $("#s").val();
e.preventDefault();
});
$(window).bind('hashchange', function(){
url = window.location.hash.substring(1);
if (!url) {
return;
}
if (url=="1") {
$mainContent.html('<p>Text1</>');
}
if (url=="2") {
$mainContent.html('<p>Text2</>');
}
if (url=="3") {
$mainContent.html('<p>Text3</>');
}
if (url=="4") {
$mainContent.html('<p>Text4</>');
}
// url = url + "#content";
//$mainContent.animate({opacity: "0.1"}).html('<p>Please wait...</>').load(url, function() {
//$mainContent.animate({opacity: "1"});
//});
});
$(window).trigger('hashchange');
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633490",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Appirater doesn't work I'm trying to implement Appirater in my app. I've followed the instructions in the read me, and the app runs fine in Xcode. But no message is shown, no matter how many times i try to run it. I have edited the #defines, so the problem shouldn't be there. When APPIRATER_DEBUG is enabled, it also doesn't show anything. I've tried cleaning the project, but that didn't seem to work.
A: You imported Appirater in AppDelegate.ma It should now open the pop-up to the launch of the app
import "AppDelegate.h"
import "Appirater.h"
@implementation AppDelegate
*
*(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[Appirater appLaunched];
return YES;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Admob(Ads) in Custom Alert Dialog In the market I saw an app is displaying admob in the alert dialog . after I reading this and this and this ,
I still can't figure out how to display the ads in alert dialog same like the one below. (or any others method , that can display the ads in a alert dialog)
I've been scratching my head trying to figure out how
to do that.
Could anyone be kind enough to guide me through how
to go about this?
XML :
<?xml version="1.0" encoding="utf-8"?>
<TableLayout android:id="@id/tablayout" android:layout_width="fill_parent" android:layout_height="fill_parent" android:stretchColumns="*"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myapp="http://schemas.android.com/apk/res/com.xxx.xxx">
<TableRow>
<com.admob.android.ads.AdView android:id="@id/myad"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
myapp:backgroundColor="#ff000000"
myapp:primaryTextColor="#ffffffff"
myapp:secondaryTextColor="#ffcccccc" />
</TableRow>
</TableLayout>
Java :
public void onBackPressed() {
//set up dialog
Dialog dialog = new Dialog(main.this);
dialog.setContentView(R.layout.exitdialog);
dialog.setTitle("This is my custom dialog box");
dialog.setCancelable(true);
//set up button
Button button = (Button) dialog.findViewById(R.id.Button01);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
//now that the dialog is set up, it's time to show it
dialog.show();
}
});
}
Thanks.
A: I found another solution to do this.
AdMob offers a JavaScript integration solution for Android and iPhone sites/web apps.
Instead of using XML and a custom dialog.
We can use Admob web ads and a HTML that contain the admob code and load it with webview in the dialog.
A: I believe it's not possible unless you're on landscape mode. The reason is that the ad needs something close to the device width (in portrait mode, e.g. 480) for the ad, so it is only available in landscape mode when you're adding it inside a dialog
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ASP CustomValidator doesn't detect text changed with JQuery autocomplete I've written a web page that uses an ASP.NET CustomValidator to validate the input of a text field (client side). The text field uses JQuery UI Autocomplete - and this is where I run into problems.
The validator works just fine. But in the event that the validation fails and the user gets an error message, the user will go back to the text field and enter a new value - choosing from the drop down made by the autocomplete plugin. Now when a new value has been chosen and the user leaves the input field, the validation code doesn't fire again. I suspect that it is because, for some reason, it is not detected that the text was changed, when the value came from the autocomplete helper. Does that make sense?
Does anyone know how I can force the field to validate via the CustomValidator when the user removes focus from the field?
Heres the CustomValidator:
<asp:CustomValidator EnableClientScript="True" runat="server" ControlToValidate="tbInput"
ID="inputCustomValidator" ClientValidationFunction="validateFunction" ErrorMessage="Not valid"
Display="Dynamic" ValidationGroup="ValidationGrp1" />
The javascript that is called is not interesting - since it is not being called. That is what I want to achieve.
A: I found a way to do this. In javascript I added a blur() function to the element I wanted to validate and made that function trigger Page_ClientValidate('validationGroupName'). A functionality that was new to me.
$('.elementToValidate').blur(function () {
Page_ClientValidate('ValidationGrp1');
});
A: This might not be what you want to hear, but I would avoid mixing jQuery and ASP.net's Javascript whenever possible - they don't tend to play nicely.
In your case, I'd recommend dumping your ASP.net CustomValidator and switching to jQuery's Validate plugin. That will play much more nicely with jQuery UI.
A: You can also use autoselect's select: handler to trigger validation.
$(".someClass").autocomplete({
select: function(event, ui)
{
Page_ClientValidate(ui);
}
});
A: I got this working by setting the onBlur event for my textbox.
<asp:TextBox ID="TextBox1" runat="server" onBlur="Page_ClientValidate('ValidationGrp1');"></asp:TextBox>
(assuming your CustomValidator's ValidationGroup is 'ValidationGrp1')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633505",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Getting clicks on css :pseudo-elements I'm trying to make a custom checkbox, so I made something like that : http://jsfiddle.net/wQdUn/2/
The problem is that, on WebKit based browsers, the checkbox is toggled only when clicking on the content of the <span>, not on the box itself, while in Firefox I get the behavior I expect.
So I have two questions:
*
*Which one is the right behavior (i.e. the one conform to specifications)?
*How do I get the result I want in both browsers (and others...)?
Thanks.
A: Not sure about the first question, but if you make the span an inline block too, it'll work as you expect in WebKit browsers. See http://jsfiddle.net/wQdUn/5
A: For those who come to this topic form google:
Safari 6.0.4(8536.29.13) still got this problem, you need to set inline-block on pseudo-element to make click work.
Chrome switched to Blink as it's rendering engine, so this problem didn't happen on chrome any more(26.0.1410.65).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: $.get not working in IE This displays 1 no matter what I echo in getbillno.php - also why I'm not showing that part anymore.
Nothing would change unless I change bill into a string
or put tbl (just to see what happens) in its place, so I figured the problem is not
in getbillno.php but with this part right here. I'm very
much new to jQuery and I really can't see what's wrong
with this.
This works perfectly with Chrome, FF, and in Safari. I have other functions with jQuery in the same page and those work fine in any browser including IE(9). It's just with this one that I'm having problems.
<script type="text/javascript">
function getbillno(tbl){
$.get("getbillno.php?tbl="+ tbl, function(bill){
$("#billno").val(bill); });
}
</script>
I'm trying to make this work with IE(9) because it's the only browser
that lets me have the Print options I want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Mifare classic 1k and NFC communication protocol which protocol is used (other than NDEF protocol) for communication between Mifare classic 1k and nfc enabled mobile, when we raed or write indvisual blocks.
A: NDEF is not a communication protocol, but the message content description:
"...The NDEF specification defines a message encapsulation format to
exchange information... NDEF is a lightweight, binary message format that can be used to encapsulate one or more application-defined payloads of arbitrary type and size into a single message construct. Each payload is described by a type, a length, and an optional identifier.
Type identifiers may be URIs, MIME media types, or NFC-specific types..."
The protocol to read/write Mifare sectors is a proprietary see e.g. here: http://www.nxp.com/documents/data_sheet/MF1S503x.pdf
BR
STeN
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633513",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Dealing with an array of checkboxes in php Ok so I am making an emailing form and need to get a bunch of items in a checkbox array to be printed... or converted into a string... so they can be made into a variable...
here is what the form looks like:
And there is the html behind it:
<th valign="top" scope="row">Receive further information_on: </th>
<td width="27%"><input type="checkbox" name="Information_on[]" value="Rapid Auto Roll Doors" id="Information on" />
Rapid Auto Roll Doors<br />
<input type="checkbox" name="Information_on[]" value="Swingflex Doors" id="Information on" />
Swingflex Doors<br />
<input type="checkbox" name="Information_on[]" value="Floor Guides" id="Information on" />
Floor Guides<br />
<input type="checkbox" name="Information_on[]" value="Visiflex Strip Doors" id="Information on" />
Visiflex Strip Doors<br />
<input type="checkbox" name="Information_on[]" value="PVC-Strip / Sheets" id="Information on" />
PVC-Strips / Sheets</td>
<td width="37%"><input type="checkbox" name="Information_on[]" value="Efaflex Doors" id="Information on" />
Efaflex Doors <br />
<input type="checkbox" name="Information_on[]" value="Traffic Doors" id="Information on" />
Traffic Doors<br />
<input type="checkbox" name="Information_on[]" value="Fold Up Doors" id="Information on" />
Fold Up Doors <br />
<input type="checkbox" name="Information_on[]" value="Dock Levellers" id="Information on" />
Dock Levellers<br />
<input type="checkbox" name="Information_on[]" value="Other" id="Information on" />
Other
</p></td>
they all have the same name: Information_on[]
ok so the next part is to convert the "selected" ones into a php string that would look like the following format:
$outputExample = "selecteditem1, selecteditem2, selecteditem3.";
but of course with the values set in the checkboxes.
So I have no idea how to do this, to have them be gathered and checked to see which titles need to be sent in PHP... thanks for the help!
A: Make sure your form is POST, since you're making a contact form. Then you could do something like this:
$info = $_POST['Information_on'];
$outputExample = implode(', ', $info);
Remember that where a checkbox is blank, you won't get any value in your $_POST array (not even an "off" - just the way it works!).
A: Remember to always sanitize your data inputs!
$info = filter_var_array($_POST['Information_on'], FILTER_SANITIZE_STRING);
$CSV = implode(', ', $info)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633514",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CGridview custom field sortable I had created with custom field in yii Cgridview but how to make that sortable. The custom field value is from a function in the model. I want to make this field sortable?
Can someone help me?
A: In the search function of your model, where customField is the name of your field:
// ...other criteria...
$criteria->compare('customField',$this->customField);
$sort = new CSort();
$sort->attributes = array(
'customField'=>array(
'asc'=>'customField ASC',
'desc'=>'customField DESC',
),
'*', // this adds all of the other columns as sortable
);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'sort'=>$sort,
));
You may also need to update rules and attributeLabels in your model to reflect the new custom field.
A: There is a detailed description about searching on custom fields at this URL:
Using standard filters in CGridView custom fields
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Data not send/received properly I am trying to implement a TCP server/client using sockets in c.
I have written the program in such a way that whatever we send in the client is displayed in the server line by line till exit is typed.
The program works but the data is shown in the server all together at the last. Can anybody please check the code?
TCP SERVER
#include<sys/socket.h>
#include<netinet/in.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
main()
{
char buf[100];
socklen_t len;
int k,sock_desc,temp_sock_desc;
struct sockaddr_in client,server;
memset(&client,0,sizeof(client));
memset(&server,0,sizeof(server));
sock_desc = socket(AF_INET,SOCK_STREAM,0);
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_port = 7777;
k = bind(sock_desc,(struct sockaddr*)&server,sizeof(server));
k = listen(sock_desc,20);
len = sizeof(client);
temp_sock_desc = accept(sock_desc,(struct sockaddr*)&client,&len);
while(1)
{
k = recv(temp_sock_desc,buf,100,0);
if(strcmp(buf,"exit")==0)
break;
if(k>0)
printf("%s",buf);
}
close(sock_desc);
close(temp_sock_desc);
return 0;
}
TCP CLIENT
#include<sys/socket.h>
#include<netinet/in.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
main()
{
char buf[100];
struct sockaddr_in client;
int sock_desc,k;
sock_desc = socket(AF_INET,SOCK_STREAM,0);
memset(&client,0,sizeof(client));
client.sin_family = AF_INET;
client.sin_addr.s_addr = inet_addr("127.0.0.1");
client.sin_port = 7777;
k = connect(sock_desc,(struct sockaddr*)&client,sizeof(client));
while(1)
{
gets(buf);
k = send(sock_desc,buf,100,0);
if(strcmp(buf,"exit")==0)
break;
}
close(sock_desc);
return 0;
}
A: while(1){
k = recv(temp_sock_desc,buf,100,0);
if(memcmp(buf,"exit", 4)==0)
break;
if(k>0)
printf("%*.*s", k, k, buf);
}
The result of recv() is not a string, so it will not be nul-terminated.
The above "fix" is not entirely correct, but is only intended to point you in the right direction.
A: gets() replaces terminating newline with '\0'. Resulting string is sent to server, which writes it to stdout. Stdout is buffered, so nothing will appear on screen until program terminates or '\n' is printed.
Add '\n' to your printf:
if(k>0)
printf("%s\n",buf);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Windows Azure Local Testing I am recently evaluating Windows Azure. One of the problems I found is that Azure start charging as soon as the app is deployed even if it is in the testing stage.
I want to ask existing Azures how much of your tests are done locally and how much are done after it is deployed? Does Azure provide any means of testing web services locally?
Many thanks.
A: Yes, Azure provides an emulation framework that largely (but not completely) mimics the Azure deployment environment. This is usually sufficient for testing.
Costs of test deployments can be controlled somewhat, however:
*
*It's possible to deploy "extra-small" instances that are significantly less expensive than larger instances, at the expense of throughput - which unless you're doing load testing isn't usually an issue
*You won't generally need to have multiple instances of a role deployed, just one will usually do, unless you have major concurrency issues under load
*Some of the cost of Azure is in data traffic, which will obviously be less expensive for test instances
*It's not necessary to have test instances permanently available. They can be torn down or re-deployed at will; if your environment becomes sophisticated this can be done programmatically by a continuous integration engine.
In practice we're finding that the cost of test instances is relatively insignificant compared to the cost of our developers and the alternative, which would be to provision and maintain our own data centre.
In particular, being able to quickly spin up a test environment that is a direct mimic of production in a few minutes is a very powerful feature.
A: Windows azure already provide option to do testing locally.
The Microsoft Azure storage emulator provides a local environment that emulates the Azure Blob, Queue, and Table services for development purposes. Using the storage emulator, you can test your application against the storage services locally, without creating an Azure subscription or incurring any costs. When you're satisfied with how your application is working in the emulator, you can switch to using an Azure storage account in the cloud.
To get complete detail please check link below.
https://azure.microsoft.com/en-in/documentation/articles/storage-use-emulator/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633526",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Unable to instantiate Action, com.hcl.hips.action.KAListproduct, defined for 'KAListproduct' in namespace '/'com.hcl.hips.action.KAListproduct Unable to instantiate Action, com.hcl.hips.action.KAListproduct, defined for 'KAListproduct' in namespace '/'com.hcl.hips.action.KAListproduct
at com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:306)
at com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:387)
at com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:186)
at org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:61)
at org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
at com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:47)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:458)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at net.sf.j2ep.ProxyFilter.doFilter(ProxyFilter.java:91)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.hcl.hips.action.LoginFilter.doFilter(LoginFilter.java:108)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:859)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:574)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1527)
at java.lang.Thread.run(Thread.java:619)
Caused by: java.lang.ClassNotFoundException: com.hcl.hips.action.KAListproduct
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1387)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1233)
at com.opensymphony.xwork2.util.ClassLoaderUtil.loadClass(ClassLoaderUtil.java:146)
at com.opensymphony.xwork2.ObjectFactory.getClassInstance(ObjectFactory.java:96)
at com.opensymphony.xwork2.spring.SpringObjectFactory.getClassInstance(SpringObjectFactory.java:206)
at com.opensymphony.xwork2.spring.SpringObjectFactory.buildBean(SpringObjectFactory.java:128)
at com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:139)
at com.opensymphony.xwork2.ObjectFactory.buildAction(ObjectFactory.java:109)
at com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:287)
... 26 more
A: your error is described in the stack trace
java.lang.ClassNotFoundException: com.hcl.hips.action.KAListproduct
You did not import your class, or somehow failed to wire up it up correctly. Post relevant configs if you want further help.
A: Hey this is the code to resolve this issue
http://www.bpjava.net/Struts2_Configuration_Plugin/config-browser/showBeans.action
i do not know whether kiran kumar solved it or not...
But for future people........
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: User validation not working properly in CakePHP through the User Model For some reason, I can't get this validation to work as I'd like it to, specifically with the password minLength field.
Everything else is fine (even the minLength for Username works). For some reason, when I add the same minLength rule into the password field, it just ignores it and when I actually do enter in a password, it tells me that I need to enter a password:
var $validate = array(
'email' => array(
'email' => array(
'rule' => array('email', true),
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a valid email address'
),
'isUnique' => array(
'rule' => 'isUnique',
'message' => 'This email is already in use'
)
),
'username' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => 'Please enter a valid username'
),
'allowedCharacters' => array(
'rule' => '/^[a-zA-Z]+[0-9]*$/',
'message' => 'Please enter a valid username'
),
'minLength' => array(
'rule' => array('minLength', 3),
'message' => 'Please enter a longer username'
),
'maxLength' => array(
'rule' => array('maxLength', 23),
'message' => 'Please enter a shorter username'
),
'isUnique' => array(
'rule' => 'isUnique',
'message' => 'That username is already taken'
)
),
'password' => array(
'notEmpty' => array(
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a password'
),
'minLength' => array(
'rule' => array('minLength', 4),
'message' => 'Please enter a longer password'
),
'passwordConfirm' => array(
'rule' => array('checkPasswords'),
'message' => 'Passwords must match'
)
),
);
Am I overlooking something minor? It's driving me nuts.
A: This happens because in Cake, the password field is automatically hashed as soon as you submit it; which will break your validation rules (a 5 character password suddenly becomes a 40+ digit hash). There are various proposed fixes for this problem.
One that sounds the most promising:
Create two fields e.g pw and pw_confirm as opposed to password and confirm_password. Use these values for your password validation (so, max length etc)
Then something like:
$this->User->set($this->data);
if ($this->User->validates()) {
// all your data validates, so hash the password submitted,
// ready for storage as normal.
$password_hash = $this->Auth->password($this->data['User']['pw'];
$this->data['User']['password'] = $password_hash;
}
This way, Cake won't automatically hash the passed that's entered - allowing your validation to function as you intended.
To visualise this, add this to your register/add user method:
function admin_add() {
if (!empty($this->data)) {
debug($this->data);
exit;
You'll get:
Array
(
[User] => Array
(
[username] => somename
[password] => 25ae3c1689d26b20e03abc049982349482faa64e
)
)
before validation takes place.
A: It looks like you have a small mistake in your validation array.
Every validation for a field must have a 'rule' key, and you don't have that in your 'notEmpty' validation.
Try updating the password validation like this:
<?php
array(
'password' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a password'
),
'minLength' => array(
'rule' => array('minLength', 4),
'message' => 'Please enter a longer password'
),
'passwordConfirm' => array(
'rule' => array('checkPasswords'),
'message' => 'Passwords must match'
)
))
?>
Also, note that if you're using the Auth component your password will be hashed BEFORE it is validated. This means that even if you enter a 3-character password you'll end up with a 40-character hash, which obviously will validate as being longer than the minLength.
A: use my change password behavior. it takes care of all those things at a single and clean place:
http://www.dereuromark.de/2011/08/25/working-with-passwords-in-cakephp/
you will most certainly have more problems later on otherwise
because you need a lost password and change password functionality as well.
and maybe a backend for the admin to simply change passwords as well
and to your problem i already commented:
"you should also use last=>true here! otherwise it doesnt make much sense"
i believe this is also part of your problem. all your rules need this param to make it work properly. the error messages will be off otherwise.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Django objects.filter multiple filters The user can select fields to filter by, I need to filter by only those fields but there can be 3 fields.
The user selects all three options:a, b and c
Foo.objects.filter(a=1,b=2,c=3), good
What if the user selects only 1 option or 2 options ?
Foo,objects.filter(a=1, b=2, c=not selected)
How can I do this to only filter by the selected choices. THis comes from a post to the view, and looks like this if not selected:
a=1,b=NaN,c=3
So b was not selected and I would not like to inlclude it in my filter,
Foo.objects.filter(a=1,c=3)
Or can I perhaps so a filter that is basically a "all" selector
So as per above:
Foo.objects.filter(a=1,b=%,c=3)
A: You can use a keyword argument dict:
filterargs = { 'a': 1, 'b': 2, 'c': 3 }
Foo.objects.filter(**filterargs)
then to only filter on a and b:
filterargs = { 'a': 1, 'b': 2 }
or a and c:
filterargs = { 'a': 1, 'c': 3}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633532",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Lost sessionvariables in firefox I have a pretty strage problem im dealing with.
Lost sessionvariables in firefox.
Im using wordpress and have a subpage that causes the loss.
More specific:
In wordpress there exists a page called My pages (Original page names are in swedish, translated for convinience)
Under this page i have a few subpages. Among these are a page called Create test. There is nothing special about this page, for now only contains the phrase "hello world". If I enter any page other that this, it works.
But this particular page just seems to clear my session variables (wich I use to store login info)
I tried deleting the page in question in the effort to remake it.
While it was deleted I tried navigating around on the page.
Create test was the last item in the subnavigation menu, and now when its gone, the same thing happens on the last menuitem (now Account settings). This leave me to believe its something with the menu.
Even more strange, after recreating Create test, so that this page is now the last item. Still it's Account settings that is the page with the resetting of sessionvars...
I have through echo determined that the session id stays the same, just the variables that get unset.
I have unset($_SESSION['id']); at only one place, and this code is NOT run.
The problem just baffles me and I have no idea why this particular pages does this.
A: It may be totally unrelated, but we had problem with Firefox and sessions on certain pages in the past. It happened most of the times while developing and therefore refreshing a particular page, have you tried clearing your browser cookies which is where session is stored?
As an addition:
Check that you assign sessions before you write anything to the response stream.
Also we had similar problems with sessions set in a pages that were doing a redirection (i.e. a login page that if successful would set the session and redirect to the another page.)
I'm not sure about PHP but in .NET that can be overcome by explicitly setting not to terminate the response so that all headers are written to the response stream.
A: Fixed now, actually have no idea what I did. but I've change some html but mostly CSS.
So there is a strong posibility it was CSS-related.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Find gaps in time not covered by records with start date and end date I have a table of fee records (f_fee_item) as follows:
Fee_Item_ID int
Fee_Basis_ID int
Start_Date date
End_Date date
(irrelevant columns removed)
Assume that records for the same Fee_Basis_ID won't overlap.
I need to find the Start_Date and End_Date of each gap in the fee records for each Fee_Basis_ID between a supplied @Query_Start_Date and @Query_End_Date. I need this data to calculate fee accruals for all periods where fees have not been charged.
I also need the query to return a record if there are no fee records at all for a given Fee_Basis_ID (Fee_Basis_ID is a foreign key to D_Fee_Basis.Fee_Basis_ID if that helps).
For example:
@Query_Start_Date = '2011-01-01'
@Query_Start_Date = '2011-09-30'
D_Fee_Basis:
F_Fee_Item
1
2
3
F_Fee_Item:
Fee_Item_ID Fee_Basis_ID Start_Date End_Date
1 1 2011-01-01 2011-03-31
2 1 2011-04-01 2011-06-30
3 2 2011-01-01 2011-03-31
4 2 2011-05-01 2011-06-30
Required Results:
Fee_Basis_ID Start_Date End_Date
1 2011-07-01 2011-09-30
2 2011-04-01 2011-04-30
2 2011-07-01 2011-09-30
3 2011-01-01 2011-09-30
I've bee trying different self-joins for days trying to get it working but with no luck.
Please help!!
A: Here is a solution:
declare @Query_Start_Date date= '2011-01-01'
declare @Query_End_Date date = '2011-09-30'
declare @D_Fee_Basis table(F_Fee_Item int)
insert @D_Fee_Basis values(1)
insert @D_Fee_Basis values(2)
insert @D_Fee_Basis values(3)
declare @F_Fee_Item table(Fee_Item_ID int, Fee_Basis_ID int,Start_Date date,End_Date date)
insert @F_Fee_Item values(1,1,'2011-01-01','2011-03-31')
insert @F_Fee_Item values(2,1,'2011-04-01','2011-06-30')
insert @F_Fee_Item values(3,2,'2011-01-01','2011-03-31')
insert @F_Fee_Item values(4,2,'2011-05-01','2011-06-30')
;with a as
(-- find all days between Start_Date and End_Date
select @Query_Start_Date d
union all
select dateadd(day, 1, d)
from a
where d < @Query_end_Date
), b as
(--find all unused days
select a.d, F_Fee_Item Fee
from a, @D_Fee_Basis Fee
where not exists(select 1 from @F_Fee_Item where a.d between Start_Date and End_Date and Fee.F_Fee_Item = Fee_Basis_ID)
),
c as
(--find all start dates
select d, Fee, rn = row_number() over (order by fee, d) from b
where not exists (select 1 from b b2 where dateadd(day,1, b2.d) = b.d and b2.Fee= b.Fee)
),
e as
(--find all end dates
select d, Fee, rn = row_number() over (order by fee, d) from b
where not exists (select 1 from b b2 where dateadd(day,-1, b2.d) = b.d and b2.Fee= b.Fee)
)
--join start dates with end dates
select c.Fee Fee_Basis_ID, c.d Start_Date, e.d End_Date from c join e on c.Fee = e.Fee and c.rn = e.rn
option (maxrecursion 0)
Link for result:
https://data.stackexchange.com/stackoverflow/q/114193/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to read title and id from Blu-ray disc? Is it somehow possible to fetch Blu-Ray Disc id and title programmatically on Windows7+ platform?
A: If you can programmatically open the following files you'll probably get what you need:
/AACS/mcmf.xml - This file is the Managed Copy manifest file and will contain a 'contentID' attribute (in the mcmfManifest tag) that can be used to identify the disc. Typically it is a 32 hexadecimal digit string.
There is sometimes, also an /CERTIFICATE/id.bdmv file which contains a 4 byte disc organization id (at byte offset 40) followed by a 16 byte disc id.
Sometimes, there is metadata information in the /BDMV/META/DL directory in the XML file bdmt_eng.xml (replace eng for other 3 letter language codes for other languages). For example on the supplemetary disc of The Dark Knight I see this file contains:
<di:title><di:name>The Dark Knight Bonus Disc</di:name></di:title>
A: For .NET, the BDInfo library will parse the relevant disc structure.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Uploading Sqlite database to a remote server I am collecting data using my device then save it in a local sqlite database. I am now attempting to upload this database to a remote server by the click of a button.
I have been able to upload the whole database, but the catch is that am not able to view the contents as they are encrypted using UTF-8 (if am not wrong). When i open the uploaded file the encrypted text starts with SQLite format 3 but then the other entered data is encrypted.
Here is a sample of my code that implements the upload, How can i get this file decrypted back to normal text/characters?
public void doUpload(String filepath, String filename) {
HttpClient httpClient = new DefaultHttpClient();
try {
httpClient.getParams().setParameter("http.socket.timeout",new Integer(90000));
post = new HttpPost(new URI("http://10.0.2.2:8080/Force/sync"));
File file = new File(filepath);
FileEntity entity;
if (filepath.substring(filepath.length() - 2, filepath.length()).equalsIgnoreCase("db" || filepath.substring(filepath.length() - 3, filepath.length()).equalsIgnoreCase("log")) {
entity = new FileEntity(file, "text/plain; charset=\"SQLite format 3\"");
entity.setChunked(true);
} else {
entity = new FileEntity(file, "binary/octet-stream");
entity.setChunked(true);
}
post.setEntity(entity);
post.addHeader(filepath, filename);
HttpResponse response = httpClient.execute(post);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
} else {
// Here every thing is fine.
}
HttpEntity resEntity = response.getEntity();
if (resEntity == null) {
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown();
}
}
This code is invoked at the click of the upload button, and the url invokes a servlet (sync) that handles the uploaded file.
I will appreciate any asist.
Regards.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Close only a specific tab with firefox extension i'm developing a firefox extension and i want to be able to close a specific tab. For example if there are many open tabs in the browser o want to close only the tab with a specific url.
I know that i can use gBrowser.removeTab(tab) but i don't know how to get tab object.
On the other hand i can get the browser that corresponds to the url but the param of the removeTab() function must be a "tab object". How cat i get the tab object.
Any ideas?
A: tabbrowser.getBrowserForTab() method is actually the easiest way of associating browsers with tabs. So you would do something like this:
var tabs = gBrowser.tabs;
for (var i = tabs.length - 1; i >= 0; i--)
{
var tab = tabs[i];
var browser = gBrowser.getBrowserForTab(tab);
if (browser.currentURI && browser.currentURI.spec == "...")
gBrowser.removeTab(tab);
}
A: I think you can use this method: gBrowser.removeCurrentTab(); this example closes the currently selected tab.
For more code, please refers this link: https://developer.mozilla.org/en/Code_snippets/Tabbed_browser
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633547",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Is there any way to sort strings in all languages? I have this code. It sorts correctly in French and Russian. I used Locale.US and it seems to be right. Is this solution do right with all languages out there? Does it work with other languages? For example: Chinese, Korean, Japanese... If not, what is the better solution?
public class CollationTest {
public static void main(final String[] args) {
final Collator collator = Collator.getInstance(Locale.US);
final SortedSet<String> set = new TreeSet<String>(collator);
set.add("abîmer");
set.add("abîmé");
set.add("aberrer");
set.add("abhorrer");
set.add("aberrance");
set.add("abécédaire");
set.add("abducteur");
set.add("abdomen");
set.add("государственно-монополистический");
set.add("гостить");
set.add("гостевой");
set.add("гостеприимный");
set.add("госпожа");
set.add("госплан");
set.add("господи");
set.add("господа");
for(final String s : set) {
System.out.println(s);
}
}
}
Update:
Sorry, I don't require this set must contain all languages in order. I mean this set contain one language and sort correctly in every languages.
public class CollationTest {
public static void main(final String[] args) {
final Collator collator = Collator.getInstance(Locale.US);
final SortedSet<String> set = new TreeSet<String>(collator);
// Sorting in French.
set.clear();
set.add("abîmer");
set.add("abîmé");
set.add("aberrer");
set.add("abhorrer");
set.add("aberrance");
set.add("abécédaire");
set.add("abducteur");
set.add("abdomen");
for(final String s : set) {
System.out.println(s);
}
// Sorting in Russian.
set.clear();
set.add("государственно-монополистический");
set.add("гостить");
set.add("гостевой");
set.add("гостеприимный");
set.add("госпожа");
set.add("госплан");
set.add("господи");
set.add("господа");
for(final String s : set) {
System.out.println(s);
}
}
}
A: Because of every language has its own alphabetic order you can not. For example,
Russian language as you stated has с letter has a different order than Turkish language.
You should always use collator. What I can suggest you is to us Collection API.
//
// Define a collator for German language
//
Collator collator = Collator.getInstance(Locale.GERMAN);
//
// Sort the list using Collator
//
Collections.sort(words, collator);
For futher information check and as stated here
This program shows what can happen when you sort the same list of words with two different collators:
Collator fr_FRCollator = Collator.getInstance(new Locale("fr","FR"));
Collator en_USCollator = Collator.getInstance(new Locale("en","US"));
The method for sorting, called sortStrings, can be used with any Collator. Notice that the sortStrings method invokes the compare method:
public static void sortStrings(Collator collator,
String[] words) {
String tmp;
for (int i = 0; i < words.length; i++) {
for (int j = i + 1; j < words.length; j++) {
if (collator.compare(words[i], words[j]) > 0) {
tmp = words[i];
words[i] = words[j];
words[j] = tmp;
}
}
}
}
The English Collator sorts the words as follows:
peach
péché
pêche
sin
According to the collation rules of the French language, the preceding list is in the wrong order. In French péché should follow pêche in a sorted list. The French Collator sorts the array of words correctly, as follows:
peach
pêche
péché
sin
A: Even if you could accurately detect the language being used, useful collation orders are usually specific to a particular language+country combination. And even within a language+country, collation can vary depending on usage or certain customisations.
However, if you do need to sort arbitrary sets of text, your best bet is the Unicode Collation Algorithm, which defines a language-independent collation for any Unicode text. The algorithm is customisable, but doesn't necessary give results that make sense to any one culture (and definitely not across them).
Java's collation classes don't implement this algorithm, but it is available as part of ICU's RuleBaseCollator.
A: As far I know, the Chinese do not have any order for their language, the Japanes possible have the order in the Hiragana or Katakana, but in Kanji it is doubtful. But in computers sience everything is represented by numbers same thing goes for languages sings. Each sign correspond to unique UNICODE number. So this might be the solution for you, sort the words using their UNICODE positions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633552",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: How to programmatically define a global function within a function or method? For example,
def makeFunction name
... #define a function with the name supplied
end
makeFunction 'functionMade'
functionMade
I know it's possible to make a global variable $functionMade through lambda or proc, but is it possible to make it really a function without the $ prefix?
A: i think via class_eval on Kernel:
Kernel.class_eval <<-RUBY
def abc
puts 'abc'
end
RUBY
but i wouldn't recommend that. what do you need it for, or are you just curious?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jquery remove part of href that is dynamic In this href:
<a href="/Lists/ListeActualitesCarrousel/4_.000/DispForm.aspx?ID=4" class="">Lire l'article</a>
This part /ListeActualitesCarrousel/4_.000/ is dynamic and can change, I would like to remove it. Thus, the URL will become:
<a href="/Lists/ListeActualitesCarrousel/DispForm.aspx?ID=4" class="">Lire l'article</a>
How can that be done?
A: Try:
$('a').attr('href',$('a').attr('href').replace(/\/(\d)_.(\d{3})\//,'/'));
For Multiple hrefs : -
$('a').each(function(){
$(this).attr('href',$(this).attr('href').replace(/\/(\d)_.(\d{3})\//,'/'));
})
A: $("a").each(function() {
var pattern = /\d+_\.\d+\//im,
href = this.href;
if(pattern.test(href)) {
this.href = href.replace(pattern ,"");
}
});
Im guessing it can be anything like 11_.123144/ as a dynamic value at the moment.
A: $('a').attr('href',function(i,h){ return h.replace(/(ListeActualitesCarrousel/)(.?)/(D.)/,"$1$3"); });
demo:
http://jsfiddle.net/LzMse/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633554",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ASP.NET Is it possible to call methods within Server Tag using Eval()? I have an aspx page which contains a repeater. I can output data using Eval() but I want to know if it is possible to call a method that belongs to another class and pass it the value of Eval()?
For example, in the <ItemTemplate> section of the repeater:
<ItemTemplate>
<tr>
<td>
<%# ClassName.Method( Eval("value1") ) %>
</td>
<td>
<%# Eval("value2") %>
</td>
</tr>
</ItemTemplate>
If it is possible to do this, what is the correct way to do it?
A: Yes, but you need to provide the full name and to cast the result of the Eval function, which returns System.Object instances.
<%# Namespace.ClassName.Method( (string)Eval("value1") ) %>
Here, method is public static, but you can use instance methods also.
<%# new Namespace.ClassName((string)Eval("value1")).Method2((int)Eval("value2")) %>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Setting selected value in select list I have a Spring form that user fill. That form includes select dropdowns with multiple options.
I must provide a page, where user can mofidy the form values once sent. That means I need selects where the option once selected is selected, and the other ones available in selectlist. Can anyone help me how to set the orginal option selected?
options are type id = int and label = string
A: If you are using Command form-backing objects, you can use the Spring MVC Form taglib. This taglib will take care of the binding and selecting for you. Here's a fairly comprehensive example, although it doesn't use all the annotations: http://www.vaannila.com/spring/spring-form-tags-1.html.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java RESTful Web Service - Annotate an Interface instead of a Class I am trying to setup a simple web service (deploy on tomcat) which goes like this:
@Path("/api")
public interface Api {
@GET
@Path("categ")
public String getCateg();
}
and I have the following class implementing the interface:
public class RAPI implements API {
public String getCateg() { ... }
}
My web.xml looks as follows:
<servlet>
<servlet-name>API</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.api.resources</param-value> <!-- THIS IS CORRECT -->
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>API</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
But when I try to deploy on Tomcat I get the following (rather expected error):
com.sun.jersey.api.core.ScanningResourceConfig init
INFO: No provider classes found.
Which (not copied the whole trace here) tells me that although it found the API interface it cannot instantiate it.
How can I declare which of the implementing classes will actually act as the REST web service?
A: Having an interface annotated with JAX-RS allows you to create remote proxy clients. We do this with Apache CXF, but I haven't tried it with Jersey.
EG in my Spring config I can have;
<jaxrs:client id="myClient" inheritHeaders="true"
address="http://myhost/rs"
serviceClass="com.mycorp.restful.MyServiceInterface">
<jaxrs:headers>
<entry key="Accept" value="application/xml"/>
</jaxrs:headers>
</jaxrs:client>
I can now use this spring bean by just calling the methods. I don't have to create a Client and I don't have to care about the relative paths of the different RS services it defines.
A: As for using Interface for REST Service it is a good idea IMHO. But one thing do not annotate Interface itself leave it for implementation. This way you may have more flexibility. For instance,
public Interface Readable {
@GET
@Path("/read/{id}")
public String read(@PathParam("id") Integer id);
}
@Service
@Path("/book")
public class Book implements Readable, ... {
...
public String read(Integer id){...}
}
As for Jersey proxy check this:
https://jersey.java.net/project-info/2.0/jersey/project/jersey-proxy-client/dependencies.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633575",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how to fit the image perfectly in the webview thats is parsed from Wordpress rssfeed I m parsing this rss feed ("http://rss.marshillchurch.org/mhcvision") which is a wordpress blog and displaying it in tableview .clicking on the tableview row takes you to a detail view.I m parsing the following tags where the detail view contains the data from the content:encoded...the problem is the image size is too big to fit the detail view screen,which leads to horizontal scrolling...how to fit the image perfectly in the iphone webview 320X220...any help is much appreciated below is the image and the code..
- (void)viewDidLoad {
[super viewDidLoad];
self.itemTitle.text=[item objectForKey:@"title"];
[self.itemSummary loadHTMLString:[item objectForKey:@"content:encoded"] baseURL:nil];
[self.itemSummary setClipsToBounds:YES];
self.itemSummary.opaque=NO;
self.itemSummary.backgroundColor=[UIColor clearColor];
}
A: You can do this in two ways:
The first (easiest) is enabling the Scales Page to Fit property in the IB attributes inspector of the webView.
The second is processing the html code of the entry and adjusting the width of the image to make it fit your screen.
I don't know much of HTML (Correct me if I'm wrong) but, after googling a little bit found that this can be accomplished using:
<img src="yourImagePath" width="100%" alt="">
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android Location in background i'm new in java/android app and i'm creating an app that uses user-location. I want the location to be updated at the begining of the app.
The problem is that my location class is an activity and i don't want to show another contentview for this class.
Actually, i want the location thing to be done in background, without changing the UI, in a separated class.
Is it possible? How?
Thanks :P
A: There is no need to put the location in a different activity, the LocationManager already does it in the background:
public void getLocation(){
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
gpsLocationListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onLocationChanged(Location location) {
//do something with the new location
if (location != null)
gpsLocation = location;
}
};
gpsLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 0, gpsLocationListener);
}
A: Using the LocationManager you should be able to use what ever kind of activity (or service) you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Want to position the background image in the middle Hello on my login page I have a background image. Currently the image is centered but not centered the way I want it. I want it so the image is always centered in the middle of the screen. Curently, my image is centered but is positioned at the top of the page. The image need to be positioned in the middle of the screen, and kept centered.
login.html
<body style="background-image: url({{MEDIA_URL}}/admin_media/img/admin/bigstock_Photo_Showing_Financial_Growth_1339836.jpg); background-position: 50% 50%; background-repeat:no-repeat;">
A: may be you have write like this :
background-position: center center;
EDIT:
may be there problem with the body because it not takes screen entire height so if you want an image show in the center of the screen then write
html,body{height:100%;}
body{
background:url(http://www.poster.net/van-gogh-vincent/van-gogh-vincent-sternennacht-2601013.jpg) no-repeat fixed center center;
}
check the example http://jsfiddle.net/sandeep/m2fZs/2/
A: Instead of continuing to post comments, I thought it might be smarter to create a new answer.
Would something like this demo work for you? (replace 'fixed' with 'scroll' , if you want the img to scroll up and down with the page)
A: try it like this:
#element {
background-attachment:fixed;
background-position:center;
}
this should work!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Using EventWaitHandle class in Process A I need to receive an event from Proces B. I decided to use EventWaitHandle.
In both processes i write this code:
var evhandle = new EventWaitHandle(false, EventResetMode.AutoReset,"MyGUID1221");
then in process A i invoke Set() method:
evhandle.Set();
How i can to receive "MyGUID1221" event in process B and do some actions?
How to make "MyGUID1221"Listener?
Thanks.
A: The "MyGUID121" is just the name for the system-wide event.
You listen (read wait) for the event by using the WaitOne - method
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to handle alternating rows dynamically? Consider the following example: (live demo here)
HTML:
<div class="wrapper">
<div city_id="1" class="odd">Street Name #1 in city 1</div>
<div city_id="3" class="even">Street Name #2 in city 3</div>
<div city_id="2" class="odd">Street Name #3 in city 2</div>
<div city_id="1" class="even">Street Name #4 in city 1</div>
<div city_id="1" class="odd">Street Name #5 in city 1</div>
<div city_id="3" class="even">Street Name #6 in city 3</div>
<div city_id="2" class="odd">Street Name #7 in city 2</div>
<div city_id="3" class="even">Street Name #8 in city 3</div>
<div city_id="1" class="odd">Street Name #9 in city 1</div>
</div>
<select>
<option value="">Please select...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
CSS:
.odd {
background-color: #777;
}
.even {
background-color: #aaa;
}
JS:
$(function() {
$("select").change(function() {
var city_id = $("option:selected", this).val();
$("div[city_id]").each(function() {
$(this).toggle($(this).attr("city_id") == city_id);
});
});
});
I would like to keep the alternating coloring even when some rows are hidden.
Is that possible to achieve this with pure CSS ?
If no, how would you do this using Javascript/jQuery ?
A: Here's a simple solution . Dynamically change the row's class while the selected index changes
http://jsfiddle.net/4Bjbc/5/
$(function() {
$("select").change(function() {
var city_id = $("option:selected", this).val();
$("div[city_id]").each(function() {
$(this).toggle($(this).attr("city_id") == city_id);
}).filter(":visible") ///filter the visible ones
.attr("class",function(index,$class){
///if you don't want to miss out the other classes
return index%2 == 0 ? $class.replace("odd","even") : $class.replace("even","odd");
});
});
});
A: You can use CSS for it:
.wrapper div:nth-child(even) { background-color: #777; }
.wrapper div:nth-child(odd) { background-color: #aaa; }
However, it won't take hidden rows into account. To achieve this, you need to restrict the div selector even more:
.wrapper div.visible:nth-child(even) { background-color: #777; }
.wrapper div.visible:nth-child(odd) { background-color: #aaa; }
Then you just need to ensure that all visible elements have the visible class.
A: you need from javascript to set the class odd or even by walking through the items and if they are visible alternate the class
A: With jquery you could use in the change event:
$('.wrapper div:visible:even').css({
'background-color': '#777'
});
$('.wrapper div:visible:odd').css({
'background-color': '#aaa'
});
FULL CODE
$("select").change(function() {
var city_id = $("option:selected", this).val();
$("div[city_id]").each(function() {
$(this).toggle($(this).attr("city_id") == city_id);
});
$('.wrapper div:visible:even').css({
'background-color': '#777'
});
$('.wrapper div:visible:odd').css({
'background-color': '#aaa'
});
});
This way it sets the background color taking into account only visible rows
fiddle here: http://jsfiddle.net/4Bjbc/3/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633588",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Center page in IE7 & page moves after clicking menu items My page seems to be centered in all modern browsers except IE7. In CSS I have simply:
html, body {
width: 1000px;
margin: auto auto;
}
and it doesn't work.
Another issue for all browsers is that whole page slightly moves after clicking menu items. E.g. choosing second menu item causes thah page is shifted to the right compared to third page. Could you help me how to solve these problems. TIA
A: To fix the first issue, remove html from the selector:
body {
width: 1000px;
margin: auto auto;
}
The second issue is caused by there not always being a vertical scrollbar, which changes the width of the page and so causes a slight horizontal shift.
Fix it by adding this, which forces there to always be a vertical scrollbar:
html {
overflow-y: scroll
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633600",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: File access speed
I have got a theoretical question:
I think to use files that store an object's position.(each line contains coordinates x and y)
The data is going to be read from the file 3 times per second.
Is the delay 0.3 s of reading a coordinates from the file is too small? Will my program get necessary information in time?
Thanks.
A: Technically, I'd imagine that you could easily read this amount of data from a file at 3 times per second - but this seems like an odd design approach? Perhaps you can expand on what you're trying to achieve for some different ideas?
A: 540 objects in array is not too much, if it is just texts / numbers. Just do the read-write job in memory. You can write the array to file after the 3-minute.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Scalaz's traverse_ with IO monad I want to use IO monad.
But this code do not run with large file.
I am getting a StackOverflowError.
I tried the -DXss option, but it throws the same error.
val main = for {
l <- getFileLines(file)(collect[String, List]).map(_.run)
_ <- l.traverse_(putStrLn)
} yield ()
How can I do it?
I wrote Iteratee that is output all element.
def putStrLn[E: Show]: IterV[E, IO[Unit]] = {
import IterV._
def step(i: IO[Unit])(input: Input[E]): IterV[E, IO[Unit]] =
input(el = e => Cont(step(i >|> effects.putStrLn(e.shows))),
empty = Cont(step(i)),
eof = Done(i, EOF[E]))
Cont(step(mzero[IO[Unit]]))
}
val main = for {
i <- getFileLines(file)(putStrLn).map(_.run)
} yield i.unsafePerformIO
This is also the same result.
I think to be caused by IO implementation.
A: This is because scalac is not optimizing loop inside getReaderLines for tail calls. loop is tail recursive but I think the case anonymous function syntax gets in the way.
Edit: actually it's not even tail recursive (the wrapping in the IO monad) causes at least one more call after the recursive call. When I was doing my testing yesterday, I was using similar code but I had dropped the IO monad and it was then possible to make the Iteratee tail recursive. The text below, assumes no IO monad...
I happened to find that out yesterday while experimenting with iteratees. I think changing the signature of loop to this will help (so for the time being you may have to reimplement getFilesLines and getReaderLines:
@annotations.tailrec
def loop(it: IterV[String, A]): IO[IterV[String, A]] = it match {
// ...
}
We should probably report this to the scalaz folk (and may be open an enhancement ticket for scala).
This shows what happens (code vaguely similar to getReaderLines.loop):
@annotation.tailrec
def f(i: Int): Int = i match {
case 0 => 0
case x => f(x - 1)
}
// f: (i: Int)Int
@annotation.tailrec
def g: Int => Int = {
case 0 => 0
case x => g(x - 1)
}
/* error: could not optimize @tailrec annotated method g:
it contains a recursive call not in tail position
def g: Int => Int = {
^
*/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633609",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: facebook chat using asmack on android with the new access token I have a FB chat client developed for Android. I've been using facebook android-sdk to obtain the access token from a user. Using asmack, user was logged into the chat. Token was in the form: 226409362971500|3b29bc82baa7901a9baca042.4-72793766|9eb417f06fc376897222938295a0dd0c The code I used was:
XMPPConnection xmpp = new XMPPConnection(config);
SASLAuthentication.registerSASLMechanism("DIGEST-MD5", SASLDigestMD5Mechanism.class);
SASLAuthentication.supportSASLMechanism("DIGEST-MD5", 0);
xmpp.connect();
xmpp.login("226409362971500", "3b29bc82baa7901a9fbaca042.4-72793766|9eb417f06fc376897222938295a0dd0c", "Application");
Now it seems that Facebook has changed the token format. I have tried logging in with the old token, but I always get XMPPException. I've tried logging in with the new access token:
xmpp.login(token, "Application"),
but still no luck.
Any idea how to solve this?
A: After a bit of research (php example on the official FB documentation is really good), I came to a following conclusion:
1. xmpp connection must use ssl
2. in a response, session_key must be replaced with access_token
In short:
ConnectionConfiguration config = new ConnectionConfiguration("chat.facebook.com", 5222);
config.setSASLAuthenticationEnabled(true);
config.setSecurityMode(ConnectionConfiguration.SecurityMode.enabled);
XMPPConnection xmpp = new XMPPConnection(config);
SASLAuthentication.registerSASLMechanism("X-FACEBOOK-PLATFORM",SASLXFacebookPlatformMechanism.class);
SASLAuthentication.supportSASLMechanism("X-FACEBOOK-PLATFORM", 0);
xmpp.connect();
xmpp.login(appSecret, accessToken, "Application");
SASLXFacebookPlatformMechanism is my class which extends from org.jivesoftware.smack.sasl.SASLMechanism
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: WiX custom license file: setup shows links with < > I created a WiX 3.5 setup with a custom license file by putting this into the .wxs file:
<WixVariable Id="WixUILicenseRtf" Value="License.rtf" />
This works perfectly and the link is displayed when I run the created .msi file.
(I'm using the WixUI_InstallDir Dialog Set)
Now I want to put a hyperlink into the license file.
I just put the link into the file by opening it in WordPad and pasting http://mylink.com (WordPad turns it into a hyperlink automatically).
When I compile that in WiX, the license agreement dialog shows the link like this:
<http://mylink.com>
I noticed that this seems to relate to WordPad creating a hyperlink automatically (see above).
When I remove the http:// part from the link in the license file, WordPad doesn't recognize it as a link anymore and in the compiled .msi file, the < and > in the license agreement dialog go away.
Any ideas how I can get rid of the additional < and >, except putting the link into the license file without the http:// part?
EDIT:
Okay, maybe I didn't think enough when I used the word "hyperlink".
What I actually meant was: It does not have to be an actual clickable hyperlink.
I just want the adress of my web page to be displayed at the top of the license file.
I'm perfectly fine if it's just the URL as text (not clickable), but I want it to be displayed as I entered it, and not with < >.
The problem is that WordPad automatically turns any URL into a hyperlink as soon as I enter it, so I have no idea how to get the license agreement dialog to treat it as normal text.
A: Windows Installer doesn't support hyperlinks in the scrollable text control. This is why the link is not displayed correctly. Even if it was, nothing would happen when you click it because Windows Installer doesn't handle this event.
A hyperlink in a scrollable text control works only if you use an external UI which handles it.
Edit:
If you just want to display some text as a link, the usual approach is make it blue and underlined. As you already noticed Windows Installer doesn't show conventional hyperlinks correctly.
If you want to show a link as normal text, simply open the RTF file with a normal text editor (for example notepad.exe) and remove the hyperlink markers. Just follow the normal text formatting and you will easily spot the markers you want to remove.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: getting values from a select and moving them to a ul - jquery I am creating a plugin at the moment, that allows me to change select boxes into something pretty, I do this by changing the select boxes that are found on a page in to definition lists, with the definition description I am nesting a ul in it, and the li are the values from the select list.
I am having a problem however, if for example I have 3 select boxes on the page I get a strange mistake, and I cannot pinpoint where in my code I am going wrong but what is that multiple dd are being added to each dl so for example the second dl has 2 dd where as it should have one, like the 3rd select box should have 1 dd but it has 3, it seems like the amount of dd's created matches the index of the loop. How can I make so that only one dd, is created per dl, and that correct options are added.
This is my plugin code,
/***********
* Select-Me create pretty select lists using a <ul> inplace of the <select>
* Author: Simon Ainley (on behalf of The Factory Agency)
* Version: 0.0.1
***********/
(function($){
$.fn.selectMe = function(options) {
var defaults = {
select_text : null,
remove_first_value : false,
speed : 1000
}
var options = $.extend(defaults, options);
return this.each(function(index) {
//get an instance of the object we are working with
var obj = $(this);
var obj_name = obj.attr('name');
console.log(obj_name);
obj.closest('form').append('<input type="hidden" class="dropdown_value" value="" name="'+obj_name+'"/>');
var options = $("option", obj);
var replacement_list_heading = "<dl class='dropdown "+obj_name+"'><dt><span>"+defaults.select_text+"</span><a href=''>Go</a></dt></dl>";
obj.closest('form').prepend(replacement_list_heading);
var values_start = "<dd class='shadow_50'><ul></ul></dd>";
$(".dropdown").append(values_start);
if(defaults.remove_first_value == true) {
options.splice(0, 1);
}
options.each(function(index){
$(".dropdown." + obj_name + " dd ul").append(
'<li><a href="#"><span class="option">' +
$(this).text() + '</span><span class="value">' +
$(this).val() + '</span></a></li>'
);
});
obj.remove();
$('.dropdown li a').hover(function() {
$(this).parent('li').addClass('hover');
}, function() {
$(this).parent('li').removeClass('hover');
});
$(".dropdown dt a").click(function(e) {
$(this).closest("dl").find("dd").slideToggle(defaults.speed);
e.preventDefault();
});
$(".dropdown ul a").click(function(e) {
var value = $(this).find('span').text();
$(this).addClass('selected');
$(".dropdown_value").val(value);
$(".dropdown dt span").text($('.selected .option').text());
$(".dropdown dd").slideUp(defaults.speed);
$(this).removeClass('selected');
e.preventDefault();
});
});
};
})(jQuery);
I believe the problems are within these sections of the code,
var options = $("option", obj); - I think I need to differentiate between each set of options?
options.each(function(index){
$(".dropdown." + obj_name + " dd ul").append(
'<li><a href="#"><span class="option">' +
$(this).text() + '</span><span class="value">' +
$(this).val() + '</span></a></li>'
);
});
I believe this bit is just looping regardless of whether it should stop and add the options to a new dd?
any help would be great!
How I invoke my plugin,
$(".type select").selectMe({
select_text : "I'm looking for...",
remove_first_value : true,
});
$(".skill select").selectMe({
select_text : "Skill",
remove_first_value : true,
});
$(".gender select").selectMe({
select_text : "Gender",
remove_first_value : true,
});
and the HTML that is changed,
div class="grid_4">
<fieldset>
<div class="formRow drop_down">
<select name="type">
<option value="0" selected="selected">I'm looking for...</option>
<option value="1">actors</option>
<option value="2">presenters</option>
<option value="3">voice overs</option>
</select>
</div>
</fieldset>
</div>
<div class="grid_4">
<fieldset>
<div class="formRow drop_down">
<select name="skill">
<option value="0" selected="selected">Skill</option>
<option value="1">actors</option>
<option value="2">presenters</option>
<option value="3">voice overs</option>
<option value="4">dancers</option>
<option value="5">accents</option>
<option value="6">film</option>
<option value="7">tv</option>
</select>
</div>
</fieldset>
</div>
<div class="grid_4">
<fieldset>
<div class="formRow drop_down">
<select name="gender">
<option value="0" selected="selected">Gender</option>
<option value="1">male</option>
<option value="2">female</option>
</select>
</div>
</fieldset>
</div>
A: As it stands I'm not sure how it is executing at all, the selector ".type select" won't return anything from the HTML you've supplied - for that to work you'd need a <div class='type'> and </div> wrapped around your first <select>.
I can see why you are getting multiple DDs though, in your plugin you execute this:
var values_start = "<dd class='shadow_50'><ul></ul></dd>";
$(".dropdown").append(values_start);
That selector will target every .dropdown class you have created so far on the page. So for each subsequent call to the plugin, you'll be adding DD elements into the DL elements you have already created.
I think you want $(".dropdown." + obj_name).append(values_start); instead.
Because your event calls at the end are targetting the .dropdown class in general, they'll suffer from the same problem, creating multiple events on each of the elements.
You're making quite a few selector calls throughout your plugin which will cause jQuery to look through the entire DOM (e.g. in your options .each function). Since at quite a few of the steps you're just building up one single element which you can then add into the page, you should probably think about just building this up and adding it into the page without using further selectors.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQLAlchemy -Comparison between existing column value and potential update value I have a SQLAlchemy model which I'm updating with data from an XML file. I want to be notified where the new value differs from the old one.
I tried the simple:
if ModelInstance.Field <> NewValue:
print "Field has changed from", ModelInstance.Field, "to", NewValue
But this doesn't work in many cases because the types of the variables differ and would also not work if I added triggers to the model that changed the value on assignment.
So, what I'm asking is how I can compare the value of the field now with the value the field would hold if I assigned it the new value.
To clarify following the comment from DrColossus - I might read "1.0" as a string from the source file and the model might have an Integer type column containing the value 1. If you compare the two they aren't the same but if you were to assign "1.0" into the column the value would end up the same and it's that kind of thing I'm trying to detect.
A: You probably want an attribute set event.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633622",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Java api for Sharepoint server I would like to know if there is a java api for the sharepoint server.
Thanks a lot
A: I hope these API will help you
http://code.google.com/p/java-sharepoint-library/
http://code.google.com/p/sharepoint-wsdl/
http://dev.day.com/docs/en/crx/connectors/sharepoint/current.html
We can use SharePoint Web Services for connecting from java.
http://www.infoq.com/articles/swanson-moss-web-services
http://techiehojae.blogspot.in/2009/10/invoking-sharepoint-web-services.html
A: No there isn't. The SharePoint API is .NET only. However, you could use a Java .NET Bridge like this or you could use the SharePoint Webservices.
The SharePoint Webservices are "normal" SOAP webservices, so you consume them just like any other... i don't know java, but i assume there is a tool that let you create a (client) class based on a WSDL file. Here is a good tutorial showing you the basics.
A: There are a lot of alternatives int32 is only favorizing his own product I think, there are free libraries that can do this https://code.google.com/p/java-sharepoint-library/
A: JShare from Independentsoft. It looks very promising for Java and Android.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Solr Sorting for String Literal - PatternReplaceFilterFactory What is the regular expression for the following special characters in Solr.
,~,!,@,Double Quotes,Single Quote,Brackets,? and for every special characters.
My code is:
<fieldType name="Custom_sort" class="solr.TextField" sortMissingFirst="true" sortMissingLast="true" positionIncrementGap="100" autoGeneratePhraseQueries="true">
<analyzer type="query">
<tokenizer class="solr.KeywordTokenizerFactory"/>
<filter class="solr.LowerCaseFilterFactory" />
<filter class="solr.PatternReplaceFilterFactory" pattern="(#|!|[0-9]|'|~|^|"|[)]|[(])" replacement="" replace="all" />
</analyzer>
</fieldType>
but this does not work.
How to write pattern for these special characters.
A: Instead of handling for individual special characters use below, will remove all special characters except alphabets
<filter class="solr.PatternReplaceFilterFactory" pattern="([^a-z])" replacement="" replace="all" />
Why is the analyzer applied at query time, as you would use this as sort field and need to apply the analysis at index time ?
<fieldType name="Custom_sort" class="solr.TextField" sortMissingFirst="true" sortMissingLast="true" positionIncrementGap="100" autoGeneratePhraseQueries="true">
<analyzer type="index">
<tokenizer class="solr.KeywordTokenizerFactory"/>
<filter class="solr.LowerCaseFilterFactory" />
<filter class="solr.PatternReplaceFilterFactory" pattern="([^a-z])" replacement="" replace="all" />
</analyzer>
</fieldType>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Redo changes in oracle db after commit Is there any method to redo changes in Oracle db after commit? Please can anyone guide me
P.s. Oracle version I'm using is 10.1.1.8.
A: Flashback queries can help. Have a look at this article which briefs you on the details about it.
Flashback query allows a user to view the data quickly and easily the way it was at a particular time in the past, even when it is modified and committed, be it a single row or the whole table.
Oracle documentation on Flashback query is here.
A: Another interesting link i found.
http://oracleflash.com/25/Using-Oracle-LogMiner-to-undo-incorrectly-committed-changes.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Java compilation of a .java file without a public class Okay, so a java source file must have at least one public class and the file should be called "class-name.java". Fair enough.
Hence, if I have a class, then the following would compile:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
But what bugs me is that if I remove the 'public' access modifier from the above code, the code still compiles. I just don't get it. Removing it, the code looks like:
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
In the above code, since I removed the public access modifier, my class has default or package access, i.e. it can't be accessed from the outside world, only from within the package.
So my question is, how does the above code compile ? The file HelloWorld.java in this case does not have a public HelloWorld class (only a package-private HelloWorld.class) and thus to my understanding should not compile.
A: You can place non-public class in a file, and it's not a bug but feature.
Your problem is on level of packaging, not compile. Because you can compile this file with non-public class, but you can't call it from outside, so it's not working as application base class
Like this:
// [+] single file: SomeWrapper.java
public class SomeWrapper {
ArrayList<_PrivateDataType> pdt;
}
// [-] single file: SomeWrapper.java
// [+] single file: _PrivateDataType.java
class _PrivateDataType {
// members, functions, whatever goes here
}
// [-] single file: _PrivateDataType.java
A:
a java source file must have at least one public class and the file should be called class-name.java
Incorrect, a top level class does not have to be declared public. The JLS states;
If a top level class or interface type is not declared public, then it may be accessed only from within the package in which it is declared.
See http://java.sun.com/docs/books/jls/second_edition/html/names.doc.html#104285 section 6.6.1.
A: A main method is just like any other method. The only difference is that it may be invoked from the command line with the java command. Even if the main method is not visible from the command line, the class can still be used like any other Java class, and your main method may be invoked by another class in the same package. Therefore i makes sense that it compiles.
In Java main function are not special in any sense. There just exists a terminal command that is able to invoke static methods called main...
A: There are valid usages for a non public classes. So the compiler does not give error when you try to compile the file.
A: That's nothing to wonder about. I suppose this behavior is similar to the one of some C/C++-compiler.
Code like "void main() { /.../ }" will be compiled correctly by those compilers, although it is not standards-compliant code. Simply said, the compiler exchanges the "void" with "int".
I think a similar behavior is implemented by the java compiler.
A: When you do not specify the access modifier of the class (or its field or method), it is assigned "default" access. This means it is only accessible from within the same package (in this case, the default package).
The website Javabeginner.com has an article on the subject - you should become familiar with access modifiers in Java, either from this site, or others.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633631",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Android : How to set all uses-permission? How to use all the uses-permission in one single step? Anyone knows this? Thanks in Advance.
A: You can generate full list of permissions from \framework\base\core\res\AndroidManifest.xml (Android source code).
Here is full list for SDK 17.
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.SEND_SMS_NO_CONFIRMATION" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.RECEIVE_MMS" />
<uses-permission android:name="android.permission.RECEIVE_EMERGENCY_BROADCAST" />
<uses-permission android:name="android.permission.READ_CELL_BROADCASTS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.RECEIVE_WAP_PUSH" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.BIND_DIRECTORY_SEARCH" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.WRITE_CALL_LOG" />
<uses-permission android:name="android.permission.READ_SOCIAL_STREAM" />
<uses-permission android:name="android.permission.WRITE_SOCIAL_STREAM" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.WRITE_PROFILE" />
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
<uses-permission android:name="android.permission.READ_USER_DICTIONARY" />
<uses-permission android:name="android.permission.WRITE_USER_DICTIONARY" />
<uses-permission android:name="com.android.browser.permission.READ_HISTORY_BOOKMARKS" />
<uses-permission android:name="com.android.browser.permission.WRITE_HISTORY_BOOKMARKS" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
<uses-permission android:name="com.android.voicemail.permission.ADD_VOICEMAIL" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.INSTALL_LOCATION_PROVIDER" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIMAX_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIMAX_STATE" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH_STACK" />
<uses-permission android:name="android.permission.NFC" />
<uses-permission android:name="android.permission.CONNECTIVITY_INTERNAL" />
<uses-permission android:name="android.permission.RECEIVE_DATA_ACTIVITY_CHANGE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
<uses-permission android:name="android.permission.ACCOUNT_MANAGER" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.MANAGE_USB" />
<uses-permission android:name="android.permission.ACCESS_MTP" />
<uses-permission android:name="android.permission.HARDWARE_TEST" />
<uses-permission android:name="android.permission.NET_ADMIN" />
<uses-permission android:name="android.permission.REMOTE_AUDIO_PLAYBACK" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_PRIVILEGED_PHONE_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.USE_SIP" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_MEDIA_STORAGE" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.INTERACT_ACROSS_USERS" />
<uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" />
<uses-permission android:name="android.permission.MANAGE_USERS" />
<uses-permission android:name="android.permission.GET_DETAILED_TASKS" />
<uses-permission android:name="android.permission.REORDER_TASKS" />
<uses-permission android:name="android.permission.REMOVE_TASKS" />
<uses-permission android:name="android.permission.START_ANY_ACTIVITY" />
<uses-permission android:name="android.permission.RESTART_PACKAGES" />
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.SET_WALLPAPER" />
<uses-permission android:name="android.permission.SET_WALLPAPER_HINTS" />
<uses-permission android:name="android.permission.SET_TIME" />
<uses-permission android:name="android.permission.SET_TIME_ZONE" />
<uses-permission android:name="android.permission.EXPAND_STATUS_BAR" />
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.READ_SYNC_STATS" />
<uses-permission android:name="android.permission.SET_SCREEN_COMPATIBILITY" />
<uses-permission android:name="android.permission.ACCESS_ALL_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_GSERVICES" />
<uses-permission android:name="android.permission.SET_SCREEN_COMPATIBILITY" />
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
<uses-permission android:name="android.permission.FORCE_STOP_PACKAGES" />
<uses-permission android:name="android.permission.RETRIEVE_WINDOW_CONTENT" />
<uses-permission android:name="android.permission.SET_ANIMATION_SCALE" />
<uses-permission android:name="android.permission.PERSISTENT_ACTIVITY" />
<uses-permission android:name="android.permission.GET_PACKAGE_SIZE" />
<uses-permission android:name="android.permission.SET_PREFERRED_APPLICATIONS" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.MOUNT_FORMAT_FILESYSTEMS" />
<uses-permission android:name="android.permission.ASEC_ACCESS" />
<uses-permission android:name="android.permission.ASEC_CREATE" />
<uses-permission android:name="android.permission.ASEC_DESTROY" />
<uses-permission android:name="android.permission.ASEC_MOUNT_UNMOUNT" />
<uses-permission android:name="android.permission.ASEC_RENAME" />
<uses-permission android:name="android.permission.WRITE_APN_SETTINGS" />
<uses-permission android:name="android.permission.SUBSCRIBED_FEEDS_READ" />
<uses-permission android:name="android.permission.SUBSCRIBED_FEEDS_WRITE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.CLEAR_APP_CACHE" />
<uses-permission android:name="android.permission.ALLOW_ANY_CODEC_FOR_PLAYBACK" />
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
<uses-permission android:name="android.permission.DUMP" />
<uses-permission android:name="android.permission.READ_LOGS" />
<uses-permission android:name="android.permission.SET_DEBUG_APP" />
<uses-permission android:name="android.permission.SET_PROCESS_LIMIT" />
<uses-permission android:name="android.permission.SET_ALWAYS_FINISH" />
<uses-permission android:name="android.permission.SIGNAL_PERSISTENT_PROCESSES" />
<uses-permission android:name="android.permission.DIAGNOSTIC" />
<uses-permission android:name="android.permission.STATUS_BAR" />
<uses-permission android:name="android.permission.STATUS_BAR_SERVICE" />
<uses-permission android:name="android.permission.FORCE_BACK" />
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS" />
<uses-permission android:name="android.permission.INTERNAL_SYSTEM_WINDOW" />
<uses-permission android:name="android.permission.MANAGE_APP_TOKENS" />
<uses-permission android:name="android.permission.FREEZE_SCREEN" />
<uses-permission android:name="android.permission.INJECT_EVENTS" />
<uses-permission android:name="android.permission.FILTER_EVENTS" />
<uses-permission android:name="android.permission.RETRIEVE_WINDOW_INFO" />
<uses-permission android:name="android.permission.TEMPORARY_ENABLE_ACCESSIBILITY" />
<uses-permission android:name="android.permission.MAGNIFY_DISPLAY" />
<uses-permission android:name="android.permission.SET_ACTIVITY_WATCHER" />
<uses-permission android:name="android.permission.SHUTDOWN" />
<uses-permission android:name="android.permission.STOP_APP_SWITCHES" />
<uses-permission android:name="android.permission.READ_INPUT_STATE" />
<uses-permission android:name="android.permission.BIND_INPUT_METHOD" />
<uses-permission android:name="android.permission.BIND_ACCESSIBILITY_SERVICE" />
<uses-permission android:name="android.permission.BIND_TEXT_SERVICE" />
<uses-permission android:name="android.permission.BIND_VPN_SERVICE" />
<uses-permission android:name="android.permission.BIND_WALLPAPER" />
<uses-permission android:name="android.permission.BIND_DEVICE_ADMIN" />
<uses-permission android:name="android.permission.SET_ORIENTATION" />
<uses-permission android:name="android.permission.SET_POINTER_SPEED" />
<uses-permission android:name="android.permission.SET_KEYBOARD_LAYOUT" />
<uses-permission android:name="android.permission.INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.CLEAR_APP_USER_DATA" />
<uses-permission android:name="android.permission.DELETE_CACHE_FILES" />
<uses-permission android:name="android.permission.DELETE_PACKAGES" />
<uses-permission android:name="android.permission.MOVE_PACKAGE" />
<uses-permission android:name="android.permission.CHANGE_COMPONENT_ENABLED_STATE" />
<uses-permission android:name="android.permission.GRANT_REVOKE_PERMISSIONS" />
<uses-permission android:name="android.permission.ACCESS_SURFACE_FLINGER" />
<uses-permission android:name="android.permission.READ_FRAME_BUFFER" />
<uses-permission android:name="android.permission.CONFIGURE_WIFI_DISPLAY" />
<uses-permission android:name="android.permission.CONTROL_WIFI_DISPLAY" />
<uses-permission android:name="android.permission.BRICK" />
<uses-permission android:name="android.permission.REBOOT" />
<uses-permission android:name="android.permission.DEVICE_POWER" />
<uses-permission android:name="android.permission.NET_TUNNELING" />
<uses-permission android:name="android.permission.FACTORY_TEST" />
<uses-permission android:name="android.permission.BROADCAST_PACKAGE_REMOVED" />
<uses-permission android:name="android.permission.BROADCAST_SMS" />
<uses-permission android:name="android.permission.BROADCAST_WAP_PUSH" />
<uses-permission android:name="android.permission.MASTER_CLEAR" />
<uses-permission android:name="android.permission.CALL_PRIVILEGED" />
<uses-permission android:name="android.permission.PERFORM_CDMA_PROVISIONING" />
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES" />
<uses-permission android:name="android.permission.ACCESS_CHECKIN_PROPERTIES" />
<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" />
<uses-permission android:name="android.permission.BATTERY_STATS" />
<uses-permission android:name="android.permission.BACKUP" />
<uses-permission android:name="android.permission.CONFIRM_FULL_BACKUP" />
<uses-permission android:name="android.permission.BIND_REMOTEVIEWS" />
<uses-permission android:name="android.permission.BIND_APPWIDGET" />
<uses-permission android:name="android.permission.BIND_KEYGUARD_APPWIDGET" />
<uses-permission android:name="android.permission.MODIFY_APPWIDGET_BIND_PERMISSIONS" />
<uses-permission android:name="android.permission.CHANGE_BACKGROUND_DATA_SETTING" />
<uses-permission android:name="android.permission.GLOBAL_SEARCH" />
<uses-permission android:name="android.permission.GLOBAL_SEARCH_CONTROL" />
<uses-permission android:name="android.permission.SET_WALLPAPER_COMPONENT" />
<uses-permission android:name="android.permission.READ_DREAM_STATE" />
<uses-permission android:name="android.permission.WRITE_DREAM_STATE" />
<uses-permission android:name="android.permission.ACCESS_CACHE_FILESYSTEM" />
<uses-permission android:name="android.permission.COPY_PROTECTED_DATA" />
<uses-permission android:name="android.permission.CRYPT_KEEPER" />
<uses-permission android:name="android.permission.READ_NETWORK_USAGE_HISTORY" />
<uses-permission android:name="android.permission.MANAGE_NETWORK_POLICY" />
<uses-permission android:name="android.permission.MODIFY_NETWORK_ACCOUNTING" />
<uses-permission android:name="android.intent.category.MASTER_CLEAR.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.PACKAGE_VERIFICATION_AGENT" />
<uses-permission android:name="android.permission.BIND_PACKAGE_VERIFIER" />
<uses-permission android:name="android.permission.SERIAL_PORT" />
<uses-permission android:name="android.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY" />
<uses-permission android:name="android.permission.UPDATE_LOCK" />
Warning: you will have to set ProtectedPermission to ignored in lint config to build it.
A: In AndroidManifest.xml,
Select the "Permissions" tab along the bottom of the editor (Manifest - Application - Permissions - Instrumentation - AndroidManifest.xml), then "Add..." a "Uses Permission" and select the desired permission from the dropdown on the right, or just copy paste in the necessary one (such as the "android.permission.INTERNET" permission you required).
For More information, Follow this link:
http://developer.android.com/reference/android/Manifest.permission.html
A: Here is the code to print all permissions:
StringBuilder sb = new StringBuilder(" \n");
final Field[] manifestFields = Manifest.permission.class.getDeclaredFields();
for (final Field field : manifestFields) {
sb.append("<uses-permission android:name=\"android.permission."
+ field.getName() + "\"/>");
sb.append("\n");
if (sb.length() > 1000) {
Log.v(TAG, sb.toString());
sb = new StringBuilder();
}
}
A: All uses permissions in alphabetical order (updated for API 23)
<uses-permission android:name="android.permission.ACCESS_CACHE_FILESYSTEM"/>
<uses-permission android:name="android.permission.ACCESS_CHECKIN_PROPERTIES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY"/>
<uses-permission android:name="android.permission.ACCESS_DRM_CERTIFICATES"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FM_RADIO"/>
<uses-permission android:name="android.permission.ACCESS_IMS_CALL_SERVICE"/>
<uses-permission android:name="android.permission.ACCESS_INPUT_FLINGER"/>
<uses-permission android:name="android.permission.ACCESS_KEYGUARD_SECURE_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_MTP"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_CONDITIONS"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NOTIFICATIONS"/>
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY"/>
<uses-permission android:name="android.permission.ACCESS_PDB_STATE"/>
<uses-permission android:name="android.permission.ACCESS_SURFACE_FLINGER"/>
<uses-permission android:name="android.permission.ACCESS_VOICE_INTERACTION_SERVICE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIMAX_STATE"/>
<uses-permission android:name="android.permission.ACCOUNT_MANAGER"/>
<uses-permission android:name="android.permission.ADD_VOICEMAIL"/>
<uses-permission android:name="android.permission.ALLOW_ANY_CODEC_FOR_PLAYBACK"/>
<uses-permission android:name="android.permission.ASEC_ACCESS"/>
<uses-permission android:name="android.permission.ASEC_CREATE"/>
<uses-permission android:name="android.permission.ASEC_DESTROY"/>
<uses-permission android:name="android.permission.ASEC_MOUNT_UNMOUNT"/>
<uses-permission android:name="android.permission.ASEC_RENAME"/>
<uses-permission android:name="android.permission.BACKUP"/>
<uses-permission android:name="android.permission.BATTERY_STATS"/>
<uses-permission android:name="android.permission.BIND_ACCESSIBILITY_SERVICE"/>
<uses-permission android:name="android.permission.BIND_APPWIDGET"/>
<uses-permission android:name="android.permission.BIND_CARRIER_MESSAGING_SERVICE"/>
<uses-permission android:name="android.permission.BIND_CARRIER_SERVICES"/>
<uses-permission android:name="android.permission.BIND_CHOOSER_TARGET_SERVICE"/>
<uses-permission android:name="android.permission.BIND_CONDITION_PROVIDER_SERVICE"/>
<uses-permission android:name="android.permission.BIND_CONNECTION_SERVICE"/>
<uses-permission android:name="android.permission.BIND_DEVICE_ADMIN"/>
<uses-permission android:name="android.permission.BIND_DIRECTORY_SEARCH"/>
<uses-permission android:name="android.permission.BIND_DREAM_SERVICE"/>
<uses-permission android:name="android.permission.BIND_INCALL_SERVICE"/>
<uses-permission android:name="android.permission.BIND_INPUT_METHOD"/>
<uses-permission android:name="android.permission.BIND_INTENT_FILTER_VERIFIER"/>
<uses-permission android:name="android.permission.BIND_JOB_SERVICE"/>
<uses-permission android:name="android.permission.BIND_KEYGUARD_APPWIDGET"/>
<uses-permission android:name="android.permission.BIND_MIDI_DEVICE_SERVICE"/>
<uses-permission android:name="android.permission.BIND_NFC_SERVICE"/>
<uses-permission android:name="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"/>
<uses-permission android:name="android.permission.BIND_PACKAGE_VERIFIER"/>
<uses-permission android:name="android.permission.BIND_PRINT_SERVICE"/>
<uses-permission android:name="android.permission.BIND_PRINT_SPOOLER_SERVICE"/>
<uses-permission android:name="android.permission.BIND_REMOTEVIEWS"/>
<uses-permission android:name="android.permission.BIND_REMOTE_DISPLAY"/>
<uses-permission android:name="android.permission.BIND_ROUTE_PROVIDER"/>
<uses-permission android:name="android.permission.BIND_TELECOM_CONNECTION_SERVICE"/>
<uses-permission android:name="android.permission.BIND_TEXT_SERVICE"/>
<uses-permission android:name="android.permission.BIND_TRUST_AGENT"/>
<uses-permission android:name="android.permission.BIND_TV_INPUT"/>
<uses-permission android:name="android.permission.BIND_VOICE_INTERACTION"/>
<uses-permission android:name="android.permission.BIND_VPN_SERVICE"/>
<uses-permission android:name="android.permission.BIND_WALLPAPER"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH_MAP"/>
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED"/>
<uses-permission android:name="android.permission.BLUETOOTH_STACK"/>
<uses-permission android:name="android.permission.BODY_SENSORS"/>
<uses-permission android:name="android.permission.BRICK"/>
<uses-permission android:name="android.permission.BROADCAST_NETWORK_PRIVILEGED"/>
<uses-permission android:name="android.permission.BROADCAST_PACKAGE_REMOVED"/>
<uses-permission android:name="android.permission.BROADCAST_SMS"/>
<uses-permission android:name="android.permission.BROADCAST_STICKY"/>
<uses-permission android:name="android.permission.BROADCAST_WAP_PUSH"/>
<uses-permission android:name="android.permission.C2D_MESSAGE"/>
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.CALL_PRIVILEGED"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.CAMERA_DISABLE_TRANSMIT_LED"/>
<uses-permission android:name="android.permission.CAMERA_SEND_SYSTEM_EVENTS"/>
<uses-permission android:name="android.permission.CAPTURE_AUDIO_HOTWORD"/>
<uses-permission android:name="android.permission.CAPTURE_AUDIO_OUTPUT"/>
<uses-permission android:name="android.permission.CAPTURE_SECURE_VIDEO_OUTPUT"/>
<uses-permission android:name="android.permission.CAPTURE_TV_INPUT"/>
<uses-permission android:name="android.permission.CAPTURE_VIDEO_OUTPUT"/>
<uses-permission android:name="android.permission.CARRIER_FILTER_SMS"/>
<uses-permission android:name="android.permission.CHANGE_APP_IDLE_STATE"/>
<uses-permission android:name="android.permission.CHANGE_BACKGROUND_DATA_SETTING"/>
<uses-permission android:name="android.permission.CHANGE_COMPONENT_ENABLED_STATE"/>
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION"/>
<uses-permission android:name="android.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIMAX_STATE"/>
<uses-permission android:name="android.permission.CLEAR_APP_CACHE"/>
<uses-permission android:name="android.permission.CLEAR_APP_USER_DATA"/>
<uses-permission android:name="android.permission.CONFIGURE_WIFI_DISPLAY"/>
<uses-permission android:name="android.permission.CONFIRM_FULL_BACKUP"/>
<uses-permission android:name="android.permission.CONNECTIVITY_INTERNAL"/>
<uses-permission android:name="android.permission.CONTROL_INCALL_EXPERIENCE"/>
<uses-permission android:name="android.permission.CONTROL_KEYGUARD"/>
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES"/>
<uses-permission android:name="android.permission.CONTROL_VPN"/>
<uses-permission android:name="android.permission.CONTROL_WIFI_DISPLAY"/>
<uses-permission android:name="android.permission.COPY_PROTECTED_DATA"/>
<uses-permission android:name="android.permission.CRYPT_KEEPER"/>
<uses-permission android:name="android.permission.DELETE_CACHE_FILES"/>
<uses-permission android:name="android.permission.DELETE_PACKAGES"/>
<uses-permission android:name="android.permission.DEVICE_POWER"/>
<uses-permission android:name="android.permission.DIAGNOSTIC"/>
<uses-permission android:name="android.permission.DISABLE_KEYGUARD"/>
<uses-permission android:name="android.permission.DISPATCH_NFC_MESSAGE"/>
<uses-permission android:name="android.permission.DUMP"/>
<uses-permission android:name="android.permission.DVB_DEVICE"/>
<uses-permission android:name="android.permission.EXPAND_STATUS_BAR"/>
<uses-permission android:name="android.permission.FACTORY_TEST"/>
<uses-permission android:name="android.permission.FILTER_EVENTS"/>
<uses-permission android:name="android.permission.FLASHLIGHT"/>
<uses-permission android:name="android.permission.FORCE_BACK"/>
<uses-permission android:name="android.permission.FORCE_STOP_PACKAGES"/>
<uses-permission android:name="android.permission.FRAME_STATS"/>
<uses-permission android:name="android.permission.FREEZE_SCREEN"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS_PRIVILEGED"/>
<uses-permission android:name="android.permission.GET_APP_OPS_STATS"/>
<uses-permission android:name="android.permission.GET_DETAILED_TASKS"/>
<uses-permission android:name="android.permission.GET_PACKAGE_IMPORTANCE"/>
<uses-permission android:name="android.permission.GET_PACKAGE_SIZE"/>
<uses-permission android:name="android.permission.GET_TASKS"/>
<uses-permission android:name="android.permission.GET_TOP_ACTIVITY_INFO"/>
<uses-permission android:name="android.permission.GLOBAL_SEARCH"/>
<uses-permission android:name="android.permission.GLOBAL_SEARCH_CONTROL"/>
<uses-permission android:name="android.permission.GRANT_RUNTIME_PERMISSIONS"/>
<uses-permission android:name="android.permission.HARDWARE_TEST"/>
<uses-permission android:name="android.permission.HDMI_CEC"/>
<uses-permission android:name="android.permission.INJECT_EVENTS"/>
<uses-permission android:name="android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS"/>
<uses-permission android:name="android.permission.INSTALL_LOCATION_PROVIDER"/>
<uses-permission android:name="android.permission.INSTALL_PACKAGES"/>
<uses-permission android:name="android.permission.INSTALL_SHORTCUT"/>
<uses-permission android:name="android.permission.INTENT_FILTER_VERIFICATION_AGENT"/>
<uses-permission android:name="android.permission.INTERACT_ACROSS_USERS"/>
<uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL"/>
<uses-permission android:name="android.permission.INTERNAL_SYSTEM_WINDOW"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.INVOKE_CARRIER_SETUP"/>
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"/>
<uses-permission android:name="android.permission.KILL_UID"/>
<uses-permission android:name="android.permission.LAUNCH_TRUST_AGENT_SETTINGS"/>
<uses-permission android:name="android.permission.LOCAL_MAC_ADDRESS"/>
<uses-permission android:name="android.permission.LOCATION_HARDWARE"/>
<uses-permission android:name="android.permission.LOOP_RADIO"/>
<uses-permission android:name="android.permission.MANAGE_ACTIVITY_STACKS"/>
<uses-permission android:name="android.permission.MANAGE_APP_TOKENS"/>
<uses-permission android:name="android.permission.MANAGE_CA_CERTIFICATES"/>
<uses-permission android:name="android.permission.MANAGE_DEVICE_ADMINS"/>
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS"/>
<uses-permission android:name="android.permission.MANAGE_FINGERPRINT"/>
<uses-permission android:name="android.permission.MANAGE_MEDIA_PROJECTION"/>
<uses-permission android:name="android.permission.MANAGE_NETWORK_POLICY"/>
<uses-permission android:name="android.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS"/>
<uses-permission android:name="android.permission.MANAGE_USB"/>
<uses-permission android:name="android.permission.MANAGE_USERS"/>
<uses-permission android:name="android.permission.MANAGE_VOICE_KEYPHRASES"/>
<uses-permission android:name="android.permission.MASTER_CLEAR"/>
<uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL"/>
<uses-permission android:name="android.permission.MODIFY_APPWIDGET_BIND_PERMISSIONS"/>
<uses-permission android:name="android.permission.MODIFY_AUDIO_ROUTING"/>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
<uses-permission android:name="android.permission.MODIFY_NETWORK_ACCOUNTING"/>
<uses-permission android:name="android.permission.MODIFY_PARENTAL_CONTROLS"/>
<uses-permission android:name="android.permission.MODIFY_PHONE_STATE"/>
<uses-permission android:name="android.permission.MOUNT_FORMAT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.MOVE_PACKAGE"/>
<uses-permission android:name="android.permission.NET_ADMIN"/>
<uses-permission android:name="android.permission.NET_TUNNELING"/>
<uses-permission android:name="android.permission.NFC"/>
<uses-permission android:name="android.permission.NFC_HANDOVER_STATUS"/>
<uses-permission android:name="android.permission.NOTIFY_PENDING_SYSTEM_UPDATE"/>
<uses-permission android:name="android.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS"/>
<uses-permission android:name="android.permission.OEM_UNLOCK_STATE"/>
<uses-permission android:name="android.permission.OVERRIDE_WIFI_CONFIG"/>
<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS"/>
<uses-permission android:name="android.permission.PACKAGE_VERIFICATION_AGENT"/>
<uses-permission android:name="android.permission.PEERS_MAC_ADDRESS"/>
<uses-permission android:name="android.permission.PERFORM_CDMA_PROVISIONING"/>
<uses-permission android:name="android.permission.PERFORM_SIM_ACTIVATION"/>
<uses-permission android:name="android.permission.PERSISTENT_ACTIVITY"/>
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
<uses-permission android:name="android.permission.PROVIDE_TRUST_AGENT"/>
<uses-permission android:name="android.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT"/>
<uses-permission android:name="android.permission.READ_CALENDAR"/>
<uses-permission android:name="android.permission.READ_CALL_LOG"/>
<uses-permission android:name="android.permission.READ_CELL_BROADCASTS"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.READ_DREAM_STATE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_FRAME_BUFFER"/>
<uses-permission android:name="android.permission.READ_INPUT_STATE"/>
<uses-permission android:name="android.permission.READ_INSTALL_SESSIONS"/>
<uses-permission android:name="android.permission.READ_LOGS"/>
<uses-permission android:name="android.permission.READ_NETWORK_USAGE_HISTORY"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.READ_PRECISE_PHONE_STATE"/>
<uses-permission android:name="android.permission.READ_PRIVILEGED_PHONE_STATE"/>
<uses-permission android:name="android.permission.READ_PROFILE"/>
<uses-permission android:name="android.permission.READ_SEARCH_INDEXABLES"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.READ_SOCIAL_STREAM"/>
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS"/>
<uses-permission android:name="android.permission.READ_SYNC_STATS"/>
<uses-permission android:name="android.permission.READ_USER_DICTIONARY"/>
<uses-permission android:name="android.permission.READ_VOICEMAIL"/>
<uses-permission android:name="android.permission.READ_WIFI_CREDENTIAL"/>
<uses-permission android:name="android.permission.REAL_GET_TASKS"/>
<uses-permission android:name="android.permission.REBOOT"/>
<uses-permission android:name="android.permission.RECEIVE_BLUETOOTH_MAP"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.RECEIVE_DATA_ACTIVITY_CHANGE"/>
<uses-permission android:name="android.permission.RECEIVE_EMERGENCY_BROADCAST"/>
<uses-permission android:name="android.permission.RECEIVE_MMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_STK_COMMANDS"/>
<uses-permission android:name="android.permission.RECEIVE_WAP_PUSH"/>
<uses-permission android:name="android.permission.RECEIVE_WIFI_CREDENTIAL_CHANGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.RECOVERY"/>
<uses-permission android:name="android.permission.REGISTER_CALL_PROVIDER"/>
<uses-permission android:name="android.permission.REGISTER_CONNECTION_MANAGER"/>
<uses-permission android:name="android.permission.REGISTER_SIM_SUBSCRIPTION"/>
<uses-permission android:name="android.permission.REMOTE_AUDIO_PLAYBACK"/>
<uses-permission android:name="android.permission.REMOVE_DRM_CERTIFICATES"/>
<uses-permission android:name="android.permission.REMOVE_TASKS"/>
<uses-permission android:name="android.permission.REORDER_TASKS"/>
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
<uses-permission android:name="android.permission.RESTART_PACKAGES"/>
<uses-permission android:name="android.permission.RETRIEVE_WINDOW_CONTENT"/>
<uses-permission android:name="android.permission.RETRIEVE_WINDOW_TOKEN"/>
<uses-permission android:name="android.permission.REVOKE_RUNTIME_PERMISSIONS"/>
<uses-permission android:name="android.permission.SCORE_NETWORKS"/>
<uses-permission android:name="android.permission.SEND_RESPOND_VIA_MESSAGE"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.SERIAL_PORT"/>
<uses-permission android:name="android.permission.SET_ACTIVITY_WATCHER"/>
<uses-permission android:name="android.permission.SET_ALARM"/>
<uses-permission android:name="android.permission.SET_ALWAYS_FINISH"/>
<uses-permission android:name="android.permission.SET_ANIMATION_SCALE"/>
<uses-permission android:name="android.permission.SET_DEBUG_APP"/>
<uses-permission android:name="android.permission.SET_INPUT_CALIBRATION"/>
<uses-permission android:name="android.permission.SET_KEYBOARD_LAYOUT"/>
<uses-permission android:name="android.permission.SET_ORIENTATION"/>
<uses-permission android:name="android.permission.SET_POINTER_SPEED"/>
<uses-permission android:name="android.permission.SET_PREFERRED_APPLICATIONS"/>
<uses-permission android:name="android.permission.SET_PROCESS_LIMIT"/>
<uses-permission android:name="android.permission.SET_SCREEN_COMPATIBILITY"/>
<uses-permission android:name="android.permission.SET_TIME"/>
<uses-permission android:name="android.permission.SET_TIME_ZONE"/>
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
<uses-permission android:name="android.permission.SET_WALLPAPER_COMPONENT"/>
<uses-permission android:name="android.permission.SET_WALLPAPER_HINTS"/>
<uses-permission android:name="android.permission.SHUTDOWN"/>
<uses-permission android:name="android.permission.SIGNAL_PERSISTENT_PROCESSES"/>
<uses-permission android:name="android.permission.START_ANY_ACTIVITY"/>
<uses-permission android:name="android.permission.START_TASKS_FROM_RECENTS"/>
<uses-permission android:name="android.permission.STATUS_BAR"/>
<uses-permission android:name="android.permission.STATUS_BAR_SERVICE"/>
<uses-permission android:name="android.permission.STOP_APP_SWITCHES"/>
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.TEMPORARY_ENABLE_ACCESSIBILITY"/>
<uses-permission android:name="android.permission.TRANSMIT_IR"/>
<uses-permission android:name="android.permission.TRUST_LISTENER"/>
<uses-permission android:name="android.permission.TV_INPUT_HARDWARE"/>
<uses-permission android:name="android.permission.UNINSTALL_SHORTCUT"/>
<uses-permission android:name="android.permission.UPDATE_APP_OPS_STATS"/>
<uses-permission android:name="android.permission.UPDATE_CONFIG"/>
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS"/>
<uses-permission android:name="android.permission.UPDATE_LOCK"/>
<uses-permission android:name="android.permission.USER_ACTIVITY"/>
<uses-permission android:name="android.permission.USE_FINGERPRINT"/>
<uses-permission android:name="android.permission.USE_SIP"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.WRITE_APN_SETTINGS"/>
<uses-permission android:name="android.permission.WRITE_CALENDAR"/>
<uses-permission android:name="android.permission.WRITE_CALL_LOG"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_DREAM_STATE"/>
A: all Answer above are correct but one thing to remember we add permission in menifist..
as shown below
<manifest>
////////// all permission will be added here
<uses-permission android:name="android.permission.INTERNET" />
<application>
</application>
</manifest>
A:
package="com.myapp" >
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: PexChoose non generic methods Is there any way to specify the return type for PexChoose at runtime? For example PexChoose.Value(name, Type)?
This would be useful to make general models that generate values of different types depending on runtime contraints.
A: You could build your own helper class which will call the generic version via reflection.
For instance, to create a non-generic version of PexChoose.Value(string name)
public static class MyPexChoose
{
public static object Value(Type myType, string name)
{
// Find the PexChoose.Value() method which has a single string parameter
MethodInfo method = typeof(PexChoose).GetMethod("Value", new Type[1] {typeof(string)});
// Make and invoke the generic version of it
MethodInfo generic = method.MakeGenericMethod(myType);
return generic.Invoke(typeof(PexChoose), new object[1] { name });
}
}
Then the call
MyPexChoose(typeof(DateTime), "MyChosen");
is equivalent to
PexChoose<DateTime>("MyChosen");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why does Spongy Castle ignore the bcpg and openpgp packages Does anyone know why SpongyCastle is explicitly excluding openpgp and bcpg packages (amongst others) from being built? I would like to get OpenPGP support working and I will require a number of those classes to do so.
You can find the exclusions in the pom.xml file.
Out of curiosity, I cloned the repository and tried to include those packages. It seems to have been as simple as moving the contents of the bzip2 directory into the src directory and removing the 2 exclusions from the POM file. The result seems to build, and the resulting JAR file contains the classes I needed. Are there runtime issues that might pop up unpredictably?
A: Since v1.47 Spongy Castle has included the scpg-jdk15on artifact, supplying all the OpenPGP support from bcpg-jdk15on:
https://github.com/rtyley/spongycastle/pull/2#issuecomment-5057038
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to create Eclipse like Welcome page I want to create my own Welcome page like eclipse.I have search for but it shows for RCP Application but i want to create it inside Eclipse IDE So that when i click on menu, it should open Intro(help) page.
A: eclipse.ui.intro extension point
All you need to do is to extend org.eclipse.ui.intro.configExtension and provide your implementation.
<extension point="org.eclipse.ui.intro.configExtension">
<configExtension configId="org.eclipse.ui.intro.universalConfig"
content="intro/eclipse-tips.xml" />
</extension>
You have the whole tutorial here
http://eclipse.dzone.com/articles/short-tutorial-introwelcome
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Excel VBA - Search for string in worksheet I've got this Excel Workbook which I want to search for a specific string in Sheet1. If it finds it, enter a new value. But, the sheet is pretty huge, so I don't think it would be very efficient to loop through each cell. So, can I search through a range and find it that way?
This is what I've got so far:
Dim rngSearchRange as range
With ThisWorkbook.Sheets(1)
Set rngSearchRange = .Range("A2:A" & .Range("A" & Rows.Count).End(xlUp).Row)
End With
The string I'm looking for is the first value in an array of three values. So, how can I search this range for that specific string, find the position and then enter a new value?
I was thinking something along this:
Dim rngFindRange as range
Set rngFindRange = rngSearchRange.Find(var(0), LookIn:=xlValues, lookat:=xlWhole)
The var(0) is the value in the array I'm after. But this line doesn't really give me any results. Am I way off here?
A: something like this
Sub FindMe()
Dim ws As Worksheet
Dim rngSearchRange As Range
Dim rngFindRange As Range
Dim Var
Dim elemVar
Var = Array("apples", "oranges", "fruit")
Set ws = ThisWorkbook.Sheets(1)
Set rngSearchRange = ws.Range(ws.[a2], ws.Cells(Rows.Count, "A").End(xlUp))
For Each elemVar In Var
Set rngFindRange = rngSearchRange.Find(elemVar, LookIn:=xlValues, lookat:=xlWhole)
If Not rngFindRange Is Nothing Then
MsgBox elemVar & " found in " & rngFindRange.Address(0, 0)
Else
MsgBox elemVar & " not found in:"
End If
Next elemVar
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Combine SQL fields and Convert from bit to readable sentence If, for example, I had two fields such as 'Dog' and 'Cat' that defines whether a person has a dog or cat; and, they are bit types. And, I wanted to combine these fields for each person to say something like USER, 'has a dog and a cat' such as the following:-
SQL original --
select username, dog, cat from table
username dog cat
john 1 0
tim 1 1
SQL with combined --??
username petstatus
john 'has a dog but no cat'
tim 'has a dog and a cat'
Does anybody have any ideas on what would be the best way to achieve this type of functionality using SQL. Or, where can I get a copy of similar functionality.
Thanks,
Ric.
A: Try this :
select username,
case when dog = 1 and cat = 1 then 'has a dog and a cat'
when dog = 1 and cat = 0 then 'has a dog but no cat'
when dog = 0 and cat = 1 then 'has a cat but no dog'
when dog = 0 and cat = 0 then 'has a no cat and no dog' end as petstatus
from table
UPDATE : For more than 2 columns dynamically, you need to set text as like readable sentence by this way :
select username, 'has' +
replace(replace(dog,'1',' a dog'),'0',' no dog') +
replace(replace(cat,'1',' a cat'),'0',' no cat')
from table
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jquery validation plugin error placement I am using Jquery Validation Plugin. Here's my question - I have a simple form which is like this
<form id="form">
<label>Name</label>
<input type="text" name="name" id="name" class="required" minlength="2">
<span></span>
<label>Surname</label>
<input type="text" name="surname" id="surname" class="required" minlength="2>
<span></span>
<input type="submit" value="submit">
</form>
The validation script is customized like this -
$(function(){
$("#form").validate({
messages: {
name: "Please enter name.",
surname: "Please enter surname."
},
errorElement: "span",
errorPlacement: function(error, element) {
error.insertAfter(element);
}
});
});
The problem is, both the error messages are displayed in the first span tag. How can I correct that. Any suggestions as how to go about this?
Thanks!
A: Update the html to use label for
<label for="name">
Try - http://jsfiddle.net/EUWEE/1/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633660",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: linq to entity framework: something like isnull I have:
a = b.Sum(...) + c.Sum(...)
where b,c are entities.
The problem is: when at least one of (b.Sum(...), c.Sum(...)) is null then a will be null. I'd like null be treated as 0. How would I do this?
A: maybe something like this
a = ( b.Sum(...) + c.Sum(...)) ?? 0;
now if the expression is null, a will be 0;
A: At least in LINQ2SQL you can cast to int? manually and then handle the null case
a = ((int?)b.Sum(...) + c.Sum(...)).GetValueOrDefault();
A: I think you could use null coelesce for this:
a = (b.Sum(..) + c.Sum(...)) ?? 0;
NOTE: unchecked syntax! not sure what your sums are doing!
Have a look at the following MSDN article: http://msdn.microsoft.com/en-us/library/ms173224.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Comparing screen data at client side Is there any way I can check whether the user has changed any data on the web page between the page load and save button click. If the user has opened any page to edit some data and clicks the save button without changing any data on the screen then I need to display a message.
Thanks in advance.
A: I think setting a flag would be a good idea. Use global selectors to do such a thing.
var changed = false;
$("input").change(function(){
//something changed
changed = true;
});
Then if the users leaves the page, check if changed is true
A: I think what you are trying to do is check if the form is dirty (i.E. something has changed) and this dirty form plugin might help you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633662",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Declare a NSString in multiple lines Is there any way to declare a NSString in multiple lines? I want to write HTML code and store it into a NSString, and in multiple lines de code will be more readable. I want to do something like this:
NSString *html = @"\<html\>"
+ @"\<head\>"
+ @"\<title\>The Title of the web\</title\>"
+ @"\</head\>"
+ @"\<body\>"
[...]
A: This is an example:
NSString *html = [NSString stringWithFormat:@"<html> \n"
"<head> \n"
"<style type=\"text/css\"> \n"
"body {font-family: \"%@\"; font-size: %dpx;}\n"
"img {max-width: 300px; width: auto; height: auto;}\n"
"</style> \n"
"</head> \n"
"<body><h1>%@</h1>%@</body> \n"
"</html>", @"helvetica", 16, [item objectForKey:@"title"], [item objectForKey:@"content:encoded"]];
A: I know it's Objective-C question but it's pretty easy with Swift:
let multiline = """
first line
second line
without escaping characters
""";
A: NSString * html = @"line1\
line2\
line3\
line4";
And beware of tabs/spaces in the beginning of each line - they do count in this case.
A: Create an NSString with multiple lines to mimic a NSString read from a multi-line text file.
NSString * html = @"line1\n\
line2\n\
line3\n\
line4\n";
A \n on the last line is up to you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633664",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Finding string into a ByteArray. Is it a simple solution for that? What is the simpliest way to find an occurance of some sequance of bytes (string) in a long byte array?
thank you in advance!!
UPD: I tried to do
my_byte_array.toString().indexOf(needle_string);
the problem is that in flash/air string consist of utf8 characters, so indexOf will return value different from offset of "string" in a byte array (actually it's zip archive)
A: I believe this would work:
//needle_string is the sequence you want to find
my_byte_array.toString().indexOf(needle_string);
This will return -1 if the sequence is not found, and otherwise the index at which the sequence has been found.
A: Assuming the array is long enough that you don’t want to convert it to a string, I guess I’d just bite the bullet and do something like this:
function byteArrayContainsString
(haystack : ByteArray, needleString : String) : Boolean
{
const needle : ByteArray = new ByteArray
needle.writeUTFBytes(needleString)
return byteArrayIndexOf(haystack, needle) !== -1
}
function byteArrayIndexOf
(haystack : ByteArray, needle : ByteArray) : int
{
search: for (var i : int = 0; i < haystack.length; ++i) {
for (var j : int = 0; j < needle.length; ++j)
if (haystack[i + j] !== needle[j])
continue search
return i
}
return -1
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633668",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to avoid excessive screen flickering with GDI I'm sort of new to rendering graphics with GDI...
I made a paint program, and it works fine, it's just that it causes a lot of annoying screen flickering. I will admit my paint code is not really optimized (lack of time), but it shouldn't be super inefficient either, so I'm puzzled.
What I'm basically doing is creating a compatible DC on init, then create a compatible bitmap. Then I select it into the compatible DC, and paint to the compatible DC. Then I use BitBlit() to copy it to the window hDC...
Could anyone tell me the possible causes for this screen tearing?
EDIT: btw, screen flickering only occurs during the drawing of a path (before the path gets drawn to the hMemDC, it gets drawn to the hDC of the window)
Code samples:
(EDIT: If you need to see any more code that you think is relevant, comment and I'll edit)
Path::DrawTo(HDC)
bool Path::DrawTo(HDC hDC)
{
if(hDC == NULL || m_PointVector.size() <= 0) {
return false;
}
switch (m_Tool) {
case Tool_Pen:
{
Point2D p = m_PointVector.at(0);
if(m_PointVector.size() > 1) {
HPEN oldPen = (HPEN)SelectObject(hDC,m_hPen);
MoveToEx(hDC, p.x, p.y, nullptr);
for(UINT i = 1; i < m_PointVector.size(); ++i) {
p = m_PointVector.at(i);
LineTo(hDC,p.x,p.y);
}
SelectObject(hDC,oldPen);
break;
} //else
SetPixel(hDC,p.x-1,p.y,m_Col);
SetPixel(hDC,p.x,p.y,m_Col);
SetPixel(hDC,p.x+1,p.y,m_Col);
SetPixel(hDC,p.x,p.y-1,m_Col);
SetPixel(hDC,p.x,p.y+1,m_Col);
break;
}
case Tool_Line:
{
if(m_PointVector.size() > 1) {
Point2D p = m_PointVector.at(0);
HPEN oldPen = (HPEN)SelectObject(hDC,m_hPen);
MoveToEx(hDC, p.x, p.y, nullptr);
for(UINT i = 1; i < m_PointVector.size(); ++i) {
p = m_PointVector.at(i);
LineTo(hDC,p.x,p.y);
}
SelectObject(hDC,oldPen);
}
break;
}
case Tool_Ellipse:
{
if(m_PointVector.size() > 1) {
HPEN oldPen = (HPEN)SelectObject(hDC,m_hPen);
SelectObject(hDC,m_hBrush);
Point2D p1 = m_PointVector.at(0);
Point2D p2 = m_PointVector.at(1);
if(p1.x > p2.x) {
int iTemp = p1.x;
p1.x = p2.x;
p2.x = iTemp;
}
if(p1.y > p2.y) {
int iTemp = p1.y;
p1.y = p2.y;
p2.y = iTemp;
}
Ellipse(hDC,p1.x,p1.y,p2.x,p2.y);
SelectObject(hDC,oldPen);
}
break;
}
case Tool_Rectangle:
{
if(m_PointVector.size() > 1) {
HPEN oldPen = (HPEN)SelectObject(hDC,m_hPen);
SelectObject(hDC,m_hBrush);
Point2D p1 = m_PointVector.at(0);
Point2D p2 = m_PointVector.at(1);
if(p1.x > p2.x) {
int iTemp = p1.x;
p1.x = p2.x;
p2.x = iTemp;
}
if(p1.y > p2.y) {
int iTemp = p1.y;
p1.y = p2.y;
p2.y = iTemp;
}
Rectangle(hDC,p1.x,p1.y,p2.x,p2.y);
SelectObject(hDC,oldPen);
}
break;
}
case Tool_LineTrack:
{
HPEN oldPen = (HPEN)SelectObject(hDC,m_hPen);
SelectObject(hDC,m_hBrush);
int vSize = (int)m_PointVector.size();
Point2D p = m_PointVector.at(0);
if (vSize <= 1) {
Ellipse(hDC,p.x-10,p.y-10,p.x+10,p.y+10);
}
else {
//draw LineTrack
Point2D pTemp = m_PointVector.at(1);
MoveToEx(hDC,p.x,p.y,nullptr);
for (int i = 1; i < vSize; ++i) {
p = m_PointVector.at(i);
pTemp = m_PointVector.at(i-1);
LineTo(hDC,p.x,p.y);
Ellipse(hDC,pTemp.x-10,pTemp.y-10,pTemp.x+10,pTemp.y+10);
}
Ellipse(hDC,p.x-10,p.y-10,p.x+10,p.y+10);
}
SelectObject(hDC,oldPen);
break;
}
}
return true;
}
WndProc(HWND, UINT, WPARAM, LPARAM)
LRESULT MyApp::WndProc(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam)
{
if(iMsg == WM_CREATE)
{
CREATESTRUCT *pCS = (CREATESTRUCT*)lParam;
SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG)pCS->lpCreateParams);
}
else
{
//retrieve the stored "this" pointer
MyApp* pApp = (MyApp*)GetWindowLongPtr(hWnd, GWLP_USERDATA);
switch (iMsg)
{
case WM_PAINT:
{
pApp->Paint();
return 0;
}
case WM_COMMAND:
{
int wmId = LOWORD(wParam);
int wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_NEW:
{
////
return 0;
}
return 0;
case IDM_LOAD:
{
//////
return 0;
}
case IDM_SAVE:
{
//////
return 0;
}
case IDM_SAVEAS:
{
//////
return 0;
}
case IDM_COLOURMAIN:
{
COLORREF col;
if(MyWin32Funcs::OnColorPick(col)) {
pApp->m_pPath->SetColor1(col);
}
return 0;
}
case IDM_COLOURSECONDARY:
{
COLORREF col;
if(MyWin32Funcs::OnColorPick(col)) {
pApp->m_pPath->SetColor2(col);
}
return 0;
}
case IDM_PEN:
{
pApp->m_pPath->SetTool(Tool_Pen);
return 0;
}
case IDM_LINE:
{
pApp->m_pPath->SetTool(Tool_Line);
return 0;
}
case IDM_ELLIPSE:
{
pApp->m_pPath->SetTool(Tool_Ellipse);
return 0;
}
case IDM_RECTANGLE:
{
pApp->m_pPath->SetTool(Tool_Rectangle);
return 0;
}
case IDM_LINETRACK:
{
pApp->m_pPath->SetTool(Tool_LineTrack);
return 0;
}
default:
{
//////
return 0;
}
}
}
case WM_LBUTTONUP:
{
//////
Point2D p;
p.x = LOWORD(lParam);
p.y = HIWORD(lParam);
switch(pApp->m_pPath->GetTool()) {
case Tool_Pen:
{
pApp->m_bPaintToBitmap = true;
InvalidateRect(pApp->m_hWnd,NULL,true);
break;
}
case Tool_Ellipse:
{
pApp->m_bPaintToBitmap = true;
InvalidateRect(pApp->m_hWnd,NULL,true);
break;
}
case Tool_Rectangle:
{
pApp->m_bPaintToBitmap = true;
InvalidateRect(pApp->m_hWnd,NULL,true);
break;
}
case Tool_Line:
{
pApp->m_pPath->AddPoint(p,pApp->m_pBitmapPainter->GetBmpSize(),pApp->m_pBitmapPainter->GetBmpOffset());
InvalidateRect(pApp->m_hWnd,NULL,false);
break;
}
case Tool_LineTrack:
{
pApp->m_pPath->AddPoint(p,pApp->m_pBitmapPainter->GetBmpSize(),pApp->m_pBitmapPainter->GetBmpOffset());
InvalidateRect(pApp->m_hWnd,NULL,false);
break;
}
}
return 0;
}
case WM_RBUTTONUP:
{
//////
int x = LOWORD(lParam);
int y = HIWORD(lParam);
switch(pApp->m_pPath->GetTool()) {
case Tool_Line:
{
pApp->m_bPaintToBitmap = true;
InvalidateRect(pApp->m_hWnd,NULL,true);
break;
}
case Tool_LineTrack:
{
pApp->m_bPaintToBitmap = true;
InvalidateRect(pApp->m_hWnd,NULL,true);
break;
}
}
return 0;
}
case WM_LBUTTONDOWN:
{
Point2D p;
p.x = LOWORD(lParam);
p.y = HIWORD(lParam);
switch(pApp->m_pPath->GetTool()) {
case Tool_Pen:
pApp->m_pPath->AddPoint(p,pApp->m_pBitmapPainter->GetBmpSize(),pApp->m_pBitmapPainter->GetBmpOffset());
InvalidateRect(pApp->m_hWnd,NULL,false);
break;
}
}
case WM_MOUSEMOVE:
{
Point2D p;
p.x = LOWORD(lParam);
p.y = HIWORD(lParam);
if (wParam & MK_LBUTTON) {
switch(pApp->m_pPath->GetTool()) {
case Tool_Pen:
{
pApp->m_pPath->AddPoint(p,pApp->m_pBitmapPainter->GetBmpSize(),pApp->m_pBitmapPainter->GetBmpOffset());
InvalidateRect(pApp->m_hWnd,NULL,false);
break;
}
case Tool_Ellipse:
{
if( pApp->m_pPath->GetLen() >= 1) {
pApp->m_pPath->SetPointAt(1,p,pApp->m_pBitmapPainter->GetBmpSize(),pApp->m_pBitmapPainter->GetBmpOffset());
}
else {
pApp->m_pPath->AddPoint(p,pApp->m_pBitmapPainter->GetBmpSize(),pApp->m_pBitmapPainter->GetBmpOffset());
}
InvalidateRect(pApp->m_hWnd,NULL,false);
break;
}
case Tool_Rectangle:
{
if( pApp->m_pPath->GetLen() >= 1) {
pApp->m_pPath->SetPointAt(1,p,pApp->m_pBitmapPainter->GetBmpSize(),pApp->m_pBitmapPainter->GetBmpOffset());
}
else {
pApp->m_pPath->AddPoint(p,pApp->m_pBitmapPainter->GetBmpSize(),pApp->m_pBitmapPainter->GetBmpOffset());
}
InvalidateRect(pApp->m_hWnd,NULL,false);
break;
}
}
}
return 0;
}
case WM_CLOSE:
{
//////
return 0;
}
}
PostQuitMessage(0);
return 0;
}
}
}
return DefWindowProc (hWnd, iMsg, wParam, lParam) ;
}
MyApp::Paint()
void MyApp::Paint()
{
BeginPaint(m_hWnd,&m_PaintStruct);
if (m_bPaintToBitmap) {
Point2D p;
p.x = BMPXOFFSET;
p.y = BMPYOFFSET;
m_pPath->Offset(p);
m_pPath->DrawTo(m_pBitmapPainter->GetMemDC());
m_pPath->ClrPath();
m_pBitmapPainter->Paint(); //this is where BitBlt() occurs
m_bPaintToBitmap = false;
if(m_pBitmapPainter->IsAdjusted() == false) {
m_pBitmapPainter->SetbAdjusted(true);
}
}
else {
m_pBitmapPainter->Paint(); //this is where BitBlt() occurs
m_pPath->DrawTo(m_hDC);
}
EndPaint(m_hWnd,&m_PaintStruct);
}
Any help would much be appreciated.
A: I think what you're seeing is flicker, not tearing. To minimize flicker, your WM_PAINT should write to the window DC exactly once. Typically, this one operation is a BitBlt:
HDC hdc = BeginPaint(m_hwnd, &m_PaintStruct);
... paint to bitmap ...
BitBlt(hdc, ...); // blt from bitmap to screen
EndPaint(m_hwnd, &m_PaintStruct);
If you paint to the window DC in multiple steps, then you open the window for flicker.
Your description of the problem doesn't match the code. In your description, you say that you're blitting from the compatible DC to the window hDC. But in your code, your BitBlt is followed by a m_pPath->DrawTo(m_hDC). If a refresh occurs during the DrawTo, then the screen will refresh with a partially-drawn view, resulting in flicker.
A: If you are drawing the entire client area, override WM_ERASEBKGND, and simply return TRUE. That will reduce the flicker.
As others have pointed out; use the HDC given by WM_PAINT, as it may contain clipping regions, and other stuff that may optimize the screen update.
EDIT
If you are not drawing the entire client area, you can perform background painting in the areas you know where your WM_PAINT handler won't paint.
A: BeginPaint gives you HDC you are supposed to paint to. You are ignoring it.
A: What OS are you running on ? If its Vista or Windows 7, are you running in some sort of "compatibility mode" disabling desktop compositing ?
Supposedly one of the advantages of the Desktop Window Manager (DWM) introduced with Vista is (source):
In Windows XP, applications update their windows directly when the OS
requests them to. These requests could be executed asynchronously with
respect to the refresh rate of the monitor or to any updates that may
be currently running. The effect of these requests is that the user
sees windows tearing and re-drawing incorrectly or slowly. The DWM
style of window presentation eliminates the tearing artifacts,
providing a high quality desktop experience. The benefit to the end
user is that the system appears to be more responsive and the
experience is cleaner.
ie with the DWM, compositing to the desktop will be synchronized with drawing to avoid ever seeing partially drawn "torn" things.
If that's not it, are you sure you're not confusing "tearing" with background erase flicker or something ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Gallery's onItemSelected is called after orientan change BUT with no reference to position the first element Whenever my activity with a gallery is FIRST created the onItemSelected method is automatically called passing the 0 parameter for position and a reference to the 0th element(textview).
That is fine.
But when I change orientation and the activity is recreated, although the onItemSelected method is called again automatically the parameters are not what I'd expect. The selected position is still passed for the position but null is passed for the view parameter, in other words I can't reference the selected element.
I don't understand this behavior at all. Why is there no reference for the selected view?
(I need to change the text color of selected element based on the Bundle I get in onCreate but I don't have a reference to it.)
A: It's better not to recreate your Activity again, it's really resource-consuming and a waste. Just setting to keep it
These references might help:
http://developer.android.com/reference/android/app/Activity.html#ConfigurationChanges
http://thinkandroid.wordpress.com/2009/12/27/handling-configuration-changes-or-not/
If it's ok, please post your code, I'd like to analyze your case at object referencing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there any effect if I do not restore the application.calculation in vba? I have turned off the
application.calculation = xlcalculationmanual
and after such a lengthy vba code I have done these at the end
application.calculation = xlcalculationautomatic
What I saw is these statement is taking 20 seconds and sometimes hanging up when I restore the xlcalculation
application.calculation = xlcalculationautomatic
I really do not understand why it is taking a lot of time for that statement. To save the time, I just neglected to restore it. Is there any effect if I do not restore it back?
A: The consequence is that no calculations will be done. So if you have a cell with formula =A1+A2 and you change the values of A1 and A2, then the result won't be updated to the actual sum of the current values of A1 and A2 until you force a calculation manually F9 or select automatic calculation again. This can also be done manually in Tools > Options... > Calculation.
A: What I suspect is happening is that it it re-calculating the enture workbook.
Ideally, you should not disable automatic calculations because this is dangerous. (i.e. you may be looking at old cached values instead of recent values)
Instead you should verify that the problem is recalculation (i.e. manually recalculate the sheet and see how long it takes). If that is the problem, you should google way of speeding up calculations (i.e. splitting up your data, using static references, etc...)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: move files with spaces in file name using batch script I have next code and it works perfectly as far as there are no spaces in file names.
FOR /F "usebackq tokens=1" %%n IN (`dir D:\Skripte\radno\temp /b`) DO @FOR /F "usebackq tokens=2,3,4 delims=. " %%d IN (`date /t`) DO @move D:\App\STE\_Isporuka\Doc\%%n \\gds21-bdc01\STE\Arhiva\Novo\Doc\%%f%%e%%d-%%n
I need same functionality for files with spaces in file names.
Thanks,
Tiho
A: You will need to set a blank delimiter to the first for loop and quote the filenames in the second loop:
FOR /F "usebackq tokens=1 delims=" %%n IN (`dir D:\Skripte\radno\temp /b`) DO @FOR /F "usebackq tokens=2,3,4 delims=. " %%d IN (`date /t`) DO @move "D:\App\STE\_Isporuka\Doc\%%n" "\\gds21-bdc01\STE\Arhiva\Novo\Doc\%%f%%e%%d-%%n"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633694",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Best way to cache an XML/JSON response into my application. Full text file? I am currently using XML or JSON webservices in my various applications.
I just would like to know what would be the easiest way to cache theses answers somehere in text files.
I have been thinking about databases, but this seems quite overcomplicated!
So, what I would like to do is
*
*to store these xml/JSON files in phone memory, should I do something like that?
String FILENAME = "MyXmlFile";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
*In the onCreate of my application, I would like to parse this file. As all the tutorials are showing how to parse file from web URL, I never found a way to parse an internal text file. Does someone have an advice on that point?
Thanks.
A: You can apply SharedPreferences, which is also a XML file. Just parse your JSON/XML first, extract all the pair of key/values then write to your pref file. Next time, when loading onCreate(), just re-load the keys/values from pref.
This sample might give you a start:
http://android-er.blogspot.com/2011/01/example-of-using-sharedpreferencesedito.html
A: Another way is to use an awesome http-request library. It allows you to use ETag to check if the response is not modified (HTTP 304 Not Modified). If not modified, use JSON from file cache, else make a request to get the new resource.
File latest = new File("/data/cache.json");
HttpRequest request = HttpRequest.get("http://google.com");
//Copy response to file
request.body(latest);
//Store eTag of response
String eTag = request.eTag();
//Later on check if changes exist
boolean unchanged = HttpRequest.get("http://google.com")
.ifNoneMatch(eTag)
.notModified();
A: It will be the opposite of your write XML/JSON.
Use openFileInput to get the FileInputStream. Read the stream to a string and then parse it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Listview select "active" item
Possible Duplicate:
Select ListBoxItem if TextBox in ItemTemplate gets focus
I have a ListView bound to an ObservableCollection (Listview.ItemsSource). The listview presents several textboxes that are bound to properties of the objects in the observable collection.
I would like to have the following functionality: when a user focusses a textbox the corresponding item in the listview should get selected.
I have tried things with ContainerFromElement, ContainerFromItem, etc. but can't get this "simple" functionality to work.
Any ideas...
A: The trick here is to use the IsKeyboardFocusWithin property on the ItemContainerStyle:
<ListView ItemsSource="{Binding}">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Style.Triggers>
<Trigger Property="IsKeyboardFocusWithin" Value="True">
<Setter Property="IsSelected" Value="True" />
</Trigger>
</Style.Triggers>
</Style>
</ListView.ItemContainerStyle>
<ListView.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=YourPropertyValue}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
In this example we are simply stating that IsSelected should be set to true whenever a control within that item contains the keyboard focus.
Note: this does not work in the opposite direction; selecting a particular item in the list will not automatically give focus to the contained TextBox
Edit in response to comments
As Joep pointed out, this will mean that losing keyboard focus (which will happen when a control besides the TextBox gains focus) will cause the IsSelected property to be reset to false. You can work around this by replacing the Style setter with an trigger enter action, which prevents the change from being undone when the trigger is no longer valid.
For this to work in the same way as the previous example you will need to explicitly set the SelectionMode for the ListView to Single; otherwise, multiple items can become selected at once.
<ListView ItemsSource="{Binding}" SelectionMode="Single">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Style.Triggers>
<Trigger Property="IsKeyboardFocusWithin" Value="True">
<Trigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames
Storyboard.TargetProperty="IsSelected">
<DiscreteBooleanKeyFrame KeyTime="0:0:0"
Value="True" />
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</Trigger.EnterActions>
</Trigger>
</Style.Triggers>
</Style>
</ListView.ItemContainerStyle>
<!-- ... -->
</ListView>
A: The MVVM way would add extra properties to the ViewModel representing the properties that are focussed.
E.g., if the ViewModel has a property Name add a property IsNameFocussed, if it has a property Address, add a property IsAddressFocussed.
Then bind the appropriate control in the DataTemplate to the Is...Focussed property to highlight it.
All that is left is setting the Is...Focussed property in the GotFocus and LostFocus events of the textboxes. (I'd rather bind to a Focussed Property but it's not there...)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633705",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Data exchange between a service and an activity I have to publish the progress from a background service on the UI continuously on a progress bar. Any ideas on how to go about it. Intents won't work I guess coz they can only send the data once the activity is started. Ant other suggestions?
Update : The progress on the UI happens on a progress Bar
A: Extend Application, which is created once for entire application.
When Activity starts, store its reference to a field in your Application object. (Note that you can access Application using Activity.getApplication). Set this field to Activity reference or null in onPause/onResume calls.
Then in Service, you have also access to your Application by Service.getApplication. So look if your Activity reference is non-null, meaning that your Activity is shown to user, and update UI as needed in such case, by calling methods on your Activity.
A: Thanks for the help mice, but since I needed to update progress bars on different activities in my app depending on which one was visible, I found it easier to implement through Broadcast Intents and Recievers and Intent Filters. All I had to do was to Broadcast the progress in my service wrapped up in a bundle via a broadcast Intent (with a custom Intent Filter applied) and register (in onResume()) an inner subclass of BroadcastReciever in the activities which needed the progress (having the same intent filter). One can also unregister these recievers in the onPause() method of the activity to save memory headspace.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Optimizing Windows WF 3.5 Instance Creation for 200 request I currently have a process that creates a windows wf 3.5 instance for each account that a customer have.
foreach (Account acct in Customer.Accounts)
{
Dictionary<string, object> param = new Dictionary<string, object>();
param.Add("account", acct);
//create the workflow instance
WorkflowInstance instance = workflowRuntime.CreateWorkflow(typeof(AcctWorkflow), param);
//start and run the workflow
instance.Start();
scheduler.RunWorkflow(instance.InstanceId);
}
currently the creation of each request is about 500ms, but given 200 accounts, the total time > 1 min.
this is created real time as the user clicks on a create request button.
Please advise if there is any thing else i can do to make it faster.
A: I'm not sure what can be done for WF3.5 to speed things up. The WF3.5 run-time engine has many inherent "lack of optimization" problems that just can't be fixed or worked around (especially the way looping constructs, such as the While activity, are implemented).
If it is feasible for your project you should really consider re-writing it into WF4. The run-time engine for WF4 is a complete rewrite with a strong consideration for large+fast workflows. See http://msdn.microsoft.com/en-us/library/gg281645.aspx for a speed comparison of the WF3.5 vs WF4 run-time engines.
Even if it is not possible to rewrite your workflow into WF4, you should update to run the 3.5 workflow using the 4 engine (via the WF4 Interop activity). This could still potentially double your speed over using the WF3.5 engine. See the bottom of the page of the link above for the comparison using the Interop activity.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Row in table is getting locked after modifying a certain cell in it in oracle I have the following code in an oracle procedure, which returns a cursor (r_cursor) as an OUT parameter
SELECT userid
INTO v_userid
FROM users u
WHERE lower(u.email) = lower(p_email)
AND lower(u.token) = lower(p_IV);
UPDATE users u
SET u.token = NULL,
u.lastlogin = sysdate()
WHERE u.userid = v_userid;
OPEN r_cursor FOR
SELECT u.firstname,
u.lastname
FROM users u
WHERE u.userid = v_userid;
When calling the procedure from oracle everything works completely fine.
But when calling the procedure from a .Net application, the error ORA-24338: statement handle not executed is raised.
After a lot of testing, I find out that if I remove one of the lines lower(u.token) = lower(p_IV) from the SELECT statement or u.token = NULL, from the UPDATE statement, the cursor is returned to the .Net application without any error.
A: The ORA-24338 is usually raised when you try to fetch a cursor that has not been opened yet.
This could be raised for example if your procedure raised an exception before the OPEN statement. Afterwards when you try to fetch from the cursor oracle would raise the ORA-24338 since the cursor has never been opened.
Do you have an EXCEPTION block (with a WHEN OTHERS for example) in your PL/SQL, or do you catch SQL exception in .net?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to find out the exact operation that is posted to Dispatcher Is there a way where we can find out which UI element has posted an operation to the Dispatcher queue which eventually throws the event ,System.Windows.Threading.Dispatcher.CurrentDispatcher.Hooks.OperationPosted
Update : A private property DispatcherOperation.Name is showing what I need in the VS mouse-over in debugging mode. I just need to print this name to a logger for other debugging purposes. Is it possible to extract the Name dynamically.
A: Yes it is possible, while i give you a way to do it, i must warn you though, using reflection to get private or protected fields/properties/methods is never a good idea because first they are usually private for a reason and second of all if the signature or interface changes you code might break. But because you said it is just for debugging, this might be a valuable solution.
You can always use Reflection for these kind of things. First you need the Type and Instance of the object you want to read its private properties. Unfortunately i don't know if the Name you are looking for is a field or a property, but the overall procedure is similar. First get the property with GetProperty and then call GetValue on the returned PropertyInfo object. You might want to cache the PropertyInfo object to gain some speed while debug. You also need to use the correct BindingFlags again i don't know exactly how the field/property is described so i can't give you the exact code, but from here it should be easy to figure out.
Hope that helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What does 'unspecified error' mean in IE? I'm getting unspecified error when reading document.namespaces in IE8.
I can't seem to reproduce the problem in a standalone page, my snippet is:
function addNamespace(key, value) {
try {
$("html").attr(key, value);
if (document.namespaces && // This throws the error
!document.namespaces[key]) {
document.namespaces.add(key, value);
}
} catch (e) {
alert("Error: " + e);
}
};
Never mind right now why I'm trying to add a namespace at runtime (it has to do with Facebook Like not working properly... see this comment - Facebook like button showing in Firefox but not showing in IE).
My question is simple - on what conditions does unspecified error occur?
A: Unspecified errors seem to occur when something (usually a value) isn't set or initialized correctly that the browser is attempting to use. I've seen a lot of unspecified errors from Ajax code attempting to access something (usually from the DOM) before the page has finished loading (even if the page appears to have already loaded)...
Some Googling on this error shows some people saying this is a browser issue, but through my own experience I strongly suspect it has to do with some asynchronous code not running in the order in which you think it is running.
A: In my opinion, this error in IE is very similar to this common one in chrome
Uncaught SyntaxError: Unexpected token <
For those ones who encounter this while using polyfills for IE.
Check your order of importing different libraries, make sure the dependency relationship is correct, also if you use requireJS, this error may be caused the error from the config file as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633722",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Calling a Ruby method via a button Quick question, what's the best way to call a ruby method via a button? At the moment, the button will only call a JS function but I need it carry out a Ruby method.
Basically, the button has to compare an Excel spreadsheet with my database and display the difference in a table on another page. How can I create that page without generating a new model? Sorry for the stupid question, but I've only been sticking to the conventions, hence I am unsure as to how I should create a new page.
Thanks in advance for any help
A: Take a look at the button_to method.
<%= button_to "Compare Excel", :action => "compareExcel" %>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to test if onpropertychange is supported or not? I'd like to know if an input element has changed, I learned that I can listen to onpropertychange in IE and oninput in other browsers.
Here is my code:
var _addChangedProperty = function(input){
input.changed = false;
var oninput = function(){
this.changed = !!this.value;
if(this.changed){
this.style.color = "black";
}
};
input.onpropertychange = input.oninput = oninput;
};
Now I'd like to change input.onpropertychange = input.oninput = oninput; to addEventListerner and attachEvent, I need to check if onpropertychange event is supported, how could I do this (without browser detect)?
A: You can check using the in operator:
"onpropertychange" in input
This kind of feature test doesn't work in older versions of Firefox, which report false event for event handler properties corresponding to events that do exist, but that isn't a problem here because Firefox doesn't currently support the propertychange event and is unlikely to in the future.
Here's some background: http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
One other point: you need separate functions to handle the propertychange and input events, because in the propertychange handler you need to check whether it is the value property that has changed. Otherwise, you'll end up handling changes to any property of the input.
input.onpropertychange = function(evt) {
evt = evt || window.event;
if (evt.propertyName == "value") {
// Do stuff here
}
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Uninstalling msi installation with patches I have a product installation that has been patched with one small update patch which is uninstallable. Is there any difference if I first uninstall the patch and then product installation or if I select the uninstall of the product while the patch is still installed? Product and patch installations are created using WiX tools.
A: The final result of both ways to uninstall is the same - the product is uninstalled. However, you might potentially face with other problems in the first case, when you first uninstall a patch, then the product.
I would recommend you to get acquainted with this article to understand how it all works. The end of the page mentions uninstallable patches. Afterwards, be sure to check other Heath's blog posts about patching, like:
*
*Source Resolution during Patch Uninstall
*How to Safely Delete Orphaned Patches
*Uninstallable Patches that are not Uninstallable
Finally, you might want to browse other "installation" posts on that blog - it contains lots of useful info.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633726",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do you trigger autocomplete "select" event manually in jQueryUI? I'm using jQueryUI autocomplete, and I have a function mapped to the select event, e.g.:
$("#someId").autocomplete({
source: someData,
select: function (event, ui) { ... },
focus: function (event, ui) { ... }
});
I have a special case: The user has focused on an item in the autocomplete drop-down (but not selected it) and I need to trigger the select event manually from a different function. Is this possible? If so, how?
A: You can do it the way the jQuery team does it in their unit tests - see this answer
A: Simply call following function
setAutocomplete("#txt_User_Name","rohit");
function setAutocomplete(autocompleteId,valuetoset)
{
$(autocompleteId).val(valuetoset);
$(autocompleteId).autocomplete("search", valuetoset);
var list = $(autocompleteId).autocomplete("widget");
$(list[0].children[0]).click();
}
A: Here's what worked for me:
$(this).data('ui-autocomplete')._trigger('select', 'autocompleteselect', {item:{value:$(this).val()}});
A: 1 line solution
$('.ui-menu-item .ui-corner-all:contains(\"123")').autocomplete({autoFocus:true}).mouseenter().click()
A: $('#someId').data('uiAutocomplete')._trigger('select');
A: If we want to trigger search of something particularly:
$('#search-term').autocomplete('search', 'searching term');
or just
$('#search-term').autocomplete('search');
$('#search-term').autocomplete({
...
minLength: 0, // with this setting
...
});
A: You could do:
$("#someId").trigger("autocompleteselect");
A: From outside:
$($('#someId').data('autocomplete').menu.active).find('a').trigger('click');
An example how to setup select triggering at pressing of horizontal arrows keys from inside of "open" autocomplete event:
$('#someId').autocomplete({
open: function(event, ui) {
$(this).keydown(function(e){
/* horizontal keys */
if (e.keyCode == 37 || e.keyCode == 39) {
$($(this).data('autocomplete').menu.active).find('a').trigger('click');
}
});
}
});
Unfortunately that nice way how to solve this marked as "success" did not work at my app in chromium 140.0.835.200
A: You don't have to go through a bunch of rigmarole to call select. This is how I call select from my own extended version of autocomplete.
$(this).data('ui-autocomplete').options.select(event, ui);
where I use this
/**
* The jQuery UI plugin autocomplete
*/
$.widget( "ui.autocomplete", $.ui.autocomplete, {
options: {
close: function( event, ui ) {
if (typeof event.currentTarget == 'undefined') {
$(this).val("");
$(this).data('ui-autocomplete').options.select(event, ui);
}
}
}
});
A: I found very simple way to make it work.
Answers above did not work for me.
My input definition:
<div class="search_box">
<input type="text" class="inp disabled" id="search-user-id" placeholder="Search by user name or email" />
</div>
The autocomplete definition:
$('#search-user-id').autocomplete({
minChars: 3,
paramName: 'searchTerm',
deferRequestBy: 200, // This is to avoid js error on fast typing
serviceUrl: '${pageContext.request.contextPath}/settings/reset/psw/query',
type: 'POST',
onSelect : function(suggestion) {
showUserData(suggestion.dto);
},
onSearchError: function (query, jqXHR, textStatus, errorThrown) {
$('.cev-error-fields.reset-password').find('.error_msg').text(errorThrown).show().fadeOut(7000);
}
});
Trigger it:
I am triggering from an ajax defined in other page,
I do not put the ajax here for simplicity.
Inside the ajax response I just trigger it this way:
$('#search-user-id').val(username);
$('#search-user-id').focus();
It worked.
A: I stumbled upon this thread as I was seeking a way to prefill a bunch of jquery ui autocomplete fields in a form where users can modify an already submitted one.
First, I have to load the form, with some inputs using autocomplete.
Problem 1 : I created a php function able to call a premade autocomplete input, specifying some things like the input class, id, name... and value(s). I can also pass the name of a JS custom function to trigger (with the selected item's ID as a parameter), depending on the form and type of data... So I can't just "print" the prefilled input when loading the form because the custom function (and other actions specified in the built-in select: function( event, ui ) { ... } won't fire.
I really need to mimic a search-->click action.
Problem 2 : the source comes from an ajax call performing a search from the string entered in the input. It then shows strings as items... but I want the real input to be the IDs of those sources. To do so, the select: event creates a hidden input with the ID of the clicked item, checks if it was already selected (I can select multiple elements from one autocomplete input..), etc. It has to be triggered.
I really need to mimic a search-->click action.
Problem 3 : Since the source comes from an ajax call, I would have to make all these calls to prefill the form, which is a very bad way of populating a form (for various reasons).
I can't really mimic the search-->click action.
Solution
I simply created a second (hidden) autocomplete input for each "real ones", for which the initialisation $(id).autocomplete(...) performs the same actions (upon select), but is populated with static source i drew directly from the DB with the already saved input. Then, I simply mimic the search-->click in this dummy input, which draws the good inputs with the IDs I want to save...
foreach (values to prefill..) {
$("#'.$mot_cle.'_input_autocomplete_prefill").val("'.$valeur_finale_unique['value'].'");
$("#'.$mot_cle.'_input_autocomplete_prefill").autocomplete("search", "'.$valeur_finale_unique['value'].'");
var list = $("#'.$mot_cle.'_input_autocomplete_prefill").autocomplete("widget");
$(list[0].children[0]).click();
}
It's quite complicated. But in the end, everytime I want to show an autocomplete input in my pages, I only have to call the php function which wraps it up ;)
And it's lightning fast, and don't mess with the input IDs\Names for the entire forms managing...
There is a lot going on backend, but in the end, it looks like this, when I enter this :
<div class="marge">
<span class="texte_gras">Demandeur(s)</span><br>
'.formulaire_autocomplete("demandeurs","pdrh_formulaire_ajouter_cible_valeurs","1","usager",$valeur_demandeur,"").'
</div>
PHP function formulaire_autocomplete($keyword(used for input name),$class(used for jquery serialize when submitting form),$multi(possibility to input more than one choice),$type(which DB table to search: users, courses, etc..),$value(IDs to prefill in the form for this input, if it is an already submitted form), $function(if I want to trigger a custom JS function when select:))
I get this :
<div class="marge">
<span class="texte_gras">Demandeur(s)</span><br>
<input style="width: 90%;" class="pdrh_formulaire_ajouter_cible_valeurs ui-autocomplete-input" type="text" name="demandeurs[]" id="demandeurs_input_autocomplete" value="" autocomplete="off"> <input style="width: 90%; display: none;" class="pdrh_formulaire_ajouter_cible_valeurs ui-autocomplete-input" type="text" name="demandeurs_prefill[]" id="demandeurs_input_autocomplete_prefill" value="" autocomplete="off"> <div id="demandeurs_boite_autocomplete_selection" style="width: 100%;"><div style="width: 100%;" id="demandeurs_auto_ID_25434"><div class="petite_marge"><input style="width: 80%;" class="pdrh_formulaire_ajouter_cible_valeurs" type="hidden" name="demandeurs_auto_ID[]" id="demandeurs_input_autocomplete_auto_id_25434" value="25434"><span class="petit_texte texte_gras">STEPHANIE (41263)</span><div class="bouton_transparent" onclick="effacer_div('demandeurs_auto_ID_25434')"><div class="petite_marge"><img src="./images/vide.png" style="width: 1em;"><img src="./images/effacer.png" style="width: 1em;"></div></div></div></div><div style="width: 100%;" id="demandeurs_auto_ID_18760"><div class="petite_marge"><input style="width: 80%;" class="pdrh_formulaire_ajouter_cible_valeurs" type="hidden" name="demandeurs_auto_ID[]" id="demandeurs_input_autocomplete_auto_id_18760" value="18760"><span class="petit_texte texte_gras">MARIE (23673)</span><div class="bouton_transparent" onclick="effacer_div('demandeurs_auto_ID_18760')"><div class="petite_marge"><img src="./images/vide.png" style="width: 1em;"><img src="./images/effacer.png" style="width: 1em;"></div></div></div></div></div><script>
$("#demandeurs_input_autocomplete").autocomplete({
source: function (request, response) {
requete_ajax = $.ajax({
type: "POST",
url: 'fonctions.php',
data: 'recherche_autocomplete=usager&chaine='+request.term,
dataType: 'json',
success: function(data) {
ajax_en_cours = 0; console.log("Ajax terminé");
// var resultat = JSON.parse(data.choix);
var tableau_resultat = Object.values(data.choix);
response(tableau_resultat);
console.log(tableau_resultat);
},
error: function(e) {
ajax_en_cours = 0; console.log("Ajax terminé");
console.log('Erreur | demandeurs recherche autocomplete');
}
});
},
minLength: 3,
select: function( event, ui ) {
$("#demandeurs_input_autocomplete_auto_id").val(ui.item.ID);
var contenu_selection = $("#demandeurs_boite_autocomplete_selection").html();
$("#demandeurs_boite_autocomplete_selection").html(contenu_selection+"<div style=\"width: 100%;\" id=\"demandeurs_auto_ID_"+ui.item.ID+"\"><div class=\"petite_marge\"><input style=\"width: 80%;\" class=\"pdrh_formulaire_ajouter_cible_valeurs\" type=\"hidden\" name=\"demandeurs_auto_ID[]\" id=\"demandeurs_input_autocomplete_auto_id_"+ui.item.ID+"\" value=\""+ui.item.ID+"\"><span class=\"petit_texte texte_gras\">"+ui.item.value+"</span><div class=\"bouton_transparent\" onclick=\"effacer_div('demandeurs_auto_ID_"+ui.item.ID+"')\"><div class=\"petite_marge\"><img src=\"./images/vide.png\" style=\"width: 1em;\"><img src=\"./images/effacer.png\" style=\"width: 1em;\"></div></div></div></div>");
$("#demandeurs_input_autocomplete").val(" ");
}
});
var valeurs_prefill = [{value: "STEPHANIE (41263)", ID: "25434"},{value: "MARIE (23673)", ID: "18760"}];
$("#demandeurs_input_autocomplete_prefill").autocomplete({
source: valeurs_prefill,
minLength: 3,
select: function( event, ui ) {
$("#demandeurs_input_autocomplete_auto_id").val(ui.item.ID);
var contenu_selection = $("#demandeurs_boite_autocomplete_selection").html();
$("#demandeurs_boite_autocomplete_selection").html(contenu_selection+"<div style=\"width: 100%;\" id=\"demandeurs_auto_ID_"+ui.item.ID+"\"><div class=\"petite_marge\"><input style=\"width: 80%;\" class=\"pdrh_formulaire_ajouter_cible_valeurs\" type=\"hidden\" name=\"demandeurs_auto_ID[]\" id=\"demandeurs_input_autocomplete_auto_id_"+ui.item.ID+"\" value=\""+ui.item.ID+"\"><span class=\"petit_texte texte_gras\">"+ui.item.value+"</span><div class=\"bouton_transparent\" onclick=\"effacer_div('demandeurs_auto_ID_"+ui.item.ID+"')\"><div class=\"petite_marge\"><img src=\"./images/vide.png\" style=\"width: 1em;\"><img src=\"./images/effacer.png\" style=\"width: 1em;\"></div></div></div></div>");
$("#demandeurs_input_autocomplete").val(" ");
}
});
$("#demandeurs_input_autocomplete_prefill").val("STEPHANIE (41263)");
$("#demandeurs_input_autocomplete_prefill").autocomplete("search", "STEPHANIE (41263)");
var list = $("#demandeurs_input_autocomplete_prefill").autocomplete("widget");
$(list[0].children[0]).click();
$("#demandeurs_input_autocomplete_prefill").val("MARIE (23673)");
$("#demandeurs_input_autocomplete_prefill").autocomplete("search", "MARIE (23673)");
var list = $("#demandeurs_input_autocomplete_prefill").autocomplete("widget");
$(list[0].children[0]).click();
</script>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633727",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "34"
} |
Q: Is there any real application being self modifying code? There are few examples on the web demonstrating how to write a self-modifying code. But they're just examples. I would like to know if there is any real application being self modifying code. Thanks!
A: The first thing that comes to mind are viruses, trojaners and the likes.
Self-modifying code makes it harder for anti-virus applications to identify your application as malicious.
Another area were self-modifying code is used is genetic programming
There's also a Wikipedia article covering your question.
A: Am I allowed to reference other architectures? Because, when you're working with weaker systems, like embedded applications, SMC is often used, since there is only a limited amount of RAM available for the programs to run in.
Also, wikipedia has quite a nice list.
A: 'Self modifying code' may also refer to bytecode modifications in Java. This is used by many frameworks like Guice, JPA, EJB- and Webcontainers and almost all AOP (Aspect Oriented Programming) frameworks.
Basically they modify the bytecode before it is loaded and executed by the JVM. All those frameworks try to add behaviour to the class without the need to code cross-cutting concerns by hand. Transaction control, dependency injection, scope or context injection are the usual suspects.
A: I know a program that contains a self modifying code (works as a protection scheme), it's role is to decrypt itself if the right password was entered and the decrypted code plays a big role into saving the opened file to disk, this program is called 'WinHEX'.. you can find the SMC code right above the call to virtual protect, and if the right password is entered, the program calls the write process memory api to decrypt the section, and to eventually save the file to disk.
A: The Dynamic Language Runtime (DLR) uses self-modifying code to optimize for the common types of a given call site.
Let's say you're writing a dynamically typed language on top of .NET, and you have source code in your language as follows:
x + y
Now, in a statically typed language, the types of x and y can be determined at compile time -- say x and y are ints, then x + y will use the IL "add" instruction.
But in a dynamically typed language, this resolution could be different every time. Next time, x and y could be strings, in which case the value resolution for this call site would use String.Concat. But resolving which IL to use is liable to be very costly. In fact, if in the first hit of the call site x and y are a pair of ints, it's highly likely that successive hits on this call site will also be with a pair of ints.
So the DLR iterates as follows: The compiled code of the callsite looks like this:
return site.Update(site, x, y);
The first time a given set of types is passed in -- say, a pair of ints, the Update method turns to the language implementation to resolve which method/instruction should be used with a pair of ints and a +. Those rules are then recompiled into the callsite; the resulting compiled code looks something like this:
if (x is int x1 && y is int y1) { return x1 + y1; }
return site.Update(site, x, y);
Successive calls with pairs of ints leave the compiled code unchanged.
If a new type pair is encountered, the code self-rewrites into something like this:
if (x is int x1 && y is int y1) { return x1 + y1; }
if (x is string x2 && y is string y2) { return String.Concat(x2, y2); }
return site.Update(site, x, y);
For more information on how this works, see Jim Hugunin's talk at PDC 2008 on dynamic languages and the DLR design documentation at the DLR project.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633728",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Programatically delete [permenantly] a TFS work item Whilst I'm aware that there is a command line tool to permenantly delete a TFS work item. (e.g. How to delete Work Item from Team Foundation Server)
Has anyone been able to achieve the same action programatically using the TFS 2010 API DLLs?
A: Shai Raiten has blogged about this here, where he makes use of DestroyWorkItems(ids).
It is advisable that you proceed with extra caution in your implementation, since this can severely mess your installation. One could argue that constructing such a tool deviates from best practices.
A: You can also use PowerShell to bulk delete work items:
Copy and paste below script in a PowerShell file (with .ps1
extension), update the variable values mentioned in the list #4 below
and run the command from a machine where witadmin tool is installed
(Generally available after visual studio installation). Open
PowerShell command window and execute the script.
Note: Account running below script should have team foundation administrator or collection administrator access.
########TFS Work Items Bulk Destroy Automation Script##########
#Notes:
#1) This script requires to setup file/folder path, validate the file/folders path before running the script
#2) start the powershell window as Administrator and run the script
#3) This script requires share and admin access on the destination server, make sure your account or the account under which script is
# executing is member of admin group on the destination server
#4) Update following:
# 4.1: $CollectionURL
# 4.2: $WitAdmin tool location
# For VS 2015, Default location is C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE
# For VS 2013, Default location is C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE
# 4.3: $WI_List
# 4.4: $logfile
####################
$CollectionURL = "http://tfs:8080/tfs/CollectionName"
$WitAdminLocation = "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE"
$WI_List = Get-Content "C:\WI_List.txt"
$logfile="C:\log.txt"
$ExecutionStartTime = Get-Date
$WICount = 0
"## Starting WI Destroy @ $ExecutionStartTime ##"| Out-File $logfile -Append
"Collection URL: $CollectionURL" | Out-File $logfile -Append
foreach ($WIID in $WI_List)
{
CD $WitAdminLocation
.\witadmin destroywi /collection:$CollectionURL /id:$WIID /noprompt
"WI ID: $WIID Destroyed" | Out-File $logfile -Append
$WICount = $WICount + 1
Write-Host "$WICount Work Items Deleted"
}
$ExecutionEndTime = Get-Date
"## WI Destroy Command Completed @ $ExecutionEndTime ##"| Out-File $logfile -Append
$TotalExecutionTime = $ExecutionEndTime - $ExecutionStartTime
"Total Work Items Deleted: $WICount" | Out-File $logfile -Append
" Total Execution Time: $TotalExecutionTime" | Out-File $logfile -Append
##End of script##
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Post wall - Cancel and Share button frames I have integrated Facebook successfully. But the problem is when I am trying to post data into my wall content is exceeding iPhone screen size. Some data is behind SHARE and CANCEL buttons. How to change frames according to the my content size?
A: You can't do anything about it. Because that view is just a web page loaded dynamically into a UIWebView.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to store a translation in a different table using Doctrine 2 + Gedmo Translatable Using the instructions on https://github.com/l3pp4rd/DoctrineExtensions/blob/master/doc/translatable.md#advanced-examples a table can be split in order to store the translations in another table.
The resulting table structure is:
(example A)
Article ArticleTranslation
+--------------+ +----------------------+
| id | | id |
+--------------+ +----------------------+
| title | | locale |
+--------------+ +----------------------+
| content | | objectclass |
+--------------+ +----------------------+
| online | | foreign_key |
+--------------+ +----------------------+
| field |
+----------------------+
In my view there are two problems using this standard approach:
1. the translated entity is stored into multiple records (one per field) in the translation table
2. The original record should be in the translated table as well.
Is it possible with Doctrine+ Gedmo Translatable to store the translations like this:
(example B)
Article ArticleTranslation
+--------------+ +----------------------+
| id | | id |
+--------------+ +----------------------+
| online | | foreign_key |
+--------------+ +----------------------+
| locale |
+----------------------+
| title |
+----------------------+
| content |
+----------------------+
So untranslated fields should be in the Article table, translated fields in the ArticleTranslation table with one record per translated article.
How can this be achieved?
A: using current architecture it stores a record per field in translation table. In general it was done this way in order to avoid synchronization issues if you add or remove translatable fields from your entities.
Implementation of your method would result in having additional schema migration command specifically for extension or having some magic mapping in background. To avoid confusion the only thing which is scheduled for update is original record translation storage as default locale fallback, without having record in translation table.
I understand that in advanced cases this bahavior is not what you would have done, but it is a behavior for most users which want it configurable as simple as possible.
And regarding collection translations you can use query hint This behavior will never cover 99% of use cases like SF2 does in order to maintain simplicity
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Format of the following response? I'm using Bing's auto suggest feature to auto suggest me terms given a query. You can find the tool here: http://api.bing.com/osjson.aspx?query=pe as you can see it's returning a strange format that isn't quite JSON. Is this a specific standard different to JSON? I've attempted parsing it as JSON using...
InputStream i = new URL(url).openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(i, Charset.forName("UTF-8")));
JSONObject json = new JSONObject(readAll(reader));
but I get the error A JSONObject text must begin with '{' found:" at 2 [character 3 line 1]
readAll =
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
A: Your example is valid JSON:
["pe",["people","people search","petsmart","petco","petfinder","pep boys","people finder","people of walmart"]]
It is not object, it is array, which contains string at the first position and another array at the second. So try parse as JSONArray, not as JSONObject.
A: A JSON Object starts with a { and ends with a }, which a JSONObject class was designed to parse.
A JSON Array starts with a [ and ends with a ], which a JSONArray class was designed to parse.
I hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633736",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to get image path from server drive How to get imgepath from server drive. I have all imges in C drive Chekout folder which included my projct. I want to display that image in my asp.net application. I did server path C:\Chekout but it is searchin in users local system not in server. Please Help me..
Thanks.
A: You would need to do something like this:
YourPath = HttpContext.Current.Server.MapPath(VirtualPathUtility.ToAbsolute(YourFileName))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Hibernate custom HQL for this mapping I have following tables
------------
BAR
------------
ID
number
------------
ZOO
------------
ID
------------
FOO
------------
ID
------------
MAPPER
------------
ID
FOO
BAR
ZOO
Now I want to fetch all ZOO for particular FOO So I will do
select ZOO from MAPPER where zoo = someZoo
but now I want these ZOO sorted based on vote number so SQL would be
SELECT FOOBAR.ZOO
FROM mapper AS mapper,
BAR AS bar
WHERE mapper.FOO=SOME_VALUE AND mapper.BAR=bar.id order by bar.number desc
But now I want to do it in DB independent way in Hibernate How would I go ?
I have entities mapped setup I am using Spring Hibernate Template Support
public class Foo{
Long id;
}
public class Zoo{
Long id;
}
public class Bar{
Long id;
Long num;
}
public class Mapper{
Long id;
Long foo;
Long bar;
Long zoo;
}
A: Class Mapper should be:
public class Mapper {
Long id;
Foo foo;
Bar bar;
Zoo zoo;
}
Now, you can write the following HSQL query:
select mapper.zoo from Mapper mapper where mapper.foo=:foo order by mapper.bar.num desc
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Removing Duplicates From ListView android I am posting my code, I am unable to remove the duplicate values from the listview?
Can someone please help me? Thanks in advance!
I am pasting my code here and I have used BaseAdapter.
@Override
public void onCompleted(final List<Recommendable> result) {
android.util.Log.w("suggestionview>>>>>", "suggestion"+ result.size());
((Activity) mContext).runOnUiThread(new Runnable() {
public void run() {
Iterator<Recommendable> itr = result.iterator();
while (itr.hasNext()) {
Recommendable element = itr.next();
suggestions.add(element);
android.util.Log.w("suggestionview", "Adding elements::>"+suggestions.add(element));
}
suggestionListView.setAdapter(new Suggestiondapter(mContext));
android.util.Log.w("suggestionview","suggestion adapter Values::>"+suggestionListView);
}
});
And the second of the code
public class Suggestiondapter extends BaseAdapter {
// private LayoutInflater mInflater = null;
private Context mContext;
public Suggestiondapter(Context mContext) {
this.mContext=mContext;
android.util.Log.w("Suggestion Adapter","vlues are comming.....");
}
@Override
public int getCount() {
android.util.Log.w("suugestion adapter","suggstion size::>"+suggestions.size());
return suggestions.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Recommendable recommendable = suggestions.get(position);
if(convertView==null){
android.util.Log.w("convertView", "adaptervalues........::>"+ recommendable.Program);
android.util.Log.w("series conveter", "program series values::>"+recommendable.Series);
convertView = new HeaderView(mContext, recommendable.Program,recommendable.Series, SuggestionView.class);
}else{
Toast.makeText(mContext, "HelloView", Toast.LENGTH_SHORT);
}
return convertView;
}
};
A: You could use that code:
private static HashSet<String> hs = new HashSet<String>();
private static ArrayList<String> list= new ArrayList<String>();
for(int i=0; i<list.size(); i++){
hs.add(list.get(i));
}
list.clear();
list.addAll(hs);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: JSF 2 RI (Mojarra) and Tomahawk compatibility I need to use fileUpload from Tomahawk because not provided by Jsf.
I want to know if Tomahawk is 100% compatible with Mojarra
I dont' find this information on the web.
My version of Mojarra (2.1.2) and tomahawk (1.1.11)
Thanks,
Yoel
A: There are three builds of Tomahawk 1.1.11: One for JSF 1.1, 1.2 and 2.0. As long as you use the 2.0 build of 1.1.11 you should be able to use it on Mojarra 2.1.x. The Tomahawk site clearly states all of this.
Edit:
As requested:
*
*http://myfaces.apache.org/tomahawk-project/tomahawk/index.html
*http://myfaces.apache.org/tomahawk-project/tomahawk12/index.html
*http://myfaces.apache.org/tomahawk-project/tomahawk20/index.html
And then look at the download page, noting the different variants of Tomahawk 1.1.11 available for download: http://myfaces.apache.org/tomahawk/download.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Viewing source code from a third-party jar in Eclipse I am working on a Java project in Eclipse. In this I am using a third party JAR which I have put in on the classpath. Now I want to understand the code in the JAR file and want to see the actual code and navigate through the third party code just like my own code.
My question is this: Instead of me manually decompiling all of the class files in the JAR and putting them in the appropriate folder as per package declaration, is there some way in which Eclipse will decompile them for me, and put them in the appropriate folder? What should be the approach taken in such a scenario?
A: The decompiler I use is JAD. It has an eclipse plugin, Jadclipse.
You can download JAD from http://www.varaneckas.com/jad
You can get Jadclipse from http://sourceforge.net/projects/jadclipse/. Click on the download jar and then simply copy the jar into your Eclipse/plugins directory, and restart Eclipse. Set up the path to JAD from Preferences->Java->JADClipse. Then trying to view a class should give the decompiled code.
A: I have been using Java Decompiler for some time and have found it very useful, i don't know about eclipse but it seems to have a eclipse plugin: JD-Eclipse
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Get Product with the filter using OR operator In Magento,
I want to get the product with name attribute is Product 1 *OR* Product 2
$product = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('name','Product 1')
->setPageSize(1)
->load()
->getFirstItem();
//OR
if( !$product->getId() )
{
$product = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('name','Product 2')
->setPageSize(1)
->load()
->getFirstItem();
}
How can I just using one statement to do?
A: refer to this article http://www.magentocommerce.com/knowledge-base/entry/magento-for-dev-part-8-varien-data-collections in magento knowledgeBase
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I switch from one UITabbarview controller to another UITabbarViewController in iPhone? I have an UITabbarViewController with 3 tabbar items with a navigationbar. When I will press my first item of tabbar item there will be a button at the view.
Now my question is when I will press the button, then it will go to the another tabbarview controller which have also 3 tabbar items. How can I do that?
UITabbarViewController[with navigation bar]--->tabaritem [1] + tabaritem [2] + tabaritem [3]
tabaritem [1] viewcontroller is taking a button when I will press button the another UITabbarcontroller will be shown at the screen.
UITabbarcontroller[2] [with navigation bar]--->tabaritem [1] + tabaritem [2] + tabaritem [3]
I am new to iPhone application development.
One more thing is that I can't use table view for two tabbarcontroller because my first tabbar item of first tabbar is taking a login page so when user will able to log in then he will see second tabbarviewcontroller.
A: The only way to do this, according to apples viewpoints, is to show one of the tab bars in a modal.
It seems like you're using the first Tabbarcontroller as a Login controller. In that case, you would have this as a Modalview over you're other (normal) Viewcontroller. On Application Start, you load the main tab controller.
You then check if the user is logged in and show the Model Logging Controller (which is a Tabbar controller again) if he isn't.
Once the user has successfully logged in, you just dismiss the Modal, and voila, you got the "main" tab controller visible.
[edit:] here's a short example in (Pseuod) code:
MainViewController.m:
-(void) viewWillAppear:(BOOL)anmiated
{
UIApplicationDelegate* appDelegate = [[UIApplication sharedApplication] delegate];
if (!appDelegate.isLoggedIn) {
appDelegate.loginController = [[UIViewController alloc ] initFromNib:@"login"];
[self presentModalViewController:appDelegate.loginController animated:NO];
}
}
in the LoginController
- (iBAction) loginClicked
{
[appDelegate.mainViewController dismissModalViewControllerAnimated:YES];
}
This obviously assumes that you have references to your view controllers in the appdelegate.
A: Instead of swapping out the whole controller, why not just remove and add tab bar items for each of your modes? When your in your first mode, show tab bar items 1,2 and 3. If someone hits one, then remove all those items, and add items 4,5 and 6. Use the tag on the items to keep track of them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633751",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Circular / rotary dial view in android I have a need to create a circular dial/rotary style component for use in an application. It's essentially a circular menu that allows users to select from the items that are ringed around it, and then they can click the button in the center to activate the selected item. However, I've never created a custom UIView of this type, and don't really know where to begin. Can anyone give me any pointers as to how I would draw the view and then rotate it as the user drags their finger? I obviously know how to intercept touch events, etc. but I'm not sure how to actually go about manipulating the UI appropriately. Any tips or pointers would be great!
A: I don't know if you've already found a solution to this, but here is a nice overview of how to get started:
http://shahabhameed.blogspot.com/2011/05/custom-views-in-android.html
For you, I think you can extend an existing View, that View being the SeekBar. You can take the standard SeekBar and draw it in a circle.
Finally, here is a source code that does the rotation with a volume knob. It is its own project though, so you have to do some work to use it in your own app.
http://mindtherobot.com/blog/534/android-ui-making-an-analog-rotary-knob/
Good Luck!
A: I have a neat library to do this. It is extremely stable and well maintained. https://bitbucket.org/warwick/hgdialrepo
Heres a youtube demo: https://youtu.be/h_7VxrZ2W-g
This library comes with a demo app with source code and the demo app actually uses a dial as a menu, So I think this should be the perfect solution for you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to unregister / cancel UILocalNotification I have some trouble finding this. Actually I want to unregister / cancel all of my local notification when I kill my appln from background. Any thoughts how can I do that.
A: Just do this to cancel all local notifications.
[[UIApplication sharedApplication] cancelAllLocalNotifications];
And, of course, you can't do this when the app is killed from multi-tasking bar, since your app will not be notified by any means when it is killed from multi-tasking bar.
A: When your app is killed while in the background you do NOT get any notification and you do NOT get any chance to run or cleanup. You must do this when you go into the background or wait until your app comes back to the foreground.
When an app is killed from the task bar while in the background it is sent a SIGKILL signal which cannot be caught by a signal handler, it is just summarily killed with no warning to the app.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to draw a image as a texture of a polygon and how to rotate the polygon in all directions touching the polygon on the screen? I need to draw a texture on a square polygon, not a cube, i need to do it on a symple square, it is the face of a cube. I check this tutorial (open gl ES)and it seems to work fine for writting a texture on a square polygon: http://blog.jayway.com/2010/12/30/opengl-es-tutorial-for-android-%E2%80%93-part-vi-textures/
OK, but now i need to rotate the polygon with the finger, touching the screen. I need that the user can interact with the polygon touching it, moving the polygon in the direction that he moves the polygon with the finger.
How can i do it?
A: As you are using opengl es, there is a function called glrotate which is used to rotate the object. here is the link
http://www.khronos.org/opengles/sdk/1.1/docs/man/glRotate.xml
Just call this function according to the user touch interaction.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery customize fancybox with ajax call I'm using this brilliant solution for showing a fancybox as a result of a POST request.
The problem is that I don't know how to customize the fancybox behaviour.
How to show a spinning animation (or similar) while the ajax is performed?
How to set a title/show the content of the fancybox as (stylized) html?
A: function formatTitle(title, currentArray, currentIndex, currentOpts) {
return '<div id="tip7-title"><span><a
href="javascript:;"onclick="$.fancybox.close();"><img src="/data/closelabel.gif" />
</a></span>' + (title && title.length ? '<b>' + title + '</b>' : '' ) + 'Image ' +
(currentIndex + 1) + ' of ' + currentArray.length + '</div>';
}
function showResponse(responseText){
//first of all hide the spinning animation div
//then process the response as you like
$.fancybox({
'content' : responseText,
'titlePosition' : 'inside',
'titleFormat' : formatTitle
});
}
function showspinningAnimation(iddiv_container){
//this function is called before the ajax call
//put your animation spinning or whatever in a div
}
var options = {
beforeSubmit: showRequest, // pre-submit callback
success: showResponse
};
$(document).ready(function() {
$("#myForm").ajaxForm(options);
});
Explain:
formatTitle: This function format the title for your fancybox
showspinningAnimation : In this function put a spinning .gif (as example) in a div showing the loading...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633762",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Bidirectional relationship with superclass entity property in JPA I'm tying to implement some tree-like structure with JPA.
I have a "folder" entity and a "test" entity. Folder can contain both folders and tests. Test doesnt contains anything.
Both test and folder have a Node superclass, looks like this:
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Node implements TreeNode, Serializable{
private Long id;
String description;
String name;
@ManyToOne
Node parent;
...getters, setters and other stuff that doesnt matter...
}
And here is the Folder class:
@Entity
public class Folder extends Node{
@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany(cascade=CascadeType.ALL, **mappedBy="parent"**)
List<Folder> folders;
@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany(cascade=CascadeType.ALL, **mappedBy="parent"**)
List<Test> tests;
...
}
So the main problem is the mappedBy property, which relates to superclass property not overriden in ancestor, cause I got such exception:
Exception while preparing the app : mappedBy reference an unknown target entity property: my.test.model.Folder.parent in my.test.model.Folder.folders
There is might be some tricky mapping over "folders" and "test" properties of Folder class, and I need a little help with that.
EDIT: I specified both folders and tests properties of Folder class with targetEntity=Node.class:
@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany(cascade=CascadeType.ALL, mappedBy="parent",targetEntity=Node.class)
List<Folder> folders;
@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany(cascade=CascadeType.ALL, mappedBy="parent",targetEntity=Node.class)
List<Test> tests;
And its gets work. But works not fine. Now both tests and folders mapped to both properties (I dont know why I'm not geting exceptions), when I need to get them separately.
So I'm still looking for a suitable mappings to achieve that. I would appriciate any help.
A: Interesting structure, probably contains many challenges. But to the question about relationship to superclass entitys property: unfortunately you cannot do that with Hibernate. Your approach to set targetEntityClass also does not work, because it effectively changes type of collection elements from entity mapping point of view.
Luckily there is workaround. You can have relationship from entity to the property of MappedSuperClass, which you extend. Likely you do not want to make Node to be MappedSuperClass, so you have to add new. And then it have to be located between Node and Folder: Folder->MappedSuperClass->Node. It goes like this (such a approach works at least with Hibernate 3.5.6, no idea since which version it is supported):
public class Node {
... //without parent attribute, otherwise as before
}
@MappedSuperclass
public class SomethingWithParent extends Node {
@ManyToOne
Node parent;
}
public class Folder extends SomethingWithParent {
..
//as before
}
public class Test extends SomethingWithParent {
...//as before
}
By the way, isn't Node bit too generic for Parent? At least if it is used only for this purpose. All parents are folders.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633769",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Make array with arrays from a mysql query Working on a e-shop, i must read from the DB the products that have productpack not null.
productpack from the DB looks like this : 0141,3122,0104,0111,3114,0106,0117 .
I'm trying to get all the DB items that have productpack set (not null), and make them into an array with arrays with those codes (0141,3122,0104,0111,3114,0106,0117).
function p_productpacks(){
$productpacks = array();
$pack = array();
$q = mysql_query('SELECT productpack FROM products WHERE productpack <> "";');
while($p = mysql_fetch_object($q)){
$pack = explode(",", $p);
$productpacks[] = $pack;
}
return $productpacks;
}
A: You need to create an array otherwise, you're overwriting existing packs:
$pack = explode(",", $p->productpack);
$productpacks[] = $pack;
For more information read about array_pushDocs and PHP Arrays Docs (and mysql_fetch_objectDocs).
A: You can get all productpacks in a CSV array using:
$result = mysql_query("SELECT GROUP_CONCAT(productpack) as productpacks
FROM products WHERE productpack <> '' ");
if ($result) {
$row = mysql_fetch_row($result);
$productpacks_as_CSV_string = $row['productpacks'];
}
That way you only need to get one row out of the database, saving lots of time.
See: http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
A: mysql_fetch_object returns an object and can't be used with string processing.. if you definitely want to use this, you need to do something like:
$pack=explode(',',$p->productpack);
$productpacks[]=$pack
Or, to use a good old array instead:
while ($p = mysql_query($q))
{
$pack = explode(",", $p['productpack']);
$productpacks[] = $pack;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633772",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Reflection error when creating an instance of a form I've been experimenting with an application that will scan an assembly, check for any classes that are forms and then see what members they have.
The code I'm using to query the assemblies is:
Assembly testAssembly = Assembly.LoadFile(assemblyPath);
Type[] types = testAssembly.GetTypes();
textBox1.Text = "";
foreach (Type type in types)
{
if (type.Name.StartsWith("Form"))
{
textBox1.Text += type.Name + Environment.NewLine;
Type formType = testAssembly.GetType();
Object form = Activator.CreateInstance(formType);
}
}
I'm using this to query a standard form:
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace TestForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}
My problem is that when the code tries Activator.CreateInstance(formType) I get an exception stating: "No parameterless constructor defined for this object."
I can also see from checking formType that 'DeclaringMethod: 'formType.DeclaringMethod' threw an exception of type 'System.InvalidOperationException''
I don't understand the error message as the form has a standard constructor, am I missing something really obvious?
EDIT : type.Name reveals the type that the code is trying to instantiate as being Form1.
A: You are trying to create an instance of Assembly, not of your form:
Type formType = testAssembly.GetType();
Object form = Activator.CreateInstance(formType);
You should do:
Object form = Activator.CreateInstance(type);
BTW, I wouldn't use the name of the class to check if it is derived from Form, you can use IsSubclassOf:
type.IsSubclassOf(typeof(Form));
A: Object form = Activator.CreateInstance(type);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Fastest access of a file using Hadoop I need fastest access to a single file, several copies of which are stored in many systems using Hadoop. I also need to finding the ping time for each file in a sorted manner.
How should I approach learning hadoop to accomplish this task?
Please help fast.I have very less time.
A: If you need faster access to a file just increase the replication factor to that file using setrep command. This might not increase the file throughput proportionally, because of your current hardware limitations.
The ls command is not giving the access time for the directories and the files, it's showing the modification time only. Use the Offline Image Viewer to dump the contents of hdfs fsimage files to human-readable formats. Below is the command using the Indented option.
bin/hdfs oiv -i fsimagedemo -p Indented -o fsimage.txt
A sample o/p from the fsimage.txt, look for the ACCESS_TIME column.
INODE
INODE_PATH = /user/praveensripati/input/sample.txt
REPLICATION = 1
MODIFICATION_TIME = 2011-10-03 12:53
ACCESS_TIME = 2011-10-03 16:26
BLOCK_SIZE = 67108864
BLOCKS [NUM_BLOCKS = 1]
BLOCK
BLOCK_ID = -5226219854944388285
NUM_BYTES = 529
GENERATION_STAMP = 1005
NS_QUOTA = -1
DS_QUOTA = -1
PERMISSIONS
USER_NAME = praveensripati
GROUP_NAME = supergroup
PERMISSION_STRING = rw-r--r--
To get the ping time in a sorted manner, you need to write a shell script or some other program to extract the INODE_PATH and ACCESS_TIME for each of the INODE section and then sort them based on the ACCESS_TIME. You can also use Pig as shown here.
How should I approach learning hadoop to accomplish this task? Please help fast.I have very less time.
If you want to learn Hadoop in a day or two it's not possible. Here are some videos and articles to start with.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.