text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Surface extraction a fluid . At a given time-step I have a sampled a lot points from a fluid , and I want to extract the
points which lie at the surface of the fluid. Does any one know a good algorithm
and any available codes to do this?
I am aware of surface reconstruction, but the assumption there is that the sampled points
are on/near the surface. So I guess that would not be too useful here.
A: Is finding the convex hull of the points adequate? How many points do you have?
Maybe start with a convex hull and then modify it to allow a certian amount of concavity where there are large parts of the surface without any points nearby.
Otherwise try fitting a spline or similar polynomial function to the points. You need some sort of cost metric to measure how good your fit is so that you don't bend your surface too much to reach the inner points. (Unless sharp high curvature sections are allowed for breaking waves etc?)
Is this a tank that get's moved about causing sloshing or something similar - if so there may be some physics model you can used to suggest the shape of surfaces likely to be found. The pattern of motion and speed of waves in the fluid may tell you how many waves etc you'd see.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: GWT
A: It is more idiomatic to call external functions using JSNI:
native void facebookComment(Document d, String s, String id) /*-{
fbc(d, s, id);
}-*/;
void myFunction() {
facebookComment(Document.get(), "script", "facebook-jssdk");
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Div height is adjusting to height of child div when child div is floating left, but not when it's floating right I'm working on my sister's website.
I have a problem with the DIV height not adjusting to 100% of the hight of all its child elements. What's weird is that for the child div in question, if I set the float to left, the height adjusts fine, but when it's floating right the containing div comes up short.
Site: http://www.lindsaybryden.com/
Floating Right:
Floating Left:
How can I get the height adjusting properly while floating the child div right?
A: You are clearing only the left float, not the right float. Try adding
<br style="clear: both;" />
just before the close of divContainer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602058",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SWT GTK 64 bit and UBUNTU 11.04 NPE I'm currently working in an SWT standalone application. We usually work with windows but I'd like to work in Ubuntu.I set up the following environment.
Ubuntu 11.04 64bit
Java 6 update 27 64 bit
Eclipse Java EE 3.5 Galileo 64 bit
I'm using SWT GTK 64 bit
I've got a few classes extending different SWT widgets.
For example
public class MyCombo extends Combo implements CellEditor<Long> {
private Set<ListenerRef> listeners = new HashSet<ListenerRef>();
@Override
public void addListener(int eventType, Listener listener) {
listeners.add(new MyCombo.ListenerRef(eventType, listener));
super.addListener(eventType, listener);
}
@Override
protected void checkSubclass() {
// Do nothing
}
.
.
.
This code works perfectly well in Windows 7 64 bit, running SWT32 bit and java32 bit, from eclipse 32 bit.
In Ubuntu 11.04 I get a NPE (NullPointerException) when trying to add a listener, it seems that the listeners set is null, but it shouldn't cause that set should be initialized as for the code above, and as I say it works in Windows 7
First I had problems running the SWT 32 bit app in Ubuntu64 bit cause there's seem to be a bug when running 32 apps in 64 ubuntu, so I tried to run it with the 64 version, and now I'm getting this error. If I avoid this NPE checking the set, I end up getting a
java.lang.NullPointerException
at org.eclipse.swt.accessibility.Accessible.isValidThread(Unknown Source)
at org.eclipse.swt.accessibility.Accessible.checkWidget(Unknown Source)
at org.eclipse.swt.accessibility.Accessible.addRelation(Unknown Source)
Any ideas of what could be the reason? Are you aware of this problem in previous Ubuntu distrubutions? I don't get this problems in Windows 7, at least running SWT 32 bit
Please let me know if you need more details
Thanks and regards
BTW I forgot, SWT is 3.7 in Linux and 3.6.2 in Windows
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602067",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: .Net calling Java Webservice, I need to convert an XMLSchema/long to anXMLSoap/long I am using C# with .net 4 and am trying to consume a java webservice. My code was autogenerated by adding a .net 2.0 style webservice reference. I believe there is an issue with the types .net is sending to the java webservice, here is the exception I receive when I attempt to connect:
Internal Server Error (deserialization error: deserialization error: unexpected element type: expected={http://schemas.xmlsoap.org/soap/encoding/}long, actual={http://www.w3.org/2001/XMLSchema}long)
Old documentation from the webservice:
When serializing objects to SOAP messages, the Microsoft .NET platform maps all primitives to W3C XML
schema types. This, in conjunction with the .NET platforms inability to differentiate primitives from primitive
wrappers (through auto-boxing) causes an interoperability problem with Sun One web services when using
encoded RPC SOAP messages.
In the Java programming language primitives and their equivalent object wrappers cannot be auto-boxed
thus are differentiated in the language.
When the web services are generated and deployed under Sun One, the server side WSDL maps Java
primitives to the W3C schema type and maps Java Objects to the SOAP schema type.
Does anyone know how I can tell .net to send a http://schemas.xmlsoap.org/soap/encoding/}long instead of a http://www.w3.org/2001/XMLSchema}long?
Thanks!
AFrieze
A: Suggest you to try changing the style to Document. This way , when you generate the wsdl , you will find a <type></type> section listing all data types used by the service. This section will also have a namespace element that is essentially what is causing the problem right now with you, but which is not apparent because with RPC style of service , wsdl does not contain a section for types. I am assuming the encoding is literal.
edit :
I should have guessed it first , but it seems like your service uses encoded types rather than literal. A thing about encoded services is that they are always prone to interoperability issues. My recommendation : Do not use rpc/encoded - use Document/Literal.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript's `window.resizeTo` isn't working I'm trying to create a bookmarklet to do some very specific resizing to do browser size testing, and I can't seem to get the web browser to resize using window.resizeTo.
Overly simplified example that doesn't work:
javascript:window.resizeTo(1024,600);
I can understand that browsers might have disabled this feature, but here's a screenshot of my JavaScript Settings in Firefox:
Am I missing something obvious or should I file a bug report?
A: According to this bug report, this is a new feature, not a bug. Specifically:
Two rules:
*
*Can't resize a window/tab that hasn't been created by window.open.
*Can't resize a tab if the tab is in a window with more than one tab.
If I understand this "fix" correctly, you can resize only your own popup windows, not the main window.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
}
|
Q: How to add a fade-in effect in jQuery text How to add a fade-in effect when the data is returned to the #results div?
$('#results').html(data);
I tried
$('#results').html(data).fadeIn('slow');
but it doesn't seem to work
My code
submitHandler: function(form) {
// do other stuff for a valid form
$.post('mailme.php', $("#myform").serialize(), function(data) {
$('#results').html(data).fadeIn('slow');
});
}
A: You gotta hide the div first.
$('#results').hide().html(data).fadeIn('slow');
A: This might just do the trick.
$('#results').css('display', 'none').html(data).fadeIn('slow');
A: you have to hide element firstly when you are working with "fadeIn".
here is a example, I believe you will understand after trying and editing that:
<img style="display: none;" id="google" src="http://www.google.com.tr/images/srpr/logo3w.png" alt="" />
<script>
$(document).ready(function() {
$('#google').fadeIn(1200,function(){});
});
</script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602080",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Parsing XML in vb.net I have some XML that a vendor is supplying me and I can not parse it in VB.net no matter what I try. I am a novice at XML so please be understanding of that.
This is the xml that the vendor sent me:
<?xml version='1.0'?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xsd:element name="event">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="id" type="xsd:integer"></xsd:element>
<xsd:element name="old_id" type="xsd:integer"></xsd:element>
<xsd:element name="opponent" type="xsd:string">Austin MS</xsd:element>
<xsd:element name="game_date" type="xsd:string">2011-08-31</xsd:element>
<xsd:element name="start_time" type="xsd:string">5:00PM</xsd:element>
<xsd:element name="end_time" type="xsd:string">8:00PM</xsd:element>
<xsd:element name="sport" type="xsd:string">Baseball</xsd:element>
<xsd:element name="level" type="xsd:string">7th</xsd:element>
<xsd:element name="gender" type="xsd:string">Boys</xsd:element>
<xsd:element name="year" type="xsd:string">2011</xsd:element>
<xsd:element name="season" type="xsd:string">Fall</xsd:element>
<xsd:element name="status" type="xsd:string">Deleted</xsd:element>
<xsd:element name="homeaway" type="xsd:string">Home</xsd:element>
<xsd:element name="facility">France</xsd:element>
<xsd:element name="facility_id" type="xsd:integer"></xsd:element>
<xsd:element name="opponent">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="ss_id" type="xsd:integer">19505</xsd:element>
<xsd:element name="name" type="xsd:string">Austin MS</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="location">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="ss_id" type="xsd:integer">108</xsd:element>
<xsd:element name="name" type="xsd:string">Breck School</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="score">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="result" type="xsd:string"></xsd:element>
<xsd:element name="ours" type="xsd:string"></xsd:element>
<xsd:element name="theirs" type="xsd:string"></xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="league" type="xsd:string"></xsd:element>
<xsd:element name="type" type="xsd:string">Championship</xsd:element>
<xsd:element name="ss_id" type="xsd:string">305</xsd:element>
<xsd:element name="transportation" type="xsd:string"></xsd:element>
<xsd:element name="dismissal" type="xsd:string"></xsd:element>
<xsd:element name="return" type="xsd:string"></xsd:element>
<xsd:element name="comment">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="school" type="xsd:string"></xsd:element>
<xsd:element name="conference" type="xsd:string"></xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="home_team" type="xsd:string">Breck - St Paul - Apple Valley</xsd:element>
<xsd:element name="activity_type" type="xsd:string">conference</xsd:element>
<xsd:element name="category" type="xsd:string"></xsd:element>
<xsd:element name="sub_category" type="xsd:string"></xsd:element>
<xsd:element name="state" type="xsd:string">MN</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
I have tried to use XSD.exe to create a vb.net class and it errors. I have contacted the vendor who supplied the XML but they haven't been much help. I would like to be able to pump this XML into a function and have it pop out a list(of SportEvents) with the properties and lists that are in the XML.
I would be greatful for any help in pointing me in the right direction.
Thanks
A: The method that I have used is to implement the System.Xml functionality http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx
Dim configDoc As XmlDocument = New XmlDocument()
Dim nodes As XmlNodeList = Nothing
Dim stringHolder as String = ""
you load the document like such
configDoc.Load("filepath") 'load the file
then pull in the values either single node or list of nodes
stringHolder = configDoc.SelectSingleNode("/xpath").attributes.getNamedItem("attributeName").Value.toString()
or for a list of inner nodes.
nodes = configDoc.SelectNodes("/xpath")
for each n as XmlNode in nodes
stringHolder = n.attributes.getNamedItem("attributeName").Value.toString()
'do stuff with string
next
now these ways only deal with attributes of xml nodes. if you need the inner text then you can research .innertext() its very simmiler. hope this helps to at least get you pointed in the right direction.
|
{
"language": "cs",
"url": "https://stackoverflow.com/questions/7602081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I get a Java Servlet Container to save files as an "owner / group" other than Tomcat? I have a java servlet. When it saves files, it saves them as tomcat:tomcat (in a linux environment). I actually need it to save it as sportsfan:tomcat as sportsfan is the FTP user and also needs access to create, modify or overwrite these files.
I thought about running tomcat as sportsfan:tomcat, but I'm running multiple applications under the one tomcat instance.
Perhaps the best way to do this would be to have the FTP user log in as part of the tomcat group. Would that be a correct way?
Please advise.
A: Adding your sportsfan user ftp to the tomcat group could be a good solution but before that check which are the modifiable files in you system with this permission and consider the security risks.
Another solution: Create a sportsfan group and add your sportsfan user to it. Then change the group of your upload directory and set it as setgid:
chgrp sportsfan upload
chmod g+s upload
After that the new files in the upload will be created with tomcat:sportsfan owner:group. It's not exactly what you asked for but changing the user id (setuid directories) is not supported on Linux. Wikipedia has a pretty good article about setuid and setgid directories. Futhermore, you have to set the umask value of the tomcat user to 000x (e.g. 0002) or a similar value which gives full access to the group.
3rd solution: set up a cron job which changes the permission in every n minutes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602085",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Examining associated objects in equals() Standard object modelling identifies attributes, aggregates and associations of objects. You must conform to several requirements when implementing the equals() method of a class. There is plenty of advice available on how to write this method, including pitfalls to avoid. But I couldn't find any advice indicating whether you should or should not examine associations when implementing equals(). It is clear to me that you should examine attributes and aggregates.
Should you examine associated objects in equals()? That is, should equality depend on associated objects?
A: While I think it is generally a good idea to avoid basing equality on associations, I would argue that this does not apply in all cases. While it is a good rule of thumb, there are likely a number of cases where this rule breaks completely.
It is entirely dependent on the domain and what it means for two objects to be equal. For example:
If you have a cohort of students, taught by a teacher, you could determine equality by requiring that another cohort must contain the same students be (pair-wise equal) and be taught by the same teacher. In that case, the cohort's equality is strictly dependent on each of it's pieces being equal.
A: Equality should not depend in any way on associated objects, therefore equals() should not examine associates. It should not even depend on the identity of associates, or even whether an object has an association. I'm surprised that this advice is not explicitly stated often enough for me to have found it.
*
*From an object modelling point of view, it is natural to consider two things with different associations to be equivalent. If a mad scientist were to create an exact duplicate of me, we would say the doppelgänger and I were "the same" (equivalent), even though we had different fathers (different fathered-by associations). The doppelgänger might not even have a father (if the scientist were more mad physicist than mad biologist).
*Examining associations introduces practical problems. There is the danger of bi-directional associations (spouse-of, for example) causing infinite loops. There is the performance hit of indirect associations requiring examination of potentially all objects in the working-set: if your Person objects have parent-of and child-of associations, Person.equals() would actually tell you whether family trees were equivalent.
A: in general perhaps not. but how about a car that has frame, body, engine, wheels etc. one could consider different implementations of equals.
A: Short answer: make equals() do what you need it to do. But be careful.
Where the class may be used as a key in a HashMap (or stored in a HashSet), equals() must be constant for the time that it's in the map. This suggests that, in order to avoid a lot of analysis and/or bugs, classes used as HashMap keys should restrict equals() to effectively immutable fields - including associations.
You also must ensure that any equals-included associated object has a similarly immutable-for-contained-scope equals() implementation, and doesn't do an equals() back on the original object, causing runaway recursion.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: 7 Buttons, 3 AsyncTasks, 1 Activity, and a nightmare Just when I thought I had this one cinched, I realized that I can only use the buttons in the activity in the same sequence they are written in the Activity.java (Ex: Cannot execute button 5 press, until 1,2,3,and 4 have all been pressed!)
How do I fix this?
Activity.Java:
public class TwoActivity extends Activity {
ProgressBar progressBar;
TextView textView41;
TextView textView42;
TextView textView43;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.two);
progressBar = (ProgressBar)findViewById(R.id.progressbar_Horizontal);
progressBar.setProgressDrawable(getResources().getDrawable(R.drawable.blue_progress));
textView41 = (TextView)findViewById(R.id.dl41text);
textView42 = (TextView)findViewById(R.id.dl42text);
textView43 = (TextView)findViewById(R.id.dl43text);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startDownload();
}
});
}
private void startDownload() {
String url = "http://dl.dropbox.com/u/43058382/steelers1.jpg";
new DownloadFileAsync().execute(url);
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
progressBar.setProgress(0);
progressBar.setVisibility(View.VISIBLE);
textView41.setVisibility(View.VISIBLE);
super.onPreExecute();
}
@Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/steelers1.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
progressBar.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String unused) {
progressBar.setVisibility(View.INVISIBLE);
textView41.setVisibility(View.INVISIBLE);
Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View w) {
startDownload();
}
});
}
private void startDownload() {
String url = "http://dl.dropbox.com/u/43058382/steelers2.jpg";
new DownloadFileAsync2().execute(url);
}
class DownloadFileAsync2 extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
progressBar.setProgress(0);
progressBar.setVisibility(View.VISIBLE);
textView42.setVisibility(View.VISIBLE);
super.onPreExecute();
}
@Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/steelers2.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
progressBar.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String unused) {
progressBar.setVisibility(View.INVISIBLE);
textView42.setVisibility(View.INVISIBLE);
Button button3 = (Button) findViewById(R.id.button3);
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View w) {
startDownload();
}
});
}
private void startDownload() {
String url = "http://dl.dropbox.com/u/43058382/steelers3.jpg";
new DownloadFileAsync3().execute(url);
}
class DownloadFileAsync3 extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
progressBar.setProgress(0);
progressBar.setVisibility(View.VISIBLE);
textView43.setVisibility(View.VISIBLE);
super.onPreExecute();
}
@Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/steelers3.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
progressBar.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String unused) {
progressBar.setVisibility(View.INVISIBLE);
textView43.setVisibility(View.INVISIBLE);
Button button16 = (Button) findViewById(R.id.button16);
button16.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Intent myIntent = new
Intent(TwoActivity.this, ModdifyMyWiiActivity.class);
TwoActivity.this.startActivity(myIntent);
}
});
Button button18 = (Button) findViewById(R.id.button18);
button18.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Intent myIntent = new
Intent(TwoActivity.this, ThreeActivity.class);
TwoActivity.this.startActivity(myIntent);
}
});
Button button19 = (Button) findViewById(R.id.button19);
button19.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Intent myIntent = new
Intent(TwoActivity.this, FourActivity.class);
TwoActivity.this.startActivity(myIntent);
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuexit:
final Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
break;
case R.id.menucontact:
final Intent intent1 = new Intent(android.content.Intent.ACTION_SEND);
intent1.setType("text/plain");
intent1.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { "johnnyb15613@gmail.com" });
intent1.putExtra(android.content.Intent.EXTRA_SUBJECT, "Transform Mii Help");
final PackageManager pm = getPackageManager();
final List<ResolveInfo> matches = pm.queryIntentActivities(intent1, 0);
ResolveInfo best = null;
for (final ResolveInfo info : matches)
if (info.activityInfo.packageName.endsWith(".gm") ||
info.activityInfo.name.toLowerCase().contains("gmail")) best = info;
if (best != null)
intent1.setClassName(best.activityInfo.packageName, best.activityInfo.name);
startActivity(intent1);
break;
}
return true;
}
}
}
}
}
And her is the layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/main_bg_hdpi" xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:weightSum="1">
<ScrollView android:id="@+id/scrollView1" android:layout_centerHorizontal="true" android:layout_alignParentTop="true" android:layout_width="match_parent" android:layout_height="390dp">
<RelativeLayout android:id="@+id/relativeLayout1" android:layout_width="fill_parent" android:orientation="vertical" android:weightSum="1" android:layout_height="wrap_content">
<Button android:src="@drawable/fourone_files" android:background="@drawable/modfiles41" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button1" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_marginTop="22dp"></Button>
<Button android:src="@drawable/fourtwo_files" android:background="@drawable/modfiles42" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button2" android:layout_alignTop="@+id/button1" android:layout_centerHorizontal="true"></Button>
<Button android:src="@drawable/fourthree_files" android:background="@drawable/modfiles43" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button3" android:layout_alignTop="@+id/button2" android:layout_alignParentRight="true"></Button>
<Button android:background="@drawable/unused" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button4" android:layout_below="@+id/button3" android:layout_alignParentLeft="true" android:layout_marginTop="22dp"></Button>
<Button android:background="@drawable/unused" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button5" android:layout_alignBottom="@+id/button4" android:layout_centerHorizontal="true"></Button>
<Button android:background="@drawable/unused" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button6" android:layout_alignBottom="@+id/button5" android:layout_alignParentRight="true"></Button>
<Button android:background="@drawable/unused" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button7" android:layout_below="@+id/button4" android:layout_alignParentLeft="true" android:layout_marginTop="22dp"></Button>
<Button android:background="@drawable/unused" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button8" android:layout_alignBottom="@+id/button7" android:layout_alignLeft="@+id/button5"></Button>
<Button android:background="@drawable/unused" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button9" android:layout_alignBottom="@+id/button8" android:layout_alignParentRight="true"></Button>
<Button android:background="@drawable/unused" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button10" android:layout_below="@+id/button7" android:layout_alignParentLeft="true" android:layout_marginTop="22dp"></Button>
<Button android:background="@drawable/unused" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button11" android:layout_alignBottom="@+id/button10" android:layout_alignLeft="@+id/button8"></Button>
<Button android:background="@drawable/unused" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button12" android:layout_alignTop="@+id/button11" android:layout_alignParentRight="true"></Button>
<Button android:background="@drawable/unused" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button13" android:layout_below="@+id/button10" android:layout_alignParentLeft="true" android:layout_marginTop="22dp"></Button>
<Button android:background="@drawable/unused" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button14" android:layout_alignBottom="@+id/button13" android:layout_alignLeft="@+id/button2"></Button>
<Button android:background="@drawable/unused" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button15" android:layout_alignBottom="@+id/button14" android:layout_alignParentRight="true"></Button>
<TextView android:text="** Get your System Menu Version by accessing the Wii Options Menu " android:id="@+id/CustomFontText" android:layout_width="match_parent" android:layout_height="wrap_content" android:singleLine="true" android:ellipsize="marquee" android:marqueeRepeatLimit="marquee_forever" android:scrollHorizontally="true" android:paddingLeft="5dip" android:paddingRight="5dip" android:focusable="true" android:focusableInTouchMode="true" android:freezesText="true" android:textColor="@color/wiiblue" android:textStyle="bold" android:layout_below="@+id/button15" android:layout_marginTop="22dp"></TextView>
<ProgressBar android:layout_width="fill_parent" android:layout_height="35dp" style="?android:attr/progressBarStyleHorizontal" android:id="@+id/progressbar_Horizontal" android:max="100" android:layout_below="@+id/button15" android:layout_marginTop="15dp" android:visibility="invisible" ></ProgressBar>
<TextView android:id="@+id/dl41text" android:text="Downloading 4.1 Mod Pack..." android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="@color/white" android:textStyle="bold" android:gravity="center" android:visibility="invisible" android:layout_below="@+id/button15" android:layout_marginTop="22dp"></TextView>
<TextView android:id="@+id/dl42text" android:text="Downloading 4.2 Mod Pack..." android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="@color/white" android:textStyle="bold" android:gravity="center" android:visibility="invisible" android:layout_below="@+id/button15" android:layout_marginTop="22dp"></TextView>
<TextView android:id="@+id/dl43text" android:text="Downloading 4.3 Mod Pack..." android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="@color/white" android:textStyle="bold" android:gravity="center" android:visibility="invisible" android:layout_below="@+id/button15" android:layout_marginTop="22dp"></TextView>
</RelativeLayout>
</ScrollView>
/>
Menu does not show either! All help appreciated!
A: You need to override the method onCreateOptionsMenu. I give you the sample code:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(group1Id,searchBtnId ,searchBtnId,"Search");
menu.add(group2Id,scheduleBtnId ,scheduleBtnId,R.string.schedule);
menu.add(group2Id,playBtnId ,playBtnId,"Play");
menu.add(group2Id,stopBtnId ,stopBtnId,R.string.stop);
return super.onCreateOptionsMenu(menu);
}
A: Why not create one Async class that can do 4 different types of downloads? This class would take as parameters: the button, the textview, and the url. Then you have 1/4 as much code. In the async, make all the buttons non clickable (setClickable(false)).
At any rate, you need to assign an onclicklistener for all the buttons at OnCreate(). You could make a custom class and switch on the button type, or just do the individualized anonymous class route.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
}
|
Q: Setting up Flex / AIR project structure for a large number of images? We build prototypes and demo applications in Flex 4.5.1 and AIR 2.7 for mobile and desktop use. These tend to involve a large number of full-screen .PNG files. Lately we have been looking at ways to segment our code for flexibility and multi-screen re-use.
What suggestions do people have for segmenting the project and libraries such that compile times are minimal and images are easy to replace?
A: A couple of strategies pop to mind:
*
*Externalize the assets from in-line [Embed] statements, to using a CSS file.
*Configure the CSS to compile as a seperate SWF, and load it at runtime. This should minimize the amount of PNG encoding the compiler is doing during your normal compilation process.
*If that still doesn't speed it up enough (I've found that the incremental compiler sometimes gets mixed up and re-encoded the embedded assets, killing compiler speed), move the CSS files to a separate project altogether.
This option is preferable, as loading your images at runtime gives you better flexibility in your multi-screen projects.
Alternatively:
*
*If using CSS isn't an option for some reason, move your [Embed]'s from your main project to a separate SWC project, and embed them on classes.
*Add the swc as a dependant project
*Reference the assets via the classes.
eg:
// assets-project/src/Images.as
public class Images {
[Embed('/assets/img/defaultAvatar.png')]
public static var defaultAvatar:Object;
}
// main-project/src/SomeView.mxml
<s:BitmapImage source="{Images.defaultAvatar"} />
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Counting number of associations across several Rails objects class Article
has_many :comments
end
class Comment
belongs_to :article
end
I'd like to be able to determine how many total comments exist for certain articles. For example: Article #20, #21 and #22 have a total of X comments between them.
Any pointers would be great!
A: I suggest this:
Comment.where(:article_id => [20, 21, 22]).count
Doing the counting etc. in the database and all in one query (which ActiveRecord will, in this case) is about as efficient as possible.
A: You could add a counter_cache to your articles table
class Article
has_many :comments, :counter_cache => true
end
and add a comments_count column to your articles table.
(http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html) and then sum it as so.
Article.where(:id => [20,21,22]).sum(:comments_count)
A: You can easily do this without a counter cache if you prefer.
Article.where(:id => [20,21,22]).joins(:comments).count
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: git remove file from repository but leave it on file system I try to remove unnecessary files from git repository. That files were initially added and now they are in several branches. What I want is simply stop tracking changes in that files, I don't care what changes should stay there, but I need that files to stay on file system.
I tried following
git filter-branch --index-filter "git rm --cached --ignore-unmatch file_to_remove" HEAD
but that removed file from file system what is unwanted.
A: Just:
git rm --cached file [file ...]
Of course you'll need to make sure the offending files are added to your .gitignore so they don't get recommitted straight away
A: If you want to keep the file in the repository, you can use:
git update-index --assume-unchanged <fileName>
This keeps the current version of the file in the index, but you can change it all you want and git will ignore those changes.
A: Checkout and run git clean for each branch.
git-clean - Remove untracked files from the working tree
Cleans the working tree by recursively removing files that are not under version control, starting from the current directory.
https://git-scm.com/docs/git-clean
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602106",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "37"
}
|
Q: jasper print loadObject with applet and servlet Why the applet is claiming for the Barbecue Renderer? By the way, my barbecue jar seems to be ok and included in the same folder.
network: Cache entry not found [url: http://localhost:8085/sg-fe/servlet/jasperprint, version: null]
network: Connecting http://localhost:8085/sg-fe/servlet/jasperprint with proxy=DIRECT
network: Connecting http://localhost:8085/ with proxy=DIRECT
network: Connecting http://localhost:8085/sg-fe/servlet/jasperprint with cookie "JSESSIONID=1B7B7C38E0625B8CB24D61A47343117F"
network: Cache entry not found [url: http://localhost:8085/sg-fe/pages/identidadeAcademicaFuncional/pedidos/net/sf/jasperreports/components/barbecue/BarbecueRenderer.class, version: null]
network: Connecting http://localhost:8085/sg-fe/pages/identidadeAcademicaFuncional/pedidos/net/sf/jasperreports/components/barbecue/BarbecueRenderer.class with proxy=DIRECT
network: Connecting http://localhost:8085/ with proxy=DIRECT
network: Connecting http://localhost:8085/sg-fe/pages/identidadeAcademicaFuncional/pedidos/net/sf/jasperreports/components/barbecue/BarbecueRenderer.class with cookie "JSESSIONID=1B7B7C38E0625B8CB24D61A47343117F"
network: Cache entry not found [url: http://localhost:8085/sg-fe/pages/identidadeAcademicaFuncional/pedidos/net/sf/jasperreports/components/barbecue/BarbecueRenderer.class, version: null]
network: Connecting http://localhost:8085/sg-fe/pages/identidadeAcademicaFuncional/pedidos/net/sf/jasperreports/components/barbecue/BarbecueRenderer.class with proxy=DIRECT
network: Connecting http://localhost:8085/sg-fe/pages/identidadeAcademicaFuncional/pedidos/net/sf/jasperreports/components/barbecue/BarbecueRenderer.class with cookie "JSESSIONID=1B7B7C38E0625B8CB24D61A47343117F"
network: Cache entry not found [url: http://localhost:8085/sg-fe/pages/identidadeAcademicaFuncional/pedidos/net/sf/jasperreports/renderers/BatikRenderer.class, version: null]
network: Connecting http://localhost:8085/sg-fe/pages/identidadeAcademicaFuncional/pedidos/net/sf/jasperreports/renderers/BatikRenderer.class with proxy=DIRECT
network: Connecting http://localhost:8085/sg-fe/pages/identidadeAcademicaFuncional/pedidos/net/sf/jasperreports/renderers/BatikRenderer.class with cookie "JSESSIONID=1B7B7C38E0625B8CB24D61A47343117F"
network: Cache entry not found [url: http://localhost:8085/sg-fe/pages/identidadeAcademicaFuncional/pedidos/net/sf/jasperreports/renderers/BatikRenderer.class, version: null]
network: Connecting http://localhost:8085/sg-fe/pages/identidadeAcademicaFuncional/pedidos/net/sf/jasperreports/renderers/BatikRenderer.class with proxy=DIRECT
network: Connecting http://localhost:8085/sg-fe/pages/identidadeAcademicaFuncional/pedidos/net/sf/jasperreports/renderers/BatikRenderer.class with cookie "JSESSIONID=1B7B7C38E0625B8CB24D61A47343117F"
net.sf.jasperreports.engine.JRException: Class not found when loading object from URL : http://localhost:8085/sg-fe/servlet/jasperprint
at net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:151)
at LamePrintThread$1.actionPerformed(LamePrintThread.java:35)
at java.awt.Button.processActionEvent(Button.java:409)
at java.awt.Button.processEvent(Button.java:377)
at java.awt.Component.dispatchEventImpl(Component.java:4629)
at java.awt.Component.dispatchEvent(Component.java:4455)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:649)
at java.awt.EventQueue.access$000(EventQueue.java:96)
at java.awt.EventQueue$1.run(EventQueue.java:608)
at java.awt.EventQueue$1.run(EventQueue.java:606)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:105)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:116)
at java.awt.EventQueue$2.run(EventQueue.java:622)
at java.awt.EventQueue$2.run(EventQueue.java:620)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:105)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:619)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:275)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:200)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:190)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:185)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:177)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:138)
Caused by: java.lang.ClassNotFoundException: net.sf.jasperreports.components.barbecue.BarbecueRenderer
at sun.plugin2.applet.Applet2ClassLoader.findClass(Applet2ClassLoader.java:252)
at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Plugin2ClassLoader.java:250)
at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Plugin2ClassLoader.java:180)
at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Plugin2ClassLoader.java:161)
at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at java.io.ObjectInputStream.resolveClass(ObjectInputStream.java:621)
at net.sf.jasperreports.engine.util.ContextClassLoaderObjectInputStream.resolveClass(ContextClassLoaderObjectInputStream.java:75)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1592)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1513)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1749)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1346)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1963)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1887)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1770)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1346)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:368)
at java.util.ArrayList.readObject(ArrayList.java:696)
at sun.reflect.GeneratedMethodAccessor18.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:991)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1865)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1770)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1346)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1963)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1887)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1770)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1346)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:368)
at java.util.ArrayList.readObject(ArrayList.java:696)
at sun.reflect.GeneratedMethodAccessor18.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:991)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1865)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1770)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1346)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1963)
at java.io.ObjectInputStream.defaultReadObject(ObjectInputStream.java:497)
at net.sf.jasperreports.engine.JasperPrint.readObject(JasperPrint.java:756)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:991)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1865)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1770)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1346)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:368)
at net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:143)
... 23 more
Is there a proper way to identify that sort of issue?
A snippet from my applet:
String strUrl = "http://localhosts:8085/sg-fe/servlet/jasperprint";
try {
URL url = new URL(strUrl);
JasperPrint jasperPrint = null;
jasperPrint = (JasperPrint) JRLoader.loadObject(url);
final JasperPrint print = jasperPrint;
JasperPrintManager.printReport(print, true);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (JRException e) {
e.printStackTrace();
}
A: You have to indicate what jar has to be loaded with your applet program. See the 'ARCHIVE' property in the applet tag. Here is an example:
<APPLET id="printer" name="printer" CODE = "MultiplePrinting.class" CODEBASE ="/rootapp/static/applets/printer/" ARCHIVE ="plugin.jar,PrintingAyudas.jar, jasperreports-3.7.6.jar, jasperreports-applet-3.7.6.jar,commons-digester-1.7.jar,commons-logging-1.0.4.jar,commons-collections-2.1.1.jar" WIDTH = "1" HEIGHT = "1">
<PARAM NAME = CODE VALUE = "MultiplePrinting.class" >
<PARAM NAME = CODEBASE VALUE = "/rootapp/static/applets/printer/" >
<PARAM NAME = ARCHIVE VALUE = "printer.jar,plugin.jar, jasperreports-3.7.6.jar,jasperreports-applet-3.7.6.jar,commons-logging-1.0.4.jar,commons-collections-2.1.1.jar,commons-digester-1.7.jar" >
<PARAM NAME="type" VALUE="application/x-java-applet;version=1.2.2">
<PARAM NAME="scriptable" VALUE="false">
</APPLET>
I hope it helps you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Selecting date value without time in SQL Server 2005 I am facing a problem selecting the date in SQL Server 2005. The table name is Softskill and the column name is insertdate. The data is stored as 2011-09-22 08:50:28.000 in this format.
To select, I am passing values from the front end as '2011-09-22', I mean the date only.
I tried to use
SELECT INSERTDATE FROM SOFTSKILL WHERE INSERTDATE = '2011-09-22'.
But it is not showing the record. May I know which format the column is following and is there any way to retrieve data by using only date?
A: You want to search for a range of times that encompass the day. Something like:
SELECT INSERTDATE
FROM SOFTSKILL
WHERE INSERTDATE >= '2011-09-22 00:00:00'
AND INSERTDATE < '2011-09-23 00:00:00'
You could also apply functions to INSERTDATE to extract just the date portion, but that will make the query nonsargable.
A: SELECT *
FROM SOFTSKILL
WHERE DATEADD(dd, 0, DATEDIFF(dd, 0, InsertDate)) = '2011-09-22'
A: This will do what you need
SELECT INSERTDATE
FROM SOFTSKILL
WHERE CAST(FLOOR(CAST(INSERTDATE AS FLOAT)) AS DATETIME) = '2011-09-30'
You need to truncate INSERTDATE so its time part is 00:00:00.000; then, it will be equal to '2011-09-30' assuming INSERTDATE is '2011-09-30 XX:XX:XX.xxx'.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602113",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: android: sensor data (ACCELEROMETER+MAGNETOMETER) TO image plane offset Here we go:
An android APP, I have extracted data from sensors(ACCELEROMETER & MAGNETROMETER) in my Desire HD, at the same time, I turn on the camera. what i am trying to do is to estimate the offset between two frames captured by the cam.
i have read a lot of QUESTIONS about this problem here, like gyro+acc+mag+kalman filter...Now with the data i extract from sensors (6DOF,3 for ACC, and 3 for MAG), I can get the RotationMatrix after calling the Android API. Then i have the rotation angle from world coordinate to camera coordinate.Also I can get the intrinsic parameters of camera through calibration, such as focal length, distortion coefficients...
So my question is : is it a right way to calculate the offset between two frames using the sensor data i got before, combining the angle and intrinsic parameters of camera?
any one has tried this out before?
REF: Tsai Camera Calibration
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602114",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Network Photo Application cache (Nimbus) In the Network Photo application sample from Nimbus, when I return to the table (to choose from where I want to download photos beging Facebook or Dribbble), the previous photos I saw and were in cache, are cleared from it. Is there a way to prevent this?
For instance:
*
*I enter in the album A, I downloaded 50 photos to cache.
*I enter in the album B, I downloaded 50/60 photos.
*When I re-enter the album A, I want to use the ones I have in cache.
My scenario is: Multiple Projects (Data Sources), when I go from one to another, if I have been there already, I want it to use my internal cache.
Most important: Is it possible to save it for the iPhone's internal memory?
Thanks.
A: The photos are being removed from memory when you leave the photo controller because it is the photo controller that instantiates the image caches for the photos. If you would like to keep the photos in memory beyond the existence of the photo controller then you will need to create some form of a global image in-memory cache within which you store the photos.
As for whether you can save the photos to disk, I believe that the examples use ASIHTTPRequest which uses a disk cache for the images. This will automatically cache images to disk so that even if they are removed from memory they won't be downloaded from the network again. This can still cause the images to take a second to load because loading large photos from disk isn't as fast as using them from an in-memory cache.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Parse Last.Fm XML from API in Java URL: http://ws.audioscrobbler.com/2.0/?method=chart.gethypedtracks&api_key=1732077d6772048ccc671c754061cb18&limit=10
From the above url I need to somehow remove the Artist name and the track name from the XML file produced from each Song given but I have no Idea how to work with an XML file structured in this way ??
Any help or pointers would be very much appreciated !
Thanks,
Ross
A: Here's a fully working class that loads the URL you have indicated and parses the Track and artist names.
Basically it reads the xml into a Document, and runs 2 xpath queries in loops to get the data you want.
The document itself is simple xml, if you reformat it, it looks like:
<?xml version="1.0" encoding="utf-8"?>
<lfm status="ok">
<tracks page="1" perPage="10" totalPages="50" total="500">
<track>
<name>Hysterical</name>
<duration>231</duration>
<percentagechange>3626</percentagechange>
<mbid/>
<url>http://www.last.fm/music/Clap+Your+Hands+Say+Yeah/_/Hysterical</url>
<streamable fulltrack="0">0</streamable>
<artist>
<name>Clap Your Hands Say Yeah</name>
...
All I did to clean it up was run it through a re-formatter like xmlstarlet as I mentioned in my comment. Note: you don't have to reformat it for java to read it if it's well formed. Human readable is all a re-format does for you.
The first xpath query gets the track name using a path lfm/tracks/track/name. You can use something like this xpath tester to try out your xpath queries (you can paste your xml in and it will reformat it too). If you don't understand xpath, there are many sources on the net.
The second xpath works relative to the current track name node, and looks for a following-sibling node of type artist with a name sub-node, and then displays the text of the node.
Here's the code
package net.fish;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class ParseXML {
private static final DocumentBuilderFactory DOCUMENT_BUILDER_FACTORY = DocumentBuilderFactory.newInstance();
private static final XPathFactory XPATH_FACTORY = XPathFactory.newInstance();
public static void main(String[] args) throws Exception {
new ParseXML().parseXml("http://ws.audioscrobbler.com/2.0/?method=chart.gethypedtracks&api_key=1732077d6772048ccc671c754061cb18&limit=10");
}
private void parseXml(String urlPath) throws Exception {
URL url = new URL(urlPath);
URLConnection connection = url.openConnection();
DocumentBuilder db = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder();
final Document document = db.parse(connection.getInputStream());
XPath xPathEvaluator = XPATH_FACTORY.newXPath();
XPathExpression nameExpr = xPathEvaluator.compile("lfm/tracks/track/name");
NodeList trackNameNodes = (NodeList) nameExpr.evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < trackNameNodes.getLength(); i++) {
Node trackNameNode = trackNameNodes.item(i);
System.out.println(String.format("Track Name: %s" , trackNameNode.getTextContent()));
XPathExpression artistNameExpr = xPathEvaluator.compile("following-sibling::artist/name");
NodeList artistNameNodes = (NodeList) artistNameExpr.evaluate(trackNameNode, XPathConstants.NODESET);
for (int j=0; j < artistNameNodes.getLength(); j++) {
System.out.println(String.format(" - Artist Name: %s", artistNameNodes.item(j).getTextContent()));
}
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602119",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: sending keyboard interrupt programmatically An application that asks for a keyboard interrupt. How can I send for a keyboard interrupt programmatically? I need it for automation.
Like <C-c> or <C-x>
KeyboardInterrupt
A: Code running in a separate thread can cause a KeyboardInterrupt to be generated in the main thread by calling thread.interrupt_main().
See https://docs.python.org/2/library/thread.html#thread.interrupt_main
A: Since you mention automation I assume you want a SendKeys for Python. Try this: http://rutherfurd.net/python/sendkeys/
A: My suggestion to solve this problem is to use the following code pattern. I used it to programmatically start a tensorboard server and shut it down by sending a CTRL-C when the object it belongs to is deleted. Generally speaking, this should work for any example that provokes a subprocess that is supposed to be send a KeyBoardInterrupt:
*
*Import signal and subprocess
import signal
import subprocess
*Create the subprocess using subprocess.Popen. Important: set the creationflags parameter to subprocess.CREATE_NEW_PROCESS_GROUP. This is necessary to later be able to send the KeyboardInterrupt event.
command= <enter your command that is supposed to be run in different process as a string>
process = subprocess.Popen(command.split(),stdout=subprocess.PIPE,stdin=subprocess.PIPE,creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
*Wherever you want to send the keyboardInterrupt, do the following:
process.send_signal(signal.CTRL_C_EVENT)
That is it! Please see the the official subprocess documentation for insights on why the creationflags parameter of popen has to be set that way.
This is how the code looks for my example in a less generic way:
import signal
import subprocess
import time
class ExperimentTracker():
def __init__(self):
self.tensorboard_process=None
def __del__(self):
#shutdown tensorboard server and terminate process
self.tensorboard_process.send_signal(signal.CTRL_C_EVENT)
time.sleep(0.2)
self.tensorboard_process.kill()
def launch_tensorboard(self):
#launch tensorboard
bashCommand= "tensorboard --logdir runs"
self.tensorboard_process = subprocess.Popen(bashCommand.split(),stdout=subprocess.PIPE,stdin=subprocess.PIPE,creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
time.sleep(2) #sleep for 2 seconds to give tensorboard time to be launched
A: If say you want to run a program via shell ./program. In Linux what you could do is:
# Made a function to handle more complex programs which require multiple inputs.
run(){
./program
}
# Making a child process that will run the program while you stop it later.
run &
childPid=($!)
# Process id of the program which you want to interrupt (via `run`).
# Time after which you want to interrupt
sleep 5
# Actual command to send the interrupt
kill -SIGINT $childPid
Let me know if it works in windows as well.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602120",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Android dev: PhoneLookup._ID, Phone.CONTACT_ID, ContactsContract.Contacts._ID all the same? Do they all refer to the same unique contactId of a contact person?
A: They should, but it's not guaranteed if the contacts are synced or aggregated.
You might want to try using LOOKUP_KEY instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to get the tag of a shape when clicked Lets say I have created a canvas in a Tkinter app.
In the canvas, I have drawn several rectangles.
What I want in essence, is to know in which rectangle the user has clicked, that is my main concern, but this is what I have tried and what I think might be the solution.
This is my layout:
for x in range(1,6):
for y in range(1,7):
tableNumber = y + 6*(x-1)
w.create_rectangle((table.xSeparation + table.width) * y - table.width,
(table.ySeparation + table.height) * x - table.height,
(table.xSeparation + table.width)*y,
(table.ySeparation + table.height) * x,
fill="brown", tags="table" + str(tableNumber))
w.tag_bind("table" + str(tableNumber), '<Button-1>', do)
So this just creates rectangles in a rows and columns layout.
Each rectangle has a specific tag in the form of table1,table2 to table30.
When I click on the rectangle, the do function executes.
Let's say do was something like:
def do(event):
print "click"
Not I get a "click" in the console for every click in the rectangle.
I would like to be able to get the tag of the clicked rectangle to be able to do something like this:
def do(event):
print str(theTagOfTheClickedRectangle)
So I checked on what events I can call which are:
*
*widget
*x, y
*x_root, y_root
*char
*keysym
*keycode
*num
*width, height
*type
None of the seem to pin point what rectangle I have clicked.
I thought about adding more parameters to the do function here:
w.tag_bind("table" + str(tableNumber), '<Button-1>', do(event, tag))
But that doesn't seem to work fine, but maybe I'm not doing the do right:
do(event, tag): #this doesn't work at all!!
print event.x
print tag
I hope the question is clear, if I got the tag in the same manner as I can get the 'x' and 'y' of the event, that would be very comfortable.
The only actual solution I can now think of, is working out the math of 'event.x' and 'event.y' and calculate, based on the coordinates of the click, on which rectangle the user has clicked, this seems overcomplicated for what I'm trying to do, though I've done it before and it obviously works.
I hope the question is clear, other wise please ask for any clarification.
Note that I'm not tied to any of this code, rather, I'm looking for a solution for this problem, the most efficient will work even if means not working with tags, or another type of widget or whatever is the easier.
A: You can use something like this to reference the clicked-on object:
event.widget.find_withtag("current")
The tag "current" is special and represents the top-most object under the mouse.
A: w.tag_bind("table" + str(tableNumber), '<Button-1>', do(event, tag))
should be changed to
tag = "table" + str(tableNumber)
callback = lambda event, tag=tag: do(event, tag)
w.tag_bind(tag, '<Button-1>', callback)
The lambda creates a function with the tag name as the default value of the second argument. Tkinter calls that function with just one argument, the event, and the second argument uses the default value.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602122",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Show existing activity from AppWidget click I have a problem opening an activity from an appwidget. I have tried different Intent flags, PendingIntent and launch modes without any luck. I have read diffent examples here and many other places without finding the solution.
Right now when I click my button on my appwidget it opens a new activity instead of showing the instance which already exists in the app. I have posted my code below and hope you can help me.
Is there a way to find the existing activity and show it instead of creating a new one when clicking my bottom on the appwidget?
Manifest:
<application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true" android:name="widget.helper.ResourceHelper">
<activity android:name=".ScoreBoard"
android:label="@string/app_name"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Broadcast Receiver that will process AppWidget updates -->
<receiver android:name="Widget" android:label="@string/app_name">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data android:name="android.appwidget.provider" android:resource="@xml/widget_provider" />
</receiver>
</application>
The AppWidget:
public class Widget extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
RemoteViews remoteViews;
ComponentName thisWidget;
remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
thisWidget = new ComponentName(context, Widget.class);
appWidgetManager.updateAppWidget(thisWidget, remoteViews);
}
@Override
public void onReceive(Context context, Intent intent)
{
super.onReceive(context, intent);
if(intent.getAction().equals("OPEN_APP")) {
Intent i = new Intent(Intent.ACTION_MAIN);
i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setComponent(new ComponentName("widget","widget.ScoreBoard"));
ResourceHelper.getScoreBoard().startActivity(i);
}
}
}
A: Use either FLAG_ACTIVITY_REORDER_TO_FRONT or the combination of FLAG_ACTIVITY_CLEAR_TOP and FLAG_ACTIVITY_SINGLE_TOP. FLAG_ACTIVITY_CLEAR_TOP without FLAG_ACTIVITY_SINGLE_TOP would not work, AFAIK.
A: set the activity launchMode to singleInstance in manifest.
Let us know if it is working.
Saneesh
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Need Suggestions for ASP.Net or IIS Request URL Mangling Environment:
*
*Server 2008
*IIS 7, integrated mode
*.Net 4
*ASP.NET WebForms Routing (which uses the same .dll as MVC routing, though I'm not sure which version)
*Cookieless sessions (session ID travels around on the user's URL).
We have an application that uses routing to identify which organization a user is associated with. The URL will take the form domain/Organization/OrganizationSubCategory. The user follows their custom URL and sees a landing page. When they hit next, they are directed to a page that collects some demographic info, then they hit next to proceed to the application. When they do, the user is added (if necessary) to their organization in our database. After the initial landing page, routing no longer applies - the user is directed to regular aspx pages.
The site is receiving a fair amount of users entering the app; an average of 850 per day.
The problem is that a small number (less than 1%) of users are getting added to the wrong organization.
We are logging information on the landing page and when they submit the demographic page. One thing we log is Request.RawUrl. We started noticing users who are associated with one organization being logged as having requested the full correct URL (including the sub-category) of another organization. Sometimes nobody legitimately came in following the incorrect organization URL even in the same day. We've had people report directly that they just created the "sub category" (using an administrative application), instructed a user to follow their unique URL, and yet the logs show an entirely different URL for that very user (I know it's that user because I'm logging email address and session ID so I can associate the same user's path through the landing page and the demographic page). It's as if IIS is sometimes creating a new session, and simply assigning some previously requested URL to that user.
In an attempt to eliminate some sort of caching, we have:
*
*Set the config httpRuntime element's enableKernelOutputCache attribute to false
*Disabled caching in IIS settings
*Set the config sessionState element's regenerateExpiredSessionId attribute to false (even though we haven't seen the session ids being re-used).
Other suggestions?
A: Are these internal users? Are there proxy considerations? That wouldn't explain a wrong url though. Are you 100% certain the users were given url A and they show up with URL b? Do you have any routing modules currently assigned? Are you sure its not getting rewritten by a rule in another module?
Could this be an application issue where their 'new user' email (for ex) contains the wrong url?
A: Well, we still don't know with complete confidence, but it seems that users in one organization were most likely searching the Internet to find URLs into the system and following those.
I can't explain the report we had as I described in the original post.
When I tried to enhance logging to capture pre-post session creation to prove it for sure, the logging on the begin request event worked in our QA environment (same as production), but just flat wouldn't work in production. I could never determine why.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602131",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JQuery - What method can I use to get this code to run without clicking Ok this example code contains a button. Forget about the button, it does not exist, cannot be referenced and cannot be edited.
The buttons dont exist in this example - they merely represent another process. However the fields still need to be updated from values. Sorry I couldn't explain it better.
Answer:
http://jsfiddle.net/piezack/X8D4M/56/
A: If you want the event to fire whenever the text inside the box changes, then I think you're best off using jquery's keyup event instead of blur:
$('#FormCustomObject6Name').keyup(
function()
{
var x = $('#FormCustomObject6Id').val();
$("a[href*='http://www.msn.com']").attr('href',('http://www.google.com/search?q='+ x));
$('a#link').text('Link has been updated');
}
);
The only problem with this is that it won't catch instances where users enter data without using their keyboard (paste via right click, etc.).
A: You could use a mouseover event, say over the button or the link.
I changed this
$('.butter').mouseover(function(){
to have a mouseover the button.
Example: http://jsfiddle.net/X8D4M/39/
A: You can trigger events on objects yourself manually by using trigger(event).
So this might work for you:
$('button.butter').trigger('click');
A: Did you try just triggering a click?
$('button.butter').click();
A: Here's what you're looking for.
$('#FormCustomObject6Name').trigger('blur');
A: Okay, this is probably not the most efficient solution, but if you use setInterval to check for the changed value you're guaranteed to cover all sources of the change.
setInterval(function(){
var id = $('#FormCustomObject6Id').val();
var name = x + $('#FormCustomObject6Name').val();
if (id.length > 0 && name.length > 0){
$("a[href*='http://www.msn.com']").attr('href',('http://www.google.com/search?q='+ id));
$('a#link').text('Link has been updated');
}
},500);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Enhanced auth dialog on iOS doesn't complete login flow I have an iOS app that uses the Facebook SDK for authorization. The existing app does not ask for manage_actions permission. I'm using fairly standard code to start the login flow:
NSArray permissions = [NSArray arrayWithObjects: @"email", @"publish_stream", @"user_education_history", @"rsvp_event",@"user_events,user_interests", nil];
[self.model.facebook authorize:permissions];
When I enable the enhanced auth dialog in the FBDev App and then try to sign into my app, I see a new mobile auth dialog prompting me to Add to Timeline. However, clicking the button on this screen does nothing. It doesn't show an error and doesn't return to my app.
Are there any known issues or workarounds for this flow using the new auth dialog?
(Saw this on an iPad with iOS 4.3)
Thanks,
Edit: One more detail, I saw this using the Facebook app for sign in, I haven't tried it using Safari.
A: This may have been caused because I didn't have the Bundle ID set through the DevApp.
After setting the iOS Bundle ID in the Settings -> Basic -> Native iOS App section of the DevApp, I have stopped being blocked by the Enhanced Auth Dialog.
A: In Facebook.m you have this method: - (void)authorizeWithFBAppAuth:(BOOL)tryFBAppAuth safariAuth:(BOOL)trySafariAuth. You can try setting both tryFBAuth and trySafariAuth to NO at the beginning of the method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: why do I need to set style in js initially rather than use existing style? I'm learning how to drag-and-drop-move DIV's around the document in javascript. Here is a live demo:
http://jsfiddle.net/BBANc/
This works fine in Firefox and I'm not currently developing with any other browser. However, if you change set_coords_in_js to false, the demo fails.
Using Firebug to set some breakpoints, you'll notice that this line fails:
var div_left = parseInt( mov_div_1.style.left, 10 );
There is no value for mov_div_1.style.left at this point. So javascript has no idea what the existing value is, and sets div_left to 'NaN'. This style is set, and appears to be valid in the document, but there is no value in the DOM!
If you set set_coords_in_js back to true, then the above has a value and everything works perfectly as it should.
Why?
If you want to play with this locally, copy-and-paste this into your local demo file. To see the values (or lack thereof) in Firebug, set your breakpoint on line 39 or 40 and step through, hovering your mouse over the things in the line. Make sure you set set_coords_in_js to false to see the problem.
drag_move_div.html:
<!DOCTYPE html>
<html>
<head>
<title>drag move div demo</title>
<style type='text/css'>
.movDiv {
position: absolute;
left: 80px;
top: 80px;
cursor: move;
border: 1px dashed green;
padding: 1em;
}
.coordinates_display { font-weight: bold; }
</style>
<script type='text/javascript'>
window.onload = function() {
mov_div_1 = document.getElementById('mov_div_1');
set_coords_in_js = true;
function update_coordinates( newX, newY ) {
document.getElementById('coordinate_x').innerHTML = newX;
document.getElementById('coordinate_y').innerHTML = newY;
}
// why do I need to set these here in javascript when they are set in css?
if( set_coords_in_js ) {
mov_div_1.style.left = '80px';
mov_div_1.style.top = '80px';
}
update_coordinates( mov_div_1.style.left, mov_div_1.style.top );
mov_div_1.onmousedown = function(e){
mov_div_1.style.backgroundColor = 'black';
mov_div_1.style.color = 'white';
var div_left = parseInt( mov_div_1.style.left, 10 );
var div_top = parseInt( mov_div_1.style.top, 10 );
var startX = e.clientX;
var startY = e.clientY;
mov_div_1.onmousemove = function(e){
var newX = ( div_left + e.clientX - startX );
var newY = ( div_top + e.clientY - startY );
mov_div_1.style.left = newX + 'px';
mov_div_1.style.top = newY + 'px';
update_coordinates( mov_div_1.style.left, mov_div_1.style.top );
};
};
mov_div_1.onmouseup = function(){
mov_div_1.onmousemove = null;
mov_div_1.style.backgroundColor = '';
mov_div_1.style.color = '';
};
};
</script>
</head>
<body>
<div class='movDiv' id='mov_div_1'>[ Click & Drag Me Around (slowly) ]</div>
<p>Coordinates:
<span id='coordinate_x' class='coordinates_display'></span> x
<span id='coordinate_y' class='coordinates_display'></span></p>
</body>
</html>
A: See this related question. When you access element.style, you're not accessing the computed style (which includes stylesheet declarations), you're accessing the "style" attribute on the element itself. So when you try to get a value from mov_div_1.style, no style attribute is available, and it will come back as an empty string.
To fix this, you need to use either element.currentStyle (older IE versions, I think) or element.getComputedStyle() (modern browsers):
var computedStyle = mov_div_1.currentStyle || getComputedStyle(mov_div_1);
var div_left = parseInt( computedStyle.left, 10 );
var div_top = parseInt( computedStyle.top, 10 );
See the working jsFiddle here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: phpmysql update set while uploading image I am really struggling trying to get something very simple achieved.
Essentially, I have an images table called galleryimages and a location on the server where images are stored. What I am trying to do is overwrite the source field for a given category in the table while the upload is going through.
My code will add the new image to the server, but not update the MySQL table for some reason (I can however add new lines to it although I want to keep the existing data in the table and simply change the "photo" field which locates the image).
My PHP is:
<?php include 'dbc.php'; page_protect();
if(!checkAdmin()) {header("Location: login.php");
exit();
}
$host = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$login_path = @ereg_replace('admin','',dirname($_SERVER['PHP_SELF']));
$path = rtrim($login_path, '/\\');
foreach($_GET as $key => $value) {
$get[$key] = filter($value);
}
foreach($_POST as $key => $value) {
$post[$key] = filter($value);
}
?>
<?php
if($_FILES['photo'])
{
$target = "galleries/test/";
$target = $target . basename( $_FILES['photo']['name']);
$title = mysql_real_escape_string($_POST['title']);
$pic = "galleries/test/" .(mysql_real_escape_string($_FILES['photo']['name']));
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
mysql_query("update `galleryimages` set (`title`, `photo`) VALUES ('$title', '$pic')") ;
echo "Success";
}
else
{
echo "Failure";
}
}
?>
And the HTML is:
```html
</head>
<body>
<form enctype="multipart/form-data" action="addgallery1.php" method="POST">
<table width="100%" border="2" cellpadding="5"class="myaccount">
<tr>
<td>Category: </td>
<td><select name="title" id="select8">
<option value="Landscape Pots">Landscape Pots</option>
</select></td>
</tr>
<tr>
<td>Image: </td>
<td><input type="file" name="photo" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" class="CMSbutton" value="Add" /></td>
</tr>
</table>
</form>
</body>
</html>
Now I am fairly sure the problem exists in the line:
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
mysql_query("update `galleryimages` set (`title`, `photo`) VALUES ('$title', '$pic')") ;
echo "Success";
}
but need some help to determine if this is indeed the case - and if so how I can get it to update the MySQL table - at the moment the PHP echoes Success but does not make any update to the "photo" column in MySQL.
Hope this makes sense and one of you coding geniuses can help me resolve this - its taken me hours of trial and error but still cant get it working!!!
thanks in advance to any and all help
JD
A: some thing wrong here
mysql_query("update `galleryimages` set (`title`, `photo`) VALUES ('$title', '$pic')") ;
it should be like
mysql_query("update `galleryimages` set `title`='$title', `photo`= '$pic'") ;
more info here: http://dev.mysql.com/doc/refman/5.0/en/update.html
A: Your MySQL query is wrong:
update `galleryimages` set `title`='$title', `photo`='$pic'
But be warned: This will update ALL rows in this table! You should add a WHERE clause to update one specific row.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602141",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Spork, RSpec and database_cleaner destroying development database I have the following spec_helper.rb file in my Rails 3.1 application. I am using Spork to load the environment faster for testing. All my tests worked prior to adding Spork to the mix. After adding spork, the test database was not getting properly cleared between test runs which threw off some of my expectations.
Following other instructions, I added database_cleaner to the mix with the code listed below; however, now, the development database is getting cleaned up as well as the test database. The ENV["RAILS_ENV"] call is returning test during this call.
Is there a way to explicitly limit the call for DatabaseCleaner.clean_with(:truncation) to only affect the test database?
require 'rubygems'
require 'spork'
Spork.prefork do
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'shoulda/matchers/integrations/rspec'
require 'database_cleaner'
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
config.mock_with :mocha
config.formatter = 'documentation'
config.use_transactional_fixtures = true
config.before(:suite) do
DatabaseCleaner.strategy = :truncation
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
end
end
Spork.each_run do
FactoryGirl.reload
end
Update: Here is my database.yml file
development:
adapter: sqlite3
database: db/development.sqlite3
pool: 5
timeout: 5000
test:
adapter: sqlite3
database: db/test.sqlite3
pool: 5
timeout: 5000
production:
adapter: sqlite3
database: db/production.sqlite3
pool: 5
timeout: 5000
Also, I have worked around the basic problem by moving the clean_with call into the before(:each) section, but this slows down the test runs significantly.
A: Have you tried to move ENV["RAILS_ENV"] ||= 'test' out of the Spork.prefork block?
Are you sure that Spork caused your DB got uncleaned? If you're using RSpec's transactional fixtures, the only thing that could lead to such thing is using factories within before(:all) block. You can clean up data in after(:all) block and get rid of DatabaseCleaner.
BTW, if you're using truncation strategy, there's no need to run DatabaseCleaner.start.
A: Is your RAILS_ENV explicitly set to "development"? If so, the default spec_helper will run the tests against the development DB. If you run a test from inside vim, or run rspec on the command-line, then it'll run the test against your development DB.
When I'm forced to use database_cleaner, I like to explicitly set RAILS_ENV to test in spec_helper to protect my development DB. Any time you're using something other than transactional fixtures, this is probably a good idea.
I note that you're using both transactional fixtures and database_cleaner. You don't need database_cleaner at all if your DB supports transactions. If you're using Mongo, or you are running capybara-webkit tests, then you'll need database_cleaner, and will want to disable transactional fixtures.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: How can I detect changes in zoom level? Open this page on Chrome or Safari and fiddle with the zoom level. You'll notice a cute easing effect on its elements when you change the zoom level.
Apparently this only works on Chrome and Safari (webkit?), but how is this done? And is there a cross-browser way to do this?
A: I figured it out. JavaScript is not involved, it's pure CSS.
Namely, webkit's -webkit-transition property:
/* css */
.box {
background: #5599ff; text-align: center;
line-height: 80px; height: 80px; width: 100px;
font-family: arial, helvetica; color: #FFF;
-webkit-border-radius:3px; margin: 10px }
.trans {
-webkit-transition:all .218s; }
<!-- html -->
<div class="box"> STIFF </div>
<div class="box trans"> FLUID </div>
EDIT: Upon further research, I found out most browsers (ie: everything but IE) support a vendor specific transition CSS property. However, only webkit browsers use transitions when the page is resized.
See demo on jsfiddle
A: I dont think there is any (cross-browser) direct way of listening to page zoom event. There are some backdoors described on Catch browser's "zoom" event in JavaScript . however I think you can listen to Ctrl + + / - OR Ctrl+Mouse Wheel Event.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602145",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Confused -> Silverlight 4 not allowing me to consume a WCF service using BasicHttpBinding? OK I am totally confused and hopefully I am missing something here totally obvious. I am consuming a WCF service of mine (which is stable and working in ASP.NET) hosted in a Windows Service which uses a 'BasicHttpBinding' configuration. When I try to consume it from a Silverlight 4 application I get the following error in VS.NET:
*"Custom tool warning: Endpoint 'BasicHttpBinding_IMyService' at address 'https://mywcfservice:8000/WCFServices/MyService' is not compatible with Silverlight 4. Skipping... MyService\Reference.svcmap"*
What!? I know and have gone through the hoops to jump through for making a netTCPBinding which has issues get past the error above in SL4, but why in the world is BasicHttpBinding having any issue with SL4? I thought since like day 1 of SL2 BasicHttpBinding was the defacto and easiest binding for Silverlight to consume. Here is my WCF server configuration:
<service behaviorConfiguration="ServiceBehavior" name="MyService">
<endpoint address="" binding="basicHttpBinding"
bindingConfiguration="BasicHttpWindowsBinding"
contract="IMyService"/>
<endpoint address="mex"
binding="mexHttpsBinding"
contract="IMetadataExchange"/>
<host>
<baseAddresses>
<add baseAddress="https://mywcfservice:8000/WCFServices/MyService"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceDebug includeExceptionDetailInFaults="false"/>
<serviceMetadata httpsGetEnabled="true" httpGetEnabled="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpWindowsBinding"
maxReceivedMessageSize="214748"
messageEncoding="Mtom"
transferMode="Streamed">
<security mode="Transport">
<transport clientCredentialType="None"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
What am I missing here? If anyone can help me or guide what might be incoorect please let me know. Thanks!
Edit: I think I might be on the trail - this service uses a 'Message Contract' as a parameter in a method and I wonder if this is causing any issues. However from this MSDN article: "Message contracts are supported in Silverlight 4" http://msdn.microsoft.com/en-us/library/cc896571(v=vs.95).aspx so I am still not 100% sure. I check 'Always generate message contracts' when consuming but it made no difference.
A: There are a few special attributes/values you use in your configuration file:
The BasicHttpWindowsBinding has transferMode and messageEncoding set to non default values.
According to WCF service for Sl3, which registered similar problems, you should do the following:
messageEncoding="Mtom"
Try: messageEncoding="Text" instead.
or transferMode="StreamedResponse"
Try: transferMode="Buffered" instead.
If you try these steps, you will probably get a running situation and can build in specifics from that point on, making sure it keeps working for the SL-WCF connection.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Layout hierarchical issue in an Access report I've been struggling the last hours on the following problem, I hope somebody will have an idea... This is a problem of report layout in Access.
Here is a simplification of my data model: A is the "father" of one or more B that is the father of one or more C.
What is really easy to display in the report is the following:
A
B1
B2
C2.1
C2.2
C2.3
B3
C3.1
etc where B1, B2, B3 are the children of A and C2.1 etc... the children of B2.
Another easy thing to display is ONLY the grand children of A: in the report design mode, I just have to remove the reference to B (but I keep it in the query, of course, to maintain the relation between A and C), I will obtain the following:
A
C2.1
C2.2
C2.3
C3.1
Now, what I don't manage to perform is to display for each A, at first, all his children, and then, all his grand children. In our simplification, it would mean to display the following in the same report:
A
B1
B2
B3
C2.1
C2.2
C2.3
C3.1
The classical layout of my report is that A objects are in group header A, B objects in group header B and C objects in group header C. To obtain this new layout, I have tried to move my B object from the group header B to the group header A, but when I do that, it displays only:
A
B1
C2.1
C2.2
C2.3
C3.1
How can I display ALL B's that are related to A ?
Thank you for your help...
A: Try this:
*
*Create a new report.
*Group this report by A, then B
*In the Report Footer, create a subreport.
*Group this subreport by A, then C.
This will give you:
A
B1
B2
B3
A
C2.1
C2.2
C2.3
C3.1
(I'm curious, why display this hierarchy in such a non-hierarchical style? A school project?)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602147",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Probability distribution values plot I have
probability values: 0.06,0.06,0.1,0.08,0.12,0.16,0.14,0.14,0.08,0.02,0.04 ,summing up to 1
the corresponding intervals where a stochastic variable may take its value with the corresponding probability from the above list:
126,162,233,304,375,446,517,588,659,730,801,839
How can I plot the probability distribution?
On the x axis, the interval values, between the intervals histogram with the probability value?
Thanks.
A: How about
x <- c(126,162,233,304,375,446,517,588,659,730,801,839)
p <- c(0.06,0.06,0.1,0.08,0.12,0.16,0.14,0.14,0.08,0.02,0.04)
plot(x,c(p,0),type="s")
lines(x,c(0,p),type="S")
rect(x[-1],0,x[-length(x)],p,col="lightblue")
for a quick answer? (With the rect included you might not need the lines call and might be able to change it to plot(x,p,type="n"). As usual I would recommend par(bty="l",lty=1) for my preferred graphical defaults ...)
(Explanation: "s" and "S" are two different stair-step types (see Details in ?plot): I used them both to get both the left and right boundaries of the distribution.)
edit: In your comments you say "(it) doesn't look like a histogram". It's not quite clear what you want. I added rectangles in the example above -- maybe that does it? Or you could do
b <- barplot(p,width=diff(x),space=0)
but getting the x-axis labels right is a pain.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: WIF - Federated Provider with multiple Identity Providers - store IP info in db? So despite the warnings, I think I need to build a custom STS. We will support an arbitrary number of customers who provide identity information via SAML.
What is the best practice to store details on each IP? Most examples seem to store this info in the STS's web.config. That seems like it wouldn't scale real well.
Is there an obvious reason not to just store this stuff in a db and load it when the requests come in?
A: Fundamentally, if the Identity Providers will change over time, such as via some online administration function, rather than a new application deployment, it makes total sense to store the information in a database (or other Storage).
I think this is a potential issue for any multi-tenanted service that is federating identity with the customer.
A: ADFS v2.0 (which is Microsoft's STS product) stores its details in either a SQL Server DB (or SQL Server DB farm) or a Windows Internal DB. So if it's good enough for Microsoft ...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Opening multiple types quickly with ReSharper There is an 'open type' feature that supports wild card searching, and it would be very convenient to be able to open several in the list at once rather than running the same command n times in order to get the desired behavior. I need something better than using the solution explorer given that the types I'm searching for could be scattered across many projects/folders.
Is there a way to achieve this using Visual Studio 2010 and ReSharper (or other tools, if its impossible given my dev environment)?
A: You could use the little icon on the upper right and move the results to the "Show in Find Results" and then go from there.
Edit: Ctrl+Shift+T > Type Name > Numeric pad +
This is using Resharper
A: The Solution Navigator tab from Productivity Power Tools can do this. Type something in the search box to narrow the display, and then multi-select, right-click, "Open" the things you're interested in. The search isn't as good as ReSharper's (it doesn't understand CamelCase, for example), but it works.
A: How about using Visual Studio's built-in macro recording/scripting/playback functionality to repeat the command?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Rails 3 + Omniauth. When a user clicks "Don't Allow" for FB, how can I customize the response Right now if a user clicks "Don't Allow" the popup window goes back to the site with the error message: "Could not authorize you from Facebook because "The user denied your request."
Any ideas on how I can handle this failure in my auth controller so I can close the dialog?
A: i think you need to redirect the user if the authentication fail so add this to your routes :
match 'auth/failure', to: redirect('/')
you can look at my example app here : https://github.com/senayar/facebook_connect
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: bpython-like autocomplete and parameter description in Emacs Python Mode? I've been using bpython for a while now for all of my Python interpreting needs. It's delightful, particularly when you're using unfamiliar new libraries, or libraries with a multitude of functions. In any case, it's nice to have a bpython interpreter running alongside what I'm doing, but it'd be even better if I had both the autocomplete-like feature, and the parameter description in the manner that bpython does while I'm editing code in Emacs. Am I completely crazy? Does anyone have an idea on how to do this?
Thanks,
Bradley Powers
A: You're not completely crazy.
python-mode can integrate with eldoc-mode to display the arg spec of the function you're calling at point. Just do M-x eldoc-mode while you're in a python file to turn it on and it should start working. It talks to an inferior python buffer to inspect the functions directly, so it should always be decently accurate. You can turn it on automatically for all new python-mode buffers with (add-hook 'python-mode-hook '(lambda () (eldoc-mode 1)) t) in your emacs startup file. Now, at this point I have to say that I don't do any regular python programming, and that when I tried it just now it didn't work. I spent a few minutes poking around in the source code and everything seems to be in place, but the code that it runs in the inferior process is just returning an empty string. Perhaps it's just my setup, or perhaps I'm reading the wrong source files; it's hard to say.
Emacs provides several different types of expansion/autocompletion. By default you have access to dabbrev-expand by hitting M-/. This is a fairly simple form of completion; it's just meant to work on any old file you happen to edit. More sophisticated is hippie-expand, but even that doesn't do anything python-specific. The documentation says that it can integrate with hippie-expand for exact completions, but this might be a lie; I couldn't figure out how it works. A little poking around shows several related solutions for this, all of which seem to rely on pymacs. If I were going to do a lot of python programming and didn't already have a fairly complicated emacs set up, I'd probably start by installing emacs-for-python. It looks to be a pretty complete setup, and even claims to have live warning/error detection.
In the spirit of helping others to help themselves, I'd like to point out how I came upon all of this information. My first step was to open a file in python-mode. I didn't actually have any python code available, so I just went to my scratch buffer and made it a python buffer (M-x python-mode). Then I asked for help about this strange new mode (C-h m) to see what it could do. It's author has kindly put a brief summary of what the mode can do which mentions eldoc-mode, Imenu, outline-mode, hippie-expand, rlcompleter, abbrev tables, and a bunch of other things. From there I started looking at the source code. For instance, to integrate with eldoc-mode, it defines a function called python-eldoc-function and gives that to the eldoc module for use in python buffers. Reading that code shows me how it interacts with the inferior buffer, etc.
I hope some of this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602169",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Getting current again with TextMate (bundles, tutorials) What would be the best way to get my TextMate bundles all up to date and learn all those great keyboard shortcuts that speed development? (especially rails, html, jquery, blogging)
I have circa 2008 textmate books; looking for up to date tutorials, bundles etc.
A: There is a similar question 3 questions below.
In short: whatever tutorials/books/resources you had in 2008 still apply because TextMate hasn't evolved since then and the right way to have up to date bundles is to use the GetBundles bundle.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: (unicode error) 'unicodeescape' codec can't decode bytes - string with '\u' Writing my code for Python 2.6, but with Python 3 in mind, I thought it was a good idea to put
from __future__ import unicode_literals
at the top of some modules. In other words, I am asking for troubles (to avoid them in the future), but I might be missing some important knowledge here. I want to be able to pass a string representing a filepath and instantiate an object as simple as
MyObject('H:\unittests')
In Python 2.6, this works just fine, no need to use double backslashes or a raw string, even for a directory starting with '\u..', which is exactly what I want. In the __init__ method I make sure all single \ occurences are interpreted as '\\', including those before special characters as in \a, \b, \f,\n, \r, \t and \v (only \x remains a problem). Also decoding the given string into unicode using (local) encoding works as expected.
Preparing for Python 3.x, simulating my actual problem in an editor (starting with a clean console in Python 2.6), the following happens:
>>> '\u'
'\\u'
>>> r'\u'
'\\u'
(OK until here: '\u' is encoded by the console using the local encoding)
>>> from __future__ import unicode_literals
>>> '\u'
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: end of string in escape sequence
In other words, the (unicode) string is not interpreted as unicode at all, nor does it get decoded automatically with the local encoding. Even so for a raw string:
>>> r'\u'
SyntaxError: (unicode error) 'rawunicodeescape' codec can't decode bytes in position 0-1: truncated \uXXXX
same for u'\u':
>>> u'\u'
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: end of string in escape sequence
Also, I would expect isinstance(str(''), unicode) to return True (which it does not), because importing unicode_literals should make all string-types unicode. (edit:) Because in Python 3, all strings are sequences of Unicode characters, I would expect str('')) to return such a unicode-string, and type(str('')) to be both <type 'unicode'>, and <type 'str'> (because all strings are unicode) but also realise that <type 'unicode'> is not <type 'str'>. Confusion all around...
Questions
*
*how can I best pass strings containing '\u'? (without writing '\\u')
*does from __future__ import unicode_literals really implement all Python 3. related unicode changes so that I get a complete Python 3 string environment?
edit:
In Python 3, <type 'str'> is a Unicode object and <type 'unicode'> simply does not exist. In my case I want to write code for Python 2(.6) that will work in Python 3. But when I import unicode_literals, I cannot check if a string is of <type 'unicode'> because:
*
*I assume unicode is not part of the namespace
*if unicode is part of the namespace, a literal of <type 'str'> is still unicode when it is created in the same module
*type(mystring) will always return <type 'str'> for unicode literals in Python 3
My modules use to be encoded in 'utf-8' by a # coding: UTF-8 comment at the top, while my locale.getdefaultlocale()[1] returns 'cp1252'. So if I call MyObject('çça') from my console, it is encoded as 'cp1252' in Python 2, and in 'utf-8' when calling MyObject('çça') from the module. In Python 3, it will not be encoded, but a unicode literal.
edit:
I gave up hope about being allowed to avoid using '\' before a u (or x for that matter). Also I understand the limitations of importing unicode_literals. However, the many possible combinations of passing a string from a module to the console and vica versa with each different encoding, and on top of that importing unicode_literals or not and Python 2 vs Python 3, made me want to create an overview by actual testing. Hence the table below.
In other words, type(str('')) does not return <type 'str'> in Python 3, but <class 'str'>, and all of Python 2 problems seem to be avoided.
A: AFAIK, all that from __future__ import unicode_literals does is to make all string literals of unicode type, instead of string type. That is:
>>> type('')
<type 'str'>
>>> from __future__ import unicode_literals
>>> type('')
<type 'unicode'>
But str and unicode are still different types, and they behave just like before.
>>> type(str(''))
<type 'str'>
Always, is of str type.
About your r'\u' issue, it is by design, as it is equivalent to ru'\u' without unicode_literals. From the docs:
When an 'r' or 'R' prefix is used in conjunction with a 'u' or 'U' prefix, then the \uXXXX and \UXXXXXXXX escape sequences are processed while all other backslashes are left in the string.
Probably from the way the lexical analyzer worked in the python2 series. In python3 it works as you (and I) would expect.
You can type the backslash twice, and then the \u will not be interpreted, but you'll get two backslashes!
Backslashes can be escaped with a preceding backslash; however, both remain in the string
>>> ur'\\u'
u'\\\\u'
So IMHO, you have two simple options:
*
*Do not use raw strings, and escape your backslashes (compatible with python3):
'H:\\unittests'
*Be too smart and take advantage of unicode codepoints (not compatible with python3):
r'H:\u005cunittests'
A: For me this issue related to version not up to date, in this case numpy
To fix :
conda install -f numpy
A: When you're writing string literals which contain backslashes, such as paths (on Windows) or regexes, use raw strings. That's what they're for.
A: I try this on Python 3:
import os
os.path.abspath("yourPath")
and it's worked!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602171",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
}
|
Q: Add custom methods to Rails 3.1 asset pipeline? How can I add my custom methods to my assets such as css files like Rails did with 'asset_path' helper?
With Rail's own helper, I can write this:
# some.css.erb:
<%= asset_path 'a_image.png' %>
# How can I write this:
<%= my_custom_method 'a_image.png' %>
I've tried many ways but couldn't found a decent way to this. Do you know one?
Thanks
A: The best way I found was to create a custom helper module in app/helpers:
module AssetsHelper
def my_custom_helper_method
# do something
end
end
And then to require it like this in application.rb, after your applications configuration (very bottom):
module Sprockets::Helpers::RailsHelper
require Rails.root.join('app', 'helpers', 'assets_helper.rb')
include AssetsHelper
end
And you might follow this issue to find a better way: https://github.com/rails/rails/issues/3282
A: Normal helper methods are not available in asset views. To add you own methods you'll need to extend the Sprockets helper module. Have a look at the code of the built-in helpers to see how you might do this.
In a nutshell you can add a file in lib with the same structure as this and add you own methods. Don't forget to include the new library in you application initializer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: How to only print lines with unique fields? For example... if I had a file like this:
A 16 chr11 36595888
A 0 chr1 155517200
B 16 chr1 43227072
C 0 chr20 55648508
D 0 chr2 52375454
D 16 chr2 73574214
D 0 chr3 93549403
E 16 chr3 3315671
I need to print only the lines which have a unique first column:
B 16 chr1 43227072
C 0 chr20 55648508
E 16 chr3 3315671
It's similar to awk '!_[$1]++', but I want to remove all lines which have non-unique fist field.
Bash and python solutions preferably.
A: in bash, assuming first column has fixed with (3):
sort input-file.txt | uniq -u -w 3
'-u' option prints only the unique lines and '-w 3' compares no more than the first 3 characters.
A: How about this:
#!/usr/bin/env python
from collections import defaultdict
data = defaultdict(list)
with open('file', 'rb') as f:
for line in sorted(f.readlines()):
data[line[0]].append(line)
for key in sorted(data.iterkeys()):
if len(data[key]) == 1:
print data[key]
A: awk '
{count[$1]++; line[$1]=$0}
END {for (val in count) if (count[val]==1) print line[val]}
' filename
That may alter the order of lines. If that's a problem, try this 2-pass approach:
awk '
NR==FNR {count[$1]++; next}
count[$1] == 1 {print}
' filename filename
A: sed one liner solution:
sed ':a;$bb;N;/^\(.\).*\n\1[^\n]*$/ba;:b;s/^\(.\).*\n\1[^\n]*\n*//;ta;/./P;D' file
A: in python, much easier to read and tweak:
d = dict()
for line in open('input-file.txt', 'r'):
key = line.split(' ', 1)[0]
d.setdefault(key, list()).append(line.rstrip())
for k, v in sorted(d.items()):
if len(v) == 1:
print v[0]
A: import sys
from collections import OrderedDict
lines = OrderedDict()
for line in sys.stdin:
field0 = line.strip().split('\t')[0]
lines[field0] = None if field0 in lines else line
for line in lines.values():
if line is not None:
sys.stdout.write(line)
If you don't care aout preserving order you could use a plain old dict ({}) instead of OrderedDict.
This implementation doesn't care if the duplicate fields are adjacent.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: drupal 6 VIEWS - I'm stumped I've created a view (Drupal 6) that gets put on the users profile page.
The view is supposed to list all the images that the user has uploaded. However, the view is showing every uploaded image by all users.
(When a user uploads an image, it first gets approved by me, and then posted by me and displayed on the homepage with a credit to them and a link to their user profile -- so they are not the "author" of the post, I always am.)
How can I limit the photos displaying on their user profile to just show the images uploaded by that particular user?
Thank you.
A: Use arguments handling: add argument - User ID, check "if argument not provided" and select php code: return arg(1); // if views shown as block and you want to show it in user profile, path will like user/UID, so arg(1) return UID.
2Ted: hello Ted! php code will absolutely secured, if you will check it, for example via is_numeric() function. Also users cann't get any images, becuase Views wil use Block display, and you cann't provide for this arguments directly.
2user967969: Additionally about approving: You can create second field, where you will store user profile UID. So for my above text you should use this field for argument handling, instead of user uid.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602180",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is it possible to apply color effects to an image? any one guide me is it possible to apply color effects to an image using php?
as mentioned in the screen shot i want to select Ice,Black,Crystal etc.. color effect from the top and it should be applied to image selected below?
or any useful solution?
any help would be appreciated.
A: There is the GD library in PHP which I used successfully some time ago.
A: I'd highly recommend installing imagemagick on your server and then installing the imagick PHP extension. Imagemagick is extremely powerful and basically functions like a command-line Photoshop.
A: This function takes an image, then lets you add red, green, or blue to the image. You can also use negative numbers when calling this function, to create a lack of color.
function shade($image,$r=0,$g=0,$b=0){
$width=imagesx($image);
$height=imagesy($image);
$aw=0;
$ah=0;
for(;;){
if ($aw==$width) {$aw=0; $ah++;}
if ($ah==$height) break;
$rgb = imagecolorat($image, $aw, $ah);
$colors = imagecolorsforindex($image, $rgb);
$ar = $colors['red'];
$ag = $colors['green'];
$ab = $colors['blue'];
$ar+=$r;
$ag+=$g;
$ab+=$b;
if ($ar>255) $ar=255;
if ($ag>255) $ag=255;
if ($ab>255) $ab=255;
if ($ar<0) $ar=0;
if ($ag<0) $ag=0;
if ($ab<0) $ab=0;
$newcolor = imagecolorallocate($image, $ar, $ag, $ab);
$black = imagecolorallocate($image, 0, 55, 0);
imagesetpixel ($image , $aw , $ah , $newcolor );
$aw++;
}//end loop
return $image;
}
A: You should check out pslayers it will enable you to do what you're wanting to do.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: TIFF format not working with CSS The image (logo.tiff) will not display when defined in the CSS file and called in the Index file.
However, when I save it in another format, such as gif or jpeg, it works just fine. Is there a reason or a workaround for this?
Thanks guys.
CSS file:
.logo{
float:left;
overflow:hidden;
text-indent:-9999px;
background:url(../images/logo.tiff) no-repeat;
width:218px;
height:103px;
}
Index.html file:
<h1 class="logo"><a href="#">Our Slogan Here</a></h1>
A: TIF files re not supported in Web Browsers
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: JQuery - error with element non-focusable / how to force blur? I have an html form which uses jquery focus and blur in order to clear and restore some preset field text. However, the form is in a modal dialog which can be hidden and shown using jquery hide() and show(). However, when the form is hidden, it is throwing a javascript error:
an invalid form control with name = 'email' is not focusable
I'm assuming this is because the form is hidden and can't be accessed. Is there a way to force a blur event? Or some way to resolve this error? Here's my code:
$j('.dField').focus(function(){
clearInput($j(this)[0]); //The [0] seems to be necessary to retrieve the element at the DOM object level
});
$j('.dField').blur(function(){
restoreInput($j(this)[0]);
});
function clearInput(textField) {
if (textField.value == textField.defaultValue) {
textField.value = "";
}
}
//Restores the default value
function restoreInput(textField){
if (textField.value == ""){
textField.value = textField.defaultValue;
}
}
$j('#dFormBack').click(function(){
$j('#dContentContainer').show();
$j('#vehicle_form').hide();
});
A: You can activate the function inside the blur event listener, instead of trying to initiate a blur event.
restoreInput($j(".dfield")[0]);
A side note, your first lines can be written more efficiently:
$j('.dField').focus(function(){
clearInput(this);
}).blur(function(){
restoreInput(this);
});
this in the event handler refers to the DOM element to which the event listener is attached. It's unnecessary to wrap this inside a JQuery wrapper and get the DOM element again using [0].
A: As stated here:
Triggering the focus on hidden elements causes an error in Internet Explorer. Take care to only call .focus() without parameters on elements that are visible.
So you should just check if the element is hidden before calling focus()
A: You are correct. When something is not visible, it cannot be focus()'ed or blur()'ed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602188",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Telerik Tab/MultiPage Page Size Results I have two pages with RadTabStrip/RadMultiPage controls. Both the multi pages having the RenderSelectedPageOnly="true" setting. Both pages share the same user control, which has the same data. The interesting issue I'm having is that the first page is around 300K, whereas the second page is around 80K. I'm not sure how to figure this out because the control present has the same data, the same controls present, and the pages are identical. I verified both pages has RenderSelectedPageOnly on.
Any ideas where to look first?
Thanks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602193",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Expected constructor, destructor, or type conversion before '*' token Templated linked list My problem is really similar to this. However, my implementation differs in that I'm using a templated linked-list
Here's where I'm getting errors (second line). The purpose of this function is to return a pointer to a node at the k-th location in the list
template <class T>
List<T>::ListNode* List<T>::find(int k)
{
ListNode * curr = head;
while(curr != NULL && k > 0) {
curr = curr->next;
k--;
}
return curr;
}
And this is what my list looks like (made up of nodes, which store arbitrary data of type T)
template <class T>
class List
{
private:
class ListNode
{
public:
ListNode();
ListNode(T const & ndata);
ListNode * next;
ListNode * prev;
const T data;
};
Essentially this is the same question as the one I linked to, except that my list is templated. So, after making the changes that fixed the other problem, my code still throws errors. Any ideas as to why this is happening?
A: You need to use the typename keyword:
template <class T>
typename List<T>::ListNode* List<T>::find(int k)
{
...
}
This lets the compiler know that ListNode is a type. It is needed whenever you have a dependent name (i.e. one which depends on a template parameter) which is a type.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602201",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: php how to store and read json data via mysql? php how to store and read json data via mysql?
mysql_query("INSERT INTO text (data) VALUES (json_encode('id' => $uid, 'value' => yes))");
then, how to update data value? read out the data, then insert it with an json_encode and decode process, or only easy way update?
[{"id": "1", "value": "yes"}]
then insert another change to [{"id": "1", "value": "yes"},{"id": "2", "value": "yes"}]...
Or even if a long long value.
[{"id": "1", "value": "yes"},{"id": "2", "value": "yes"}...{"id": "10000", "value": "yes"}]
then update another one, change to [{"id": "1", "value": "yes"},{"id": "2", "value": "yes"}...{"id": "10000", "value": "yes"},{"id": "10001", "value": "yes"}]
I wanna to ask, how to do this mysql query processing more wiser and efficiently? Thanks for more suggestion.
A: You can do this more efficiently by NOT storing JSON in a single field but by creating a proper MySQL table with the JSON object's property names as field names.
Storing a text-string encoded representation of your data in a database completely destroys the point of using databases in the first place.
A: Yes but....WordPress stores a lot of its data as encoded JSON strings, such as the user capabilities. Storing an array as a discrete bit of data takes away having to do multiple reads on the database and allows you to get a lot of data on one read. If you never see the need to SELECT the individual parts of the JSON string I don't see why it isn't acceptable to do it this way. MySQL must think so too because it has functions to allow a SELECT on the individual fields within a JSON string if you so desired (see MySQL EXPLAIN keyword). But I do agree if you were going to do a lot of SELECTs on a field it should have one of its own. It all depends on how you are going to use the data.
A: Technically, you are going the wrong way with that. MySQL is used to store each of your ID/VALUE seperately. For the sake of NOT changing your code we'll look at your solution first but then i'll explain the "better" way of doing it.
First, you need to make your JSON as a variable, not part of your SQL:
mysql_query("INSERT INTO text (data) VALUES (".mysql_real_escape_string(array(json_encode('id' => $uid, 'value' => 'yes'))).")");
instead of
mysql_query("INSERT INTO text (data) VALUES (json_encode('id' => $uid, 'value' => yes))");
This first part will allow you to at least instead the data correctly into mysql. I am ASSUMING your table has an ID and that you will be using it to update or delete
When you retrieve your data, you can json_decode the $row['data'] to get your data back from the row and work with it. To update it, just do:
mysql_query("UPDATE text SET data = "'.mysql_real_escape_string(json_encode($myJsonToBeData)).'" WHERE rowid = '.$myrowid)
Now, for the RIGHT way to do this:
The right way to do this would be to have these fields into your table: ID, JSONID, JSONVALUE and use this SQL instead:
SELECT * FROM text WHERE id = $rowid
INSERT INTO text VALUES(NULL, $jsonid, $jsonvalue)
UPDATE text SET jsonid = $jsonid, jsondata = $jsondata
This is pretty basic, but it will allow you to have any number of entries in your database that make it searchable, indexed, sortable, queryable, etc...
A: Assuming you want to store the JSON string as a text or varchar datatype in MySQL, you can simply just escape the JSON string like so:
Storing
$object = new stdClass();
$object->key_a = "Value A";
$object->key_b = "Value B";
$storable_json_string = trim( addslashes( json_encode( $object ) ) );
// `$storable_json_string` contains an ugly invalid JSON
mysqli_query( "INSERT INTO table_a (column_a) VALUES ('{$storable_json_string}')" );
Reading
// read from the database
$result = mysqli_query( "SELECT column_a FROM table_a" );
$row = $result->fetch_object();
// makeover the ugly invalid JSON into a machine readable valid JSON
$valid_json_string = substr( stripslashes( $row->column_a ), 1, -1 );
// makes the JSON as a PHP object
$readable_json_object = json_decode( $valid_json_string );
echo $readable_json_object->key_a; // Value A
This could be not that secure but at least these should give you some stepping stones.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Springframework constructor-arg I have a MainClass which have 2 variables. I would like to pass those 2 values to a springframework bean class "Test". how do I define that in applicationContext.xml and also how do I pass those 2 variable values to the bean "Test".
Ex:
class MainClass {
public int var1;
public int var2;
public Test test;
public void setVar1(int var11) {
var1 = var11;
}
public void setVar2(int var22) {
var2 = var22;
}
public static void main(String args[]) {
ApplicationContext context =
new FileSystemXmlApplicationContext("applicationContext.xml");
Test = context.getBean("test");
}
}
------------ TEST class ------------
public class Test {
public Test (int var1, int var2) {}
}
------------- applicationContext.xml -------------
<bean id="test" class="com.path.test">
<constructor-arg index="0" type="int" value="????"/>
<constructor-arg index="1" type="int" value="????"/>
</bean>
A: You can pass values in like this:
<bean id="test" class="com.path.test.Test">
<constructor-arg index="0" type="int" value="123"/>
<constructor-arg index="1" type="int" value="456"/>
</bean>
You should remember to put your fully-qualified class name as the value of the class attribute.
That said, your Test class is not holding onto its state. If you want to get a hold of the values you specified in your applicationContext.xml, you should create some members of Test:
public class Test {
private int v1;
private int v2;
public Test (int var1, int var2) {v1 = var1; v2 = var2;}
public int getVOne() {
return v1;
}
public int getVTwo() {
return v2;
}
}
You should then be able to access these in your main method like this:
public static void main(String args[]) {
ApplicationContext context =
new FileSystemXmlApplicationContext("applicationContext.xml");
Test test = context.getBean("test");
int v1 = test.getVOne();
int v2 = test.getVTwo();
System.out.println("V1: " + v1 + " V2: " + v2); //output: V1: 123 V2: 456
}
A: As Nicholas says, it's a bit of a weird thing to do, but you could achieve it using PropertyPlaceholderConfigurer.
Something like this:
public static void main(String args[]) {
PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
Properties properties = new Properties();
properties.setProperty("var1", Integer.toString(var1));
properties.setProperty("var2", Integer.toString(var2));
configurer.setProperties(properties);
FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext();
context.addBeanFactoryPostProcessor(configurer);
context.setConfigLocation("applicationContext.xml");
context.refresh();
Test test = (Test) context.getBean("test");
}
NOTE: var1 and var2 should be static if you want to reference them from main()
Then reference the placeholders like so:
<bean id="test" class="com.path.test">
<constructor-arg index="0" type="int" value="${var1}"/>
<constructor-arg index="1" type="int" value="${var2}"/>
</bean>
See also this forum thread: http://forum.springsource.org/showthread.php?71815-Passing-Bean-properties-using-java.util.Properties
API doc: http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.html
HTH
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602205",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Unobstrusive javascript for Forgot Password Link I have a spring form that is used to log in to the website. Its a simple spring form with a username and password fields and a submit button. There is a forgot password link next to the submit button, which uses href="javascript:jump();" function as below:
function jump() {
document.forms[0].action='pwdSelfResetStep1.mobi';
document.forms[0].submit();
}
this works perfectly when the browser has javascript enabled. However, i want to use it on the browsers where javascript is disabled as well. (unobstrusive JS). Any help is really appreciated.
A: I assume that the reason you submit the form is to get the user's email address, so you won't be able to do that (dynamically) without javascript, but you can simply change the href on the link to "pwdSelfResetStep1.mobi" instead, and attach jump() to the onclick event of the link.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602209",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Silverlight and synchronous calls to WCF I already know that calls to WCF services via Silverlight are async. I also know that many people try to find ways to make them sync calls for a variety of silly reasons (blocking UI thread for example), and that such a thing should be avoided like the plague, generally.
I just want to be able to handle all of the threading stuff myself as I have found that having to hook / unhook all of the '*Completed' events is a lot of extra work, and a huge pain, especially when you don't know the order of the calls etc. Anybody know of a clever way to make the sync calls and do the threading yourself?
A: Given that you shouldn't make synchronous networking calls, you shouldn't make synchronous networking calls and you shouldn't make synchronous networking calls, if you really, really know what you're doing, then you actually can make synchronous (blocking) calls only if you are not in the UI thread.. Just realize that it is not an officially supported scenario (so it wasn't as tested as the other features), but I've tried it a few times and it just works.
All you need to do is to use the [ServiceContract] interface (instead of the client class) - the one which exposes the Begin/End operations - and call EndXXX(BeginXXX(parameters, null, null)) as shown in the example below (this is a page with two controls, a Button whose Click event is bound to the Button_Click handler, and a TextBox named "txtDebug" where the code writes the results.
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
this.AddToDebug("In Button_Click");
ThreadPool.QueueUserWorkItem(delegate
{
ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
ServiceReference1.Service1 asInterface = client;
this.AddToDebug("Calling server \"synchronously\"...");
int result = asInterface.EndAdd(asInterface.BeginAdd(45, 67, null, null));
this.AddToDebug("Result: {0}", result);
client.CloseAsync();
});
}
private void AddToDebug(string text, params object[] args)
{
if (args != null && args.Length > 0)
{
text = string.Format(text, args);
}
text = string.Format("[{0} - {1}] {2}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("HH:mm:ss.fff"), text);
this.Dispatcher.BeginInvoke(() => this.txtDebug.Text = this.txtDebug.Text + text + Environment.NewLine);
}
}
Now, if you want to do it from the UI thread, then really, there's no way to block and wait for the response (since the response is supposed to be returned on the UI thread as well). And if you're confortable with the Begin/End pattern, you can still do the asynchronous calls, but without worrying about event handlers being leaked.
A: Solutions that rely on blocking a thread (any thread not just the UI thread) are best avoided. Threads are expensive resources and ThreadPool threads are a limited resource. Thats why network APIs have callback semantics in first place.
I agree with Carlos the first thing to do is switch to the .NET Async Pattern interface provided by the service instead of the horrible event based one. (The event based approach is designed to make things simple for UI developers that "think in events"). If your service is called "Service1" your clientside class will be called "Service1Client". However that class will also support an interface called "Service1", which will have Begin/End versions of the OperationContracts.
"a clever way to make the sync calls"
Without blocking a thread this is impossible. However making a series of tasks synchronous isn't really the requirement. What we want is simply to ensure that a series of tasks occur in sequence. You can do this simply by calling the next task from the callback method of the previous task but nesting becomes a bit of a problem.
Have a look a this series of articles perhaps starting with the one on the .NET Asynchronous Pattern. Unfortunately a WCF article is still a work in progress but I really must get it posted soon, this stuff comes up here often.
A: What if you wrap the call in another function, and that function will sleep until the async call returns?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can I check if a VHDL Integer is even or odd? What is the easiest or simplest way to check if an integer signal is even or odd in VHDL?
A: if (A mod 2) = 0 then
-- it's even
else
-- it's odd
end if;
A: As a side note if the signal is a vector, then you can do the following:
if (A(0)) then
-- it's odd
else
-- it's even
A: function is_even(val : integer) return boolean is
constant vec: signed(31 downto 0) := to_signed(val, 32);
begin
return vec(0) = '0';
end;
or
function is_even(val : integer) return boolean is
begin
return val mod 2 = 0;
end;
depending on whether your synthesiser is bright enough to figure out mod 2
A: Another way if you are not storing as an integer * is to register the LSB from the standard logic vector holding the value and check if it is 0 or 1.
EDIT: Re-storing integers
removed * (which can be a problem on many FPGA's)
My mistake here, I was thinking along two different paths and mixed the two up. I have had trouble before passing character and string types between components when coding on FPGA's. While I cannot list the error messages off hand, I took a mental note to use std logic vectors instead of the pre-compile types. I found that they always seemed to work in simulation but never on the board.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Extra space below rows that appears when scrolling to the bottom of a DataGrid? Ok, so I have a DataGrid (the standard WPF DataGrid, which comes with .Net 4.0, NOT the WPF Toolkit DataGrid) with the CanUserAddRows=false. It's bound to an ObservableCollection in the ViewModel. It has a MaxHeight set properly, so that it will scroll if there are too many rows for the screen.
It works just fine the way it is, except for the fact that if the user puts their mouse over the DataGrid and then moves the Scroll-wheel downwards, then some extra space appears below the rows:
I would rather that the gray space does not appear in this case (where there is no need to scroll). How do I accomplish this?
P.S. I've actually built my own functionality for a new row at the bottom of the DataGrid due to some special requirements for our program, thus the blank row at the bottom of the DataGrid. It's done totally in the VM, so it shouldn't affect the answer to this question.
Update:
This behavior happens on every DataGrid I have currently. However, when the MaxHeight is set on the DataGrid, and there are more rows than can be displayed, then the content starts to scroll. In this situation, the grey space below the lines is variable in size. That is, since the DataGrid scrolls based on content rather than physical scrolling (see this for details about the difference, under the remarks section), there is a little extra space at the bottom below the last row when you scroll all the way to the bottom. The grey space fills that extra space. Here is an example:
To clarify, I don't mind that behavior that much, it's just when the grey space appears when there is no need for scrolling. I just thought that this behavior would help indicate the cause of the problem.
Update #2:
I have discovered what can cause the problem: if you set the EnableRowVirtualization to false, then this problem occurs. However, if I want to set it to false, how can I prevent the grey space/"extra line" from occurring when there is no need to scroll? (this is my main concern and the main point of this question)
A: Try this: Set
*
*ScrollViewer.CanContentScroll to False
*ScrollViewer.HorizontalScrollBarVisibility to Disabled
Then
<DataGrid x:Name="myDataGrid"
RowHeaderWidth="{Binding RelativeSource={RelativeSource Self}, Path=RowHeight}"
ScrollViewer.CanContentScroll="False"
ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Width="*" Binding="{Binding Name}"/>
<DataGridTextColumn Header="Age" Width="*" Binding="{Binding Age}"/>
</DataGrid.Columns>
</DataGrid>
A: I've faced the same issue. In my case extra space at the bottom was because MaxHeight being set and bacause of
VirtualizingPanel.ScrollUnit="Item"
After setting it to
VirtualizingPanel.ScrollUnit="Pixel"
the problem actually dissapears (still having MaxHeight property)
A: You question is a little unclear but I can offer some investigative steps to find out what the cause is.
*
*Make sure that your observable collection is not harboring any null values. A null entry in the collection will still show up in the grid as a blank row.
*The fact that it is happening on different environment means that your data source may be different, so that is a good place to check. Check here that the count of the collection is directly matched with the number of rows on the grid (including the empty row).
*Make sure that this is not a control templating issue. If possible, look at the Style and DataTemplate for your DataGrid control to see if this is not a visual side-effect.
Apart from that, you should include more details in your question, such as the type of DataGrid you are using (eg. WPF Toolkit, Telerik, DevExpress, etc) so that we can rule out a templating issue.
A: I had the same problem and it was caused by the DataGrid's MaxHeight property not being set to a multiple of the row size, so the left over space was showing up at the bottom of the DataGrid. For example: if there are 5 rows that are 10 pixels in height and the MaxHeight property is set to 55 then there will be 5 pixels of space at the bottom.
A: Somehow I guess it may be because that DataGrid has to show the first visible row at row boundary, e.g. it can't display only the lower half of the first visible row in order to make the last row align with the bottom of the control.
You can test that by two steps:
1) scroll to the bottom of your DataGrid, and see the extra gray space;
2) slowly resize the DataGrid (or its containing window) vertically, and see how that gray space change, while noting the first visible row stays unmoved.
A: I had a similar problem and the answer is simple.
All you have to do is to put the following in your datagrid definition in XAML:
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding ItemList}"
CanUserAddRows="false"
and you are clear.
Another similar stuff is, if you get a blank column in your data grid then the solution is to put the Width="*" in your last column definition also in XAML.
Hope that works for you.
A: Set ScrollViewer.CanContentScroll="False" & ScrollViewer.HorizontalScrollBarVisibility="Disabled" in DataGrid.
A: set both ScrollViewer.CanContentScroll and CanUserAddRows to false.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602214",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Moonlight, WebClient and "Exception has been thrown by the target of an invocation" I'm writing a little engine to download text from some .php files, I've done this engine in Visual c# and I haven't got problems.
I'm doing this:
[ ... ]
WebClient client = null;
try {
client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler( CompleteDownload );
client.AllowReadStreamBuffering = true;
client.DownloadStringAsync( new Uri( "http://blabla/bla.php" ) );
}
catch (Exception e) {
lbl1.Text = e.Message;
}
[ ... ]
And this to "catch" the downloaded data:
public void CompleteDownloadPcops( object sender, DownloadStringCompletedEventArgs ea ) {
if ( ea.Error == null ) {
try{
lbl1.Text = ea.Result;
}
catch(Exception e) {
lbl2.Text = e.Message;
}
}
}
Executing this code I get, on lbl1 the exception Exception has been thrown by the target of an invocation, result of lbl1.Text = ea.Result; in CompleteDownload. Why? And, after knowing the reason, how I can solve it?
More info: I'm using moonlight in monodevelop 2.4 on Ubuntu 11.04 platform.
UPDATE
I've update my system to MonoDevelop 2.6 as you recomended me. Now, doing the same, I've get an error on ea.Error. The message is (in spanish):
System.Security.SecurityException ---> System.Security.SecurityException: Error de seguridad.
en System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
en System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClass5.<EndGetResponse>b__4(Object sendState)
en System.Net.Browser.AsyncHelper.<>c__DisplayClass4.<BeginOnUI>b__1(Object sendState)
--- Fin del seguimiento de la pila de excepciones internas ---
en System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
en System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
en System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
en System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result).
The full code I'm using now is:
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
private void btn1_Click(object sender, RoutedEventArgs e)
{
WebClient client = null;
try
{
client = new WebClient();
client.DownloadStringCompleted += new System.Net.DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.AllowReadStreamBuffering = true;
client.DownloadStringAsync(new Uri("http://carles.lambdafunction.com/a/try.php"));
}
catch (Exception ex)
{
lbl1.Text = ex.Message;
btn1.Content = "A";
}
}
void client_DownloadStringCompleted(object sender, System.Net.DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
try
{
lbl2.Text = e.Result;
}
catch (Exception ex)
{
lbl1.Text = ex.Message;
lbl2.Text = ex.InnerException.ToString();
btn1.Content = "C";
}
}
else
{
lbl1.Text = e.Error.ToString();
btn1.Content = "B";
txt1.Text = e.Error.ToString();
}
}
}
You can see the output of the web call (to the dummy page /p/try.php), it's really simple. Really, now, I'm lost because I'm following this tutorial: http://weblogs.asp.net/scottgu/pages/silverlight-tutorial-part-3-using-networking-to-retrieve-data-and-populate-a-datagrid.aspx .
A: Where is your .xap located ?
If you're trying to read data from a different web site (address / port) then be sure to read
"Network Security Access Restrictions in Silverlight" and provide a policy file that allow the application to access your web server.
E.g. both the following URL returns 404 (which means there's no policy to allow Silverlight or Moonlight applications to access the server)
*
*http://carles.lambdafunction.com/clientaccesspolicy.xml
*http://carles.lambdafunction.com/crossdomain.xml
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602218",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Powershell - Array Range from user input What would be the easiest way to get user input for an array range.
For example:
function MyArrayOfMachines {
[CmdletBinding()]
param(
[parameter(Mandatory=$true)][string]$Machine
# What should I assign the $Range variable as?
)
# Hardcoded range. User should be able to enter the range
$Range = 2..5
for ($i=0; $i -lt $array.length; $i +=1)
{
$result = $array[$i]
$output = $machine+$result
$output
}
}
The above function should take the input as the name of the machine and the array range. For now I have the array range hardcoded. When I assign $Range as [Array]$Range in the user prompt, there is a prompt for $Range[0] etc etc. But I would like the user the enter the range.
A: Doesn't this work? Unless I misunderstood your question...
function test($range){
$range
}
test -range (1..5)
A: You can also accept the range as a string and parse it yourself:
function Test
{
param($range)
if($range -is [String])
{
[int]$start, [int]$end = $range.split('.', [StringSplitOptions]::RemoveEmptyEntries)
$start..$end
}
else
{
$range
}
}
The reason for the if / else is for cases where the user passes an actual range, as in manojlds answer, rather than a string to be parsed (like 1..5). This means you can't strongly type the param though.
A: Make it two parameters:
function test{
param ( [int]$st,
[int]$end)
$Range = $st..$end
$Range
}
test 1 5
If they input the start and end of the range you can use that to create it dynamically in the function.
EDIT:
To get the range from a string, try:
function test{
param ($Range)
$NewRange = $Range.substring(0,($Range.indexof('.')))..$Range.substring(($Range.lastindexof('.') + 1))
$NewRange
}
test 1..5
A: I agree with @manojlds, the range should be passed in as an array. Parsing a string limits the possibilities of what a user could enter. By using [int[]] you can force the user to specify an array of integers. This would also allow a user to specify a broken range such as ((2..4)+(6..12)) which is harder to allow for when parsing strings.
In your example I'm not sure where $array is coming from, and you only need one line to return a computed machine name.
function MyArrayOfMachines {
param(
[parameter(mandatory=$true)]
[string] $machine,
[parameter(mandatory=$true)]
[int[]] $range
)
foreach($n in $range) {
$machine+$n
}
}
You could create a single machine name,
MyArrayOfMachines Laptop 1
a range of machines,
MyArrayOfMachines Workstation (2..10)
or a non-consecutive array of machines
MyArrayOfMachines Server ((2..3)+(5..9))
A: You could just pass a string and evaluate it:
function Test([string]$range) {
if ($Range -match '^\d+\.\.\d+$') {
$RangeArray = Invoke-Expression $Range
} else {
$RangeArray = 1..5
}
}
Some minimal validation is done to ensure that the user cannot pass arbitrary code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: What are the differences in the VisualStudio Add-ins for Mercurial? I'm evaluating Visual Studio Add-ins for Mercurial. Currently, I've identified 3 potential candidates :
*
*VisualHg http://visualhg.codeplex.com
*Mercurial Toolbar : http://mercurialtoolbar.codeplex.com
*HgSccPackage : http://www.newsupaplex.pp.ru/hgscc_news_eng.html
I'm looking for a comparison of features or capabilities.
Features that are important to me are: a tool that integrate well with VS, Open Source, actively developed, and robust.
A: I have just finished researching the same question. It seems that VisualHG had its last version released a year and a half ago in Oct 2011. In all 2012 it had just 3 commits. Last version of HgSccPackage was released in Mar 2012 which is roughly a year ago, but it had a bunch of commits since then.
It seems that both tools are equally powerful, but HgSccPackage recieves more investment. I decided to go with HgSccPackage.
A: Well, let's compare the details of development:
*
*VisualHg's page says it's stable. The last version release was March of this year and the latest changesets in the source are from 1 week ago.
*HgSccPackage (better found here than your other link) was last updated in the VS Gallery 2 days ago. (It can also be found on bitbucket.)
*Mercurial Toolbar's page says it's in alpha and was last updated March 2010. Of the three, it appears this one is not actively developed.
It appears [from skimming some text] that HgSccPackage has its own windows for graph logs and whatnot.
VisualHg on the other hand is more of a supplement to TortoiseHg. Many of the menu commands for VisualHg will open TortoiseHg windows. If you use TortoiseHg's UI, this consistency may be preferrable. From the screenshot I saw for HgSccPackage, you may find VisualHg's status icons more standard, as well.
Since you have only 2 choices, it really doesn't take much to try both and see which you prefer.
I have VisualHg installed, but tend to use TortoiseHg's Workbench more than VisualHg. VisualHg stays in use mainly for its automatic add, remove, rename, etc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602222",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "54"
}
|
Q: Multiple flash ads changing the way they are stacked....only in Chrome? I have three flash files that are all stacked on top of each other. There is a background, a foreground, and a close button. When in Chrome, they will sometimes change which one has a higher z-index (although this is not confirmed the inspector). They stay as expected in FF and Safari though.
Here is the code:
$('<div id="overlay_wrapper" />').appendTo('body').append('<div id="overlay_background" />').append('<div id="overlay_foreground" />').append('<div id="overlay_button"/>');
var flashvars = {};
var params = {};
params.allowscriptaccess = 'always';
var attributes = {};
params.wmode = "transparent";
params.scale = "exactfit"; // try setting this as default if noborder doesnt work
var flashvars = {};
var params = {};
params.allowscriptaccess = 'always';
var attributes = {};
var win_width = $(window).width();
var win_height = $(window).height();
var dim = {
'width' : win_width,
'height' : win_height
};
$('#overlay_wrapper').css(dim);
swfobject.embedSWF(custom_takeover_options.wallpaper_url, 'overlay_background', win_width, win_height, '9.0.0',"expressInstall.swf", flashvars, params, attributes, function(){
swfobject.embedSWF(custom_takeover_options.foreground_url, 'overlay_foreground', custom_takeover_options.foreground_width, custom_takeover_options.foreground_height, '9.0.0',"expressInstall.swf", flashvars, params, attributes, function(){
swfobject.embedSWF(custom_takeover_options.close_url, 'overlay_button', 150, 40, '9.0.0',"expressInstall.swf", flashvars, params, attributes);
});
});
Any thoughts would help!
Thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602241",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: OpenCV 2.1: facedetect.cpp crashes when it finds ugly face I am trying to compile the facedetect.cpp in the OpenCV\Samples\C folder, in Visual Studio 2010. The project compiles and begins just fine, shows a preview of my camera, and then seems to crash at cascade.detectMultiScale() as soon as it detects a face. I concluded that OpenCV thinks I am too ugly.
Unhandled exception at 0x100342bf in HeadTrackerExample.exe: 0xC0000005: Access violation writing location 0x00000000.
Unfortunately the debug info doesn't let me probe deeper. I am linking against cv210.lib;cxcore210.lib;highgui210.lib; the debug versions won't work:
LDR: LdrpWalkImportDescriptor() failed to probe D:\OpenCV2.1\bin\cv210d.dll for its manifest, ntstatus 0xc0150002
I'm going to try to trick the classifier with a printout of Anne Hathaway but I am open to other suggestions.
https://code.ros.org/trac/opencv/browser/trunk/opencv/samples/c/facedetect.cpp
A: I guess I'm better looking than you because it's working here (under OS X). Are you sure you're successfully loading the xml files? Are you using the default xml files (haarcascade_frontalface_alt.xml and haarcascade_eye_tree_eyeglasses.xml)?
It sure looks like you have a null pointer. Try setting a breakpoint at the call to cascade.detectMultiScale() and examine the values of cascade, smallImg, smallImg.data, and faces.
Edit: populating the faces vector
Here's the detectMultiScale code:
void HaarClassifierCascade::detectMultiScale( const Mat& image,
Vector<Rect>& objects, double scaleFactor,
int minNeighbors, int flags,
Size minSize )
{
MemStorage storage(cvCreateMemStorage(0));
CvMat _image = image;
CvSeq* _objects = cvHaarDetectObjects( &_image, cascade, storage, scaleFactor,
minNeighbors, flags, minSize );
Seq<Rect>(_objects).copyTo(objects);
}
It's not touching the faces vector until the last line after all the detection is done. If you are adventurous, you could throw some printf statements in here to see if cvHaarDetectObjects is completing and if it is returning a null pointer.
A: I spent the day trying to fix this. Who knows why it was crashing? I couldn't link to the debug DLLs so we'll never know. I downloaded the OpenCV-2.1.0-win32-vs2008.exe distribution. And I am using Visual Studio 2010. Therefore, the exe was crashing with
LDR: LdrpWalkImportDescriptor() failed to probe D:\OpenCV2.1\bin\cv210d.dll for its manifest, ntstatus 0xc0150002
Debugger:: An unhandled non-continuable exception was thrown during process load
The program '[5172] HeadTrackerExample.exe: Native' has exited with code -1072365566 (0xc0150002).
This is the "0xc0150002 error". According to Dependency Walker, the OpenCV debug DLLs are trying to find msvcr90d.dll and msvct90d.dll, the Visual Studio 2008 debug runtime DLLs. Well, I obtained these and it still didn't work, so then this gets into esoteric Windows sidebyside and manifest stuff.
I switched to the OpenCV-2.3.1-win-superpack.exe distribution and it is now working.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602246",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Is Thread managed by the thread pool? I know that the CLR gives each AppDomain ThreadPool time slice to work , yet i wanted to know if by creating a new thread like so Thread t = new Thread(...);
Is it managed by the CLR or by the AppDomin ThreadPool ?
A: Thread t = new Thread(); will not be managed by the ThreadPool. But it is an abstraction provided by the CLR on the Operating System threads. ThreadPool is an addtional abstraction which facilitates reusing threads and sharing thread resources.
Here is an excellent resource on threads in .NET: http://www.albahari.com/threading/
If you're using .NET 4.0 consider using TPL.
A: When you create threads with the Thread class, you are in control. You create them as you need them, and you define whether they are background or foreground (keeps the calling process alive), you set their Priority, you start and stop them.
With ThreadPool or Task (which use the ThreadPool behind the scenes) you let the ThreadPool class manage the creation of threads, and maximizes reusability of threads, which saves you the time needed to create a new thread. One thing to notice is that unlike the Thread default, threads created by the ThreadPool don't keep the calling process alive.
A huge advantage of using the ThreadPool is that you can have a small number of threads handle lots of tasks. Conversely, given that the pool doesn't kill threads (because it's designed for reusability), if you had a bunch of threads created by the ThreadPool, but later the number of items shrinks, the ThreadPool idles a lot, wasting resources.
A: When you create new threads they are not managed by the thread pool.
A: If you create a thread manually then you control its life time, this is independent from the Thread pool.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602250",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Can't assign value to Variable: undefined method `[]' for nil:NilClass (NoMethodError) I am completely stumped on this one.
I have the following code:
puts block.at_xpath("*/img")["width"].to_i
but when I change it to
width = block.at_xpath("*/img")["width"].to_i
I get this error:
NokogiriTUT.rb:70:in `blockProcessor': undefined method `[]' for nil:NilClass (NoMethodError)
When I have the puts in there it returns the expected value.
Update:
def blockProcessor(block)
header = block.xpath('td[@class="default"]/*/span[@class="comhead"]')
array = header.text.split
if array[0] != nil #checks to make sure we aren't at the top of the parent list
### Date and Time ###
if array[2] == 'hours' || array[2] == 'minutes'
date = Time.now
else
days = (array[1].to_i * 24 * 60 * 60)
date = Time.now - days
end
##Get Comment##
comment = block.at_xpath('*/span[@class="comment"]')
hash = comment.text.hash
#puts hash
##Manage Parent Here##
width = block.at_xpath("*/img")["width"].to_i
prevlevel = @parent_array[@parent_array.length-1][1]
if width == 0 #has parents
parentURL = header.xpath('a[@href][3]').to_s
parentURL = parentURL[17..23]
parentURL = "http://news.ycombinator.com/item?id=#{parentURL}"
parentdoc = Nokogiri::HTML(open(parentURL))
a = parentdoc.at_xpath("//html/body/center/table/tr[3]/td/table/tr")
nodeparent = blockProcessor(a)
@parent_array = []
node = [hash, width, nodeparent] #id, level, parent
@parent_array.push node
elsif width > prevlevel
nodeparent = @parent_array[@parent_array.length-1][0]
node = [hash, width, nodeparent]
@parent_array.push node
elsif width == prevlevel
nodeparent = @parent_array[@parent_array.length-1][2]
node = [hash, width, nodeparent]
@parent_array.push node
elsif width < prevlevel
until prevlevel == w do
@parent_array.pop
prevlevel = @parent_array[@parent_array.length-1][1]
end
nodeparent = @parent_array[@parent_array.length-1][2]
node = [hash, width, nodeparent]
@parent_array.push node
end
puts "Author: #{array[0]} with hash #{hash} with parent: #{nodeparent}"
##Handles Any Parents of Existing Comments ##
return hash
end
end
end
Here is the block that it is acting on.
<tr>
<td><img src="http://ycombinator.com/images/s.gif" height="1" width="0"></td>
<td valign="top"><center>
<a id="up_3004849" href="vote?for=3004849&dir=up&whence=%2f%78%3f%66%6e%69%64%3d%34%6b%56%68%71%6f%52%4d%38%44"><img src="http://ycombinator.com/images/grayarrow.gif" border="0" vspace="3" hspace="2"></a><span id="down_3004849"></span>
</center></td>
<td class="default">
<div style="margin-top:2px; margin-bottom:-10px; "><span class="comhead"><a href="user?id=patio11">patio11</a> 12 days ago | <a href="item?id=3004849">link</a> | <a href="item?id=3004793">parent</a> | on: <a href="item?id=3004471">Ask HN: What % of your job interviewees pass FizzB...</a></span></div>
<br><span class="comment"><font color="#000000">Every time FizzBuzz problems come up among engineers, people race to solve them and post their answers, then compete to see who can write increasingly more nifty answers for a question which does not seek niftiness at all.<p>I'm all for intellectual gamesmanship, but these are our professional equivalent of a doctor being asked to identify the difference between blood and water. You can do it. <i>We know</i>. Demonstrating that you can do it is not the point of the exercise. We do it to have a cheap-to-administer test to exclude people-who-cannot-actually-program-despite-previous-job-titles from the expensive portions of the hiring process.</p></font></span><p><font size="1"><u><a href="reply?id=3004849&whence=%2f%78%3f%66%6e%69%64%3d%34%6b%56%68%71%6f%52%4d%38%44">reply</a></u></font></p>
</td>
</tr>
A: Your basic problem is that you don't understand XPath. (You are in good company there; XPath is quite confusing.) Your selectors simply don't match what you think they match. In particular, the one that blows up
*/img
should be
//img
or something like that.
Now, because the xpath selector doesn't match anything, the value of this Ruby statement
block.at_xpath("*/img")
is nil. And nil doesn't support [], so when you try to call ["width"] on it, Ruby complains with a undefined method [] for nil:NilClass error.
And as for why it only blows up when you assign it to a variable... yeah, that's not actually what's happening. You probably changed something else too.
And now, please allow me to make some other hopefully constructive code criticisms:
*
*Your question was apparently designed to make it difficult to answer. In the future, please isolate the code in question, don't just paste in your whole homework assignment (or whatever this screen scraper is for).
*It would be extra great if you made it into a single runnable Ruby file that we can execute verbatim on our computers, e.g.:
.
require "nokogiri"
doc = Nokogiri.parse <<-HTML
<tr>
<td><img src="http://ycombinator.com/images/s.gif" height="1" width="0"></td>
<td valign="top"><center>
<a id="up_3004849" href="vote?for=3004849&dir=up&whence=%2f%78%3f%66%6e%69%64%3d%34%6b%56%68%71%6f%52%4d%38%44"><img src="http://ycombinator.com/images/grayarrow.gif" border="0" vspace="3" hspace="2"></a><span id="down_3004849"></span>
</center></td>
<td class="default">
<div style="margin-top:2px; margin-bottom:-10px; ">
<span class="comhead">
<a href="user?id=patio11">patio11</a> 12 days ago | <a href="item?id=3004849">link</a> | <a href="item?id=3004793">parent</a> | on: <a href="item?id=3004471">Ask HN: What % of your job interviewees pass FizzB...</a>
</span>
</div>
<br><span class="comment"><font color="#000000">Every time FizzBuzz problems come up among engineers, people race to solve them and post their answers, then compete to see who can write increasingly more nifty answers for a question which does not seek niftiness at all.<p>I'm all for intellectual gamesmanship, but these are our professional equivalent of a doctor being asked to identify the difference between blood and water. You can do it. <i>We know</i>. Demonstrating that you can do it is not the point of the exercise. We do it to have a cheap-to-administer test to exclude people-who-cannot-actually-program-despite-previous-job-titles from the expensive portions of the hiring process.</p></font></span><p><font size="1"><u><a href="reply?id=3004849&whence=%2f%78%3f%66%6e%69%64%3d%34%6b%56%68%71%6f%52%4d%38%44">reply</a></u></font></p>
</td>
</tr>
HTML
width = doc.at_xpath("*/img")["width"].to_i
That way we can debug with our computers, not just with our minds.
*
*You're writing Ruby now, not Java, so conform to Ruby's spacing and naming conventions: file names are snake_case, indentation is 2 spaces, no tabs, etc. It really is difficult to read code that's formatted wrong -- where "wrong" means "non-standard."
*Everywhere you have one of those descriptive comments (### Date and Time ###) is an opportunity to extract a method (def date_and_time(array)) and make your code cleaner and easier to debug.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Invalid Permissions When Running Julius Speech Recognition on a Wav File How do you use Julius to convert a Wav file containing spoken words into a text file containing those words? I've read the Julius Book and I've downloaded the Julius quickstart release on Voxforge. From the docs, I think I'm suppose to list the Wav file I want to process in another file, and pass the filename of that file to Julius via the filelist param.
For example, I have the julius executable and the other quickstart files (grammar files, conf, etc) in /home/myuser/test, and I have all my Wav files in /home/myuser/test/audio. julius is owned by my user, and has execute permission, and all the audio files have 777 permission. I have my filelist at /home/myuser/test/audio/filelist.txt, with lines like:
/home/myuser/test/audio/somewav1.wav
/home/myuser/test/audio/somewav2.wav
/home/myuser/test/audio/somewav3.wav
However, when I run:
./julian -input rawfile -filelist /home/myuser/test/audio/filelist.txt -C julian.jconf
I get the error:
./julian: line 1: /home/myuser/test/audio/somewav1.wav: Permission denied
I can't fathom why it can't access the file. It's owned by my user, running as my user, and reading a file owned by my user.
Why is Julius giving me this error?
A: Just try using sudo Front of sentence. Like
sudo ./julian -input rawfile -filelist /home/myuser/test/audio/filelist.txt -C julian.jconf
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: JTextField key listener is one behind after pasting I am trying to check that the text in a JTextField matches a perticular pattern, and if it does / doesn't display a message the user. This is what I have so far:
public class input extends KeyListener{
// Some code here
final JTextField inputField = new JTextField(35);
// Some more code...
public void generate(){
// Some GUI code here...
inputField.addKeyListener(this);
}
public void keyPressed(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {
if(e.getSource() instanceof JTextField && e.getSource().equals(inputField)){
if(Pattern.matches("../../....", (JTextComponent) e.getSource()).getText())))
System.out.println("Yh, it works");
else System.out.println("EPIC FAIL (LOL)");
}
}
}
And it does actually work almost perfectly. However, if I paste something using CTRL + V, I have to type two more characters (as opposed to one) before the KeyListener registers that the string is different! So does any one have any idea's why?
Sorry if I have missed out any details - I have tried to make the post as short and concise as possible; so please don't hesitate to ask anything...
A: For starters, don't use a KeyListener for this type of problem as it is doomed to fail, and even if you get it to work, it's a kludge at best. Instead I'd use either an ActionListener if I wanted to do my checking after the user is completely done entering information, or a DocumentListener if I want to check input as a user is entering, but am not going to block that entering or change the displayed text, or a Document Filter if I'm going to check the input as the user is entering and block it or change it if it is not appropriate.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Get remaining time for a sleeping thread wake up in C# In C#, how can I get the remaining time for a sleeping thread wake up?
A: You can't. You have to remember when you put the thread to sleep and do the calculation yourself.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I get SUM function in MySQL to return '0' if no values are found? Say I have a simple function in MySQL:
SELECT SUM(Column_1)
FROM Table
WHERE Column_2 = 'Test'
If no entries in Column_2 contain the text 'Test' then this function returns NULL, while I would like it to return 0.
I'm aware that a similar question has been asked a few times here, but I haven't been able to adapt the answers to my purposes, so I'd be grateful for some help to get this sorted.
A: Use IFNULL or COALESCE:
SELECT IFNULL(SUM(Column1), 0) AS total FROM...
SELECT COALESCE(SUM(Column1), 0) AS total FROM...
The difference between them is that IFNULL is a MySQL extension that takes two arguments, and COALESCE is a standard SQL function that can take one or more arguments. When you only have two arguments using IFNULL is slightly faster, though here the difference is insignificant since it is only called once.
A: Can't get exactly what you are asking but if you are using an aggregate SUM function which implies that you are grouping the table.
The query goes for MYSQL like this
Select IFNULL(SUM(COLUMN1),0) as total from mytable group by condition
A: Use COALESCE to avoid that outcome.
SELECT COALESCE(SUM(column),0)
FROM table
WHERE ...
To see it in action, please see this sql fiddle: http://www.sqlfiddle.com/#!2/d1542/3/0
More Information:
Given three tables (one with all numbers, one with all nulls, and one with a mixture):
SQL Fiddle
MySQL 5.5.32 Schema Setup:
CREATE TABLE foo
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
val INT
);
INSERT INTO foo (val) VALUES
(null),(1),(null),(2),(null),(3),(null),(4),(null),(5),(null),(6),(null);
CREATE TABLE bar
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
val INT
);
INSERT INTO bar (val) VALUES
(1),(2),(3),(4),(5),(6);
CREATE TABLE baz
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
val INT
);
INSERT INTO baz (val) VALUES
(null),(null),(null),(null),(null),(null);
Query 1:
SELECT 'foo' as table_name,
'mixed null/non-null' as description,
21 as expected_sum,
COALESCE(SUM(val), 0) as actual_sum
FROM foo
UNION ALL
SELECT 'bar' as table_name,
'all non-null' as description,
21 as expected_sum,
COALESCE(SUM(val), 0) as actual_sum
FROM bar
UNION ALL
SELECT 'baz' as table_name,
'all null' as description,
0 as expected_sum,
COALESCE(SUM(val), 0) as actual_sum
FROM baz
Results:
| TABLE_NAME | DESCRIPTION | EXPECTED_SUM | ACTUAL_SUM |
|------------|---------------------|--------------|------------|
| foo | mixed null/non-null | 21 | 21 |
| bar | all non-null | 21 | 21 |
| baz | all null | 0 | 0 |
A: if sum of column is 0 then display empty
select if(sum(column)>0,sum(column),'')
from table
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602271",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "180"
}
|
Q: Sqlite3 INSERT trigger only fire on REPLACE statement even where record already exists? I'm trying out the Sqlite3 REPLACE (INSERT OR REPLACE) command. I like to keep a created datetime (creDT) and an update datetime (updDT). So I created a database and a trigger for INSERT (creDT & updDT) and one for UPDATE (updDT), but each REPLACE (especially the ones where the primary key already exists) ends up with the current time in both creDT and updDT. Does REPLACE DELETE and INSERT instead of UPDATE?
Is this the standard behavior or am I doing something wrong?
def createDbTables(self):
self.sqlCursor.execute("""
CREATE TABLE rfdetector (
sn TEXT PRIMARY KEY,
detector TEXT,
hex TEXT,
updDT DATE,
creDT DATE)
""")
self.sqlCursor.execute("""
CREATE TRIGGER insert_rfdetector_creDT
AFTER INSERT ON rfdetector
BEGIN
UPDATE rfdetector SET creDT = DATETIME('now','localtime') WHERE rowid = new.rowid;
UPDATE rfdetector SET updDT = DATETIME('now','localtime') WHERE rowid = new.rowid;
END;
""")
self.sqlCursor.execute("""
CREATE TRIGGER update_rfdetector_updDT
AFTER UPDATE ON rfdetector
BEGIN
UPDATE rfdetector SET updDT = DATETIME('now','localtime') WHERE rowid = new.rowid;
END;
""")
def insertSql(self, data):
self.sqlCursor.execute(
'REPLACE INTO rfdetector (sn, hex, detector) VALUES (?, ?, ?)',
(data.serialNumber, data.hex, data.detector))
A: Looks like SQLite performs a DELETE then INSERT on REPLACE:
REPLACE
When a UNIQUE constraint violation occurs, the REPLACE
algorithm deletes pre-existing rows that are causing the
constraint violation
prior to inserting or updating the current row and the command
continues executing normally. If a NOT NULL constraint violation
occurs, the REPLACE conflict resolution replaces the NULL value with
the default value for that column, or if the column has no default
value, then the ABORT algorithm is used. If a CHECK constraint
violation occurs, the REPLACE conflict resolution algorithm always
works like ABORT.
from: http://www.sqlite.org/lang_conflict.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: IE runs JavaScript only after pressing F12 I have a strange problem in Internet Explorer with JavaScript. In every browser I did the test the JavaScript is enabled, but it seems to run only after I press the F12, running it in debug mode. And what is more confusing, after starting the IE debugger everything is working as suppose to.
Any ideas what it could be?
A: If you're calling:
console.log('...some text here...');
or any related method of console without having checked if window.console exists, the script will fail silently. Opening the console leads to window.console existing, which allows the script to continue execution.
Add "window.console && " before your calls to console:
window.console && console.log('works');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602277",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Within DIV, Links Are Overlapping After Overflow To A New Line I'm still trying to get the whole jQuery concept down with CSS and such. I'm in the process of trying to make a simple navigation bar in which there's a hidden DIV. I would start with what looks like a start button, which when clicked would set off a toggle() to show or hide the hidden DIV above it, in which case, would make the menu bar appear from the top of the page. MY problem is that I'm trying to make the links set so that they will fill up horizonally, and then when there's no more room, they will fill up underneath making a new row within the DIV. When this happens, they go to a new row, but it's slightly sitting on top of the row above it, and not lined up. If someone can show me how to make this more organized I'd appreciate it, and I'd even be willing to settle for the alternate way of placing them, i.e. Having the links fill up a column and then when it hits the bottom of the div, start a new colum and fill that from top to bottom, etc. I've tried with and without URL's so far, so this is what I currently have:
the HTML:
<div id="hidden-bar">
<ul id="hidden-bar">
<li><a href="##">Admin Menu</a></li>
<li><a href="##">Home</a></li>
<li><a href="##">Report Menu</a></li>
<li><a href="##">Alt. Report Menu</a></li>
<li><a href="##">Summary Menu</a></li>
<li><a href="##">Comparison Menu</a></li>
<li><a href="##">Editor Menu</a></li>
<li><a href="##">Hourly Reports Menu</a></li>
<li><a href="##">Constants Menu</a></li>
</ul>
</div>
<div id="pull-down"></div>
The CSS:
#hidden-bar {
background-color: #323232;
height: 110px;
width: 100%;
display: inline-block;
overflow:auto;
padding-top: 12px;
color: #FFFFFF;
clear:both;
}
#hidden-bar ul {
list-style-type:none;
display:block;
}
#hidden-bar li {
display:inline;
}
#hidden-bar a {
background-color:#AAAAAA;
font:Verdana, Arial, Helvetica, sans-serif;
font-size:12px;
color:#323232;
display:inline;
padding: 5px 10px 5px 10px;
border: 3px solid #000000;
margin-bottom: 4px;
width: 105px;
}
#hidden-bar a:hover {
background-color:#FEFADE
}
#pull-down {
background-image:url('./images/pull_down.jpg');
background-repeat:no-repeat;
height: 20px;
}
the jQuery works so far so I won't include that code, it's basically just an onclick() coded to run a toggle of id="hidden-bar".
A few notes:
*
*This is running within a .cfm file (I use coldfusion primarily, incase this will affect any judgment calls, but that's what I have to use for my job). I mention this incase anything runs into conflict, but so far, a lot of other jquery features have worked just fine so I doubt it being a cfm file is an issue.
*I have all those different Style Sheets because I was just tinkering sometimes without UL/LI tags and sometimes with, so thats why there may be a few of them in there, like one for UL, one for LI, and one for "a" tags.
My problem is that although there are a lot of tuts out there for these jquery nav bars, noone really goes into explaining how to make all the buttons separate and what to do incase of them overlapping each other, or don't explain how the functionality works in concept/english terms. Thanks in advance.
A: your code is a bit overlapping and messy. What you need is a bit of a better understanding of what your CSS is doing. You can achieve your result without using any Javascript.
I simplified your code a bit for you but you can change it later if you want.
First off, you have 2 elements with the ID hidden-bar. So when your stylesheet is rendering the page it's actually assigning the same #hidden-bar style to both your div and the ul underneath it.
What you can do is just remove the ID from the ul and refer to it as a child of the div later.
<div id="hidden-bar">
<ul>
<li><a href="##">Admin Menu</a></li>
...
You can now the div style will be applied through this:
#hidden-bar
{
background-color: #323232;
height: auto;
width: 650px;
float: left;
}
And its child ul will be styled through this:
#hidden-bar ul
{
list-style: none;
float: left;
padding: 0;
margin: 0;
}
Couple things to note here. First of all, div and ul elements are already block-level elements so there is no need to declare them as display: inline-block. Secondly, the ul element defaults to having padding and margins, so you should reset them to 0 before adding content.
The rest of the code looks like this:
#hidden-bar li
{
display: block;
float: left;
margin: 5px 5px;
text-align: center;
width: 120px;
}
#hidden-bar li a
{
background-color: #AAAAAA;
font: Verdana, Arial, Helvetica, sans-serif;
font-size: 12px;
color: #323232;
border: 1px solid #000000;
display: block;
}
#hidden-bar a:hover
{
background-color: #FEFADE;
}
Floating them to the left basically means push everything to the left inside the next parent block element. So in order for this work correctly, all the block elements have to be floated.
li and a elements are inline by default not block, so I specify I want the li's to be block so I can float them.
I set the margin and width properties on the li's rather than the a's since they are the outermost elements. They are all set to 120px because the largest of them fills just about 120px so now they all look the same.
The total width of the menu should be close to a multiple of the amount of menu items you want on it for it to look good. If I want 5 menu items:
5 * (120px width + 5px left margin + 5px right margin)
= 5 * 130px
= 650px total width
If you set the div to be 649px you will get this:
Hopefully that helps clear things up for you and helps you solve your problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602279",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: #import does not protect against circular calls? I have two classes ClassA and Class B (they are viewControllers).
Class A is a delegate of classB.
ClassA "laucnhes" and instance of ClassB.
ClassB call methods on classA.
Let's say it's :
#import "ClassB.h"
@interface ClassA : NSObject {
ClassB* subController;
}
- (void) doThis;
-------------------------------
#import "ClassA.h"
@interface ClassB : NSObject {
ClassA* delegate;
}
-------------------------------
@implementation ClassB
- (void) someMethod {
AnObject* myObj = [self.delegate.arr objectAtIndex:8];
[self.delegate doThis];
}
Doing that way, A must import B, and B must import A.
If B do not import A (with just @class A), there is a compile error for the used attribute from A.
If B imports A, there is a compile error on the ClassA* delegateline.
Why do I have those compile errors? Doesn't #import protect again recursive calls ?
I don't need a solution to solve that problem, I know how I may do this.
But I wonder why my #import cause those problems. These are not #includes...
A: In .h files prefer @class to #import. Both can then be imported in the .m implementation files.
// ClassA.h -------------------------------
@class ClassB;
@interface ClassA : NSObject {
ClassB* subController;
}
- (void) doThis;
// ClassB.h -------------------------------
@class ClassA;
@interface ClassB : NSObject {
ClassA* delegate;
}
// ClassB.m -------------------------------
#import "ClassA.h"
#import "ClassB.h"
@implementation ClassB
- (void) someMethod {
AnObject* myObj = [self.delegate.arr objectAtIndex:8];
[self.delegate doThis];
}
Using @class statements instead of #import also reduces dependencies and makes the remaining ones more clear. It can also speed up compile times.
A:
Why do I have those compile errors? Doesn't #import protect again recursive calls ?
#import protects against repeatedly importing the same header into the same module, whether by circular includes/imports or not. It protects against that by not letting you do it: Only the first #import of a header works; subsequent #imports of the same header are ignored.
In a circular #include situation, the preprocessor would go around the circle some number of times and then fail the build before you even get to compilation. Using #import prevents the preprocessor from getting wedged and lets the preprocessor succeed, but circular-#import code is still dodgy at best and usually will not compile.
So, on to your specific situation.
For the code you showed in your question, @class will work in either or both headers, and indeed you should use it in both. You'll also need to #import both headers in both .m files.
If B do not import A (with just @class A), there is a compile error for the used attribute from A.
If you mean “there is a compile error at each point where I use that attribute of type ClassA *”, then yes: You can't talk to that object because you haven't imported its interface, so the compiler doesn't know what messages you can send to a ClassA instance. That's why you need to import its interface.
If B imports A, there is a compile error on the ClassA* delegateline.
If both headers import each other, then you have this:
ClassA.m:
ClassA.h
ClassB.h
ClassA.h (ignored because this was already imported by ClassA.m)
ClassB.m:
ClassB.h
ClassA.h
ClassB.h (ignored because this was already imported by ClassB.m)
There is no way this can work without one interface preceding the other without the other interface preceding it. That's the circle you're running into—the circle that #import exists to break. #include allows the circle, and thereby gets wedged:
ClassA.m:
ClassA.h
ClassB.h
ClassA.h
ClassB.h
ClassA.h
ClassB.h
ClassA.h
ClassB.h
ClassA.h
ClassB.h
ClassA.h
ClassB.h
(fails at some point)
Hence #import.
So you cannot import each header from the other. Hence @class.
But you still need to import each header from each module. That is, in fact, exactly what you need to do: Use @class in each header and use #import (on both headers) in each module.
A: This compile complaint can be avoided by declaring
@class ClassB;
in the .h file. The ClassB.h can then be included into the .m file.
So you are right on that one. Contrary to urban myth, #imports work pretty much like #includes in the sense that the compiler has to check the file.
See this (duplicate?) question for your philosophical problem.
A: I think you'll find that #import only protects against multiple inclusion once it has already been successfully included once, so to speak.
ie, in your case, it hasn't successfully imported classa.h before it is asked to import it again, so it does so.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Cancel javascript onclick event in FF I have linkbutton with onclick event. I want cancel onclick event in FF dinamically, sometimes user can click, sometime cant click. I want cancel the onclick event in JS function fired from other control(dropdown, textbox). So, I want to write function, when sometimes cancel this event and sometimes dont cancel this event from function fired from another element on the page.
Example:
function someFCE(linkButtonID)
{
var linkButton = document.getElementById(linkButtonID);
if (//firefox//)
{
if (//something//)
//cancel event//
}
}
Where is //cancel event//, please help me write code to cancel this onclick event on FF.
And sorry my english.
If I understand right, I can cancel the event after click on the button. The problem is, the button has other JS validation and it is dangerous rewrite logic of this button. If I add other click event with jquery which cancel this click event, this cancel event calls after this validation. So, is some possibility add cancel event which calls first before all validations or simply cancel onclick event? Only in FF
Thanks.
A: You should add an event listener to the element:
linkButton.onclick = function(ev){
ev.preventDefault();
ev.stopPropagation();
}
The event object is passed as a first argument to an event listener. Methods of the event object can be invoked from within the event listener. preventDefault() prevents the default event from occuring. stopPropagation() cancels the bubble of the event, so that other event listeners don't receive the event any more.
A: If you want to stop the click event from firing, you can set the onclick event of the LinkButton to null:
linkButton.onclick = null;
This will remove the function that was previously there, so when the button is clicked, there is no event handler to be called.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602283",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Class.getResource() returns null in my Eclipse Application? Can't configure classpath? I am trying to use Class.getResource("rsc/my_resource_file.txt") to load a file in an Eclipse application. However, no matter what I do in Eclipse the classpath always contains just one entry to the Eclipse Launcher:
.../eclipse/plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.pkc
How can I configure the classpath?
Note: At runtime I am determining the classpath with the following code:
URLClassLoader cl = (URLClassLoader) ClassLoader.getSystemClassLoader();
for (URL classpathURL : cl.getURLs()) {
System.out.println(classpathURL);
}
EDIT: Further information.
The root of the problem is that Class.getResource("rsc/my_resource_file.txt") is returning null. Having done some small experiments in a simple 5 line "Java Application" I thought I had figured it out and that the problem was related to the classpath. Apparently the classpath behaves a little different with an "Eclipse Application". I solved the problem by doing Class.getResource("/rsc/my_resource_file.txt") Thanks BalusC.
A: Please take a step back. Your concrete problem is that the resource returns null, right? Are you sure that its path is right? As you have, it's relative to the package of the current class. Shouldn't the path start with / to be relative to the package root?
URL resource = getClass().getResource("/rsc/my_resource_file.txt");
// ...
Alternatively, you can also use the context class loader, it's always relative to the classpath (package) root:
ClassLoader loader = Thread.currentThread().getContextClassLoader();
URL resource = loader.getResource("rsc/my_resource_file.txt");
// ...
At least, the Eclipse launcher is not to blame here.
A: Right click on the project and follow the properties.
A: Put the file in the top level directory in your source tree. This is often called "src".
Then, when you build your project the file will be copied into your class directory (name varies). Finally, post build the file will be in your classpath (within the eclipse environment).
Class someClassObject = BlammyClassName.class;
someClassObject.getResource("my_resource_file.txt");
will return a URL to your resource.
someClassObject.getResourceAsStream("my_resource_file.txt");
will return a stream.
Edit: changed such that it does not reference Class methods statically.
A: I've had this problem occur, because the The Bundle-ClassPath setting in Manifest.MF MUST include . (see https://www.eclipse.org/forums/index.php/t/287184/), for instance:
Bundle-ClassPath: .,
test.myapp.core
Bundle-ClassPath is not added automatically by the plugin wizards, so that can cause some problems.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602289",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Integrating Artistic Style with Visual Studio 2010 Is it possible to integrate Artistic Style with Visual Studio 2010? It does a much better job of fixing mangled code indenting and styling than the include visual studio code formatter. Ideally a hotkey or something to apply it to the current file. I know how to apply it by hand but there must be a plugin or something available to help to do it automatically.
A: You can add external tools to the IDE. See the Tools menu. You can have Artistic Style format an entire file for you. It is a bit brittle, because you have to save the file before you run the external command.
You can bind a key stroke to the external command. Look at Tools.ExternalCommandN (where N is 1 to 24) in Tools -> Customize -> Keyboard.
A: Visual Studio supports external tools:
http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=EN-US&k=k%28VS.EXTERNALTOOLS%29&rd=true
Configuring it with $(ItemPath) as Arguments works just fine. You can add other options in front of it like that: -A12 $(ItemPath).
A: There's now an "AStyle Extension" plugin for Visual Studio 2010/2012 that you can download and install via the built-in Visual Studio extension manager (Tools -> Extensions and Updates). It includes a configuration dialog that lets you control all the options.
There's more information on this plugin here:
http://visualstudiogallery.msdn.microsoft.com/2f3f04cd-2866-4e47-a671-d1cc9cc3fb02
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C++ Passing variables into a class to a function I have a class "Month" that has void member functions and void parameter passing. I need to overload the constructor (I think) but the compiler doesn't like my attempts.
class Month
{
public:
Month(char firstLetter, char secondLetter, char thirdLetter); //?
Month::Month(int m) : month(m) {} //Want above ^ to look like this
Month();
void outputMonthNumber();
void outputMonthLetters();
//~Month(); // destructor
private:
int month;
};
void Month::outputMonthNumber()
{
if (month >= 1 && month <= 12)
cout << "Month: " << month << endl;
else
cout << "Not a real month!" << endl;
}
void Month::outputMonthLetters()
{
const char * monthNames[] = {
"Jan","Feb","Mar","Apr","May","Jun",
"Jul","Aug","Sep","Oct","Nov","Dec"
};
const char * output = "The number is not a month!";
if (month >= 1 && month <= 12)
output = monthNames[month - 1];
cout << output;
}
Just like how outputting the month numbers were done, I'm trying to do the same for outputMonthNumber but can't wrap my head around it.
int main(void)
{
int num;
char firstLetter, secondLetter, thirdLetter;
cout << "give me a number between 1 and 12 and I'll tell you the month name: ";
cin >> num;
Month myMonth(num);
myMonth.outputMonthLetters();
cout << endl << "Give me a 3 letter month and I'll give you the month #: ";
cin >> firstLetter >> secondLetter >> thirdLetter;
/*===How would I pass the parameters to the class?===*/
//Month herMonth(firstLetter, secondLetter, thirdLetter);
//herMonth.outputMonthNumber();
}
All member functions of class pass void parameters. I understand how to do it for passing one, but I can't seem to get it to overload correctly.
A: Do it like so:
class Month
{
public:
Month(char firstLetter, char secondLetter, char thirdLetter) :
first(firstLetter),second(secondLetter),third(thirdLetter)
{
const char * monthNames[] = {
"Jan","Feb","Mar","Apr","May","Jun",
"Jul","Aug","Sep","Oct","Nov","Dec"
};
for ( int i = 0 ; i < 12 ; i++ )
if ( monthNames[i][0] == first && monthNames[i][1] == second && monthNames[i][2] == third )
month = i + 1;
}
Month::Month(int m) : month(m) {} //Want above ^ to look like this
Month();
void outputMonthNumber();
void outputMonthLetters();
//~Month(); // destructor
private:
int month;
char first;
char second;
char third;
};
A: You can't initialize month directly from letters, unless you use a function.
Header:
int CharsToInt(char firstLetter, char secondLetter, char thirdLetter);
class Month
{
public:
Month(char firstLetter, char secondLetter, char thirdLetter)
: month(CharsToInt(firstLetter, secondLetter, thirdLetter)) {}
Month(int m) : month(m) {}
Month();
cpp file:
int CharsToInt(char firstLetter, char secondLetter, char thirdLetter)
{
firstLetter= std::tolower(firstLetter);
secondLetter = std::tolower(secondLetter);
thirdLetter = std::tolower(thirdLetter);
unsigned int abr = (firstLetter<<CHAR_BIT<<CHAR_BIT) | (secondLetter<<CHAR_BIT) | thirdLetter;
switch (abr) {
case 'jan': return 1;
case 'feb': return 2;
case 'mar': return 3;
case 'apr': return 4;
case 'may': return 5;
case 'jun': return 6;
case 'jul': return 7;
case 'aug': return 8;
case 'sep': return 9;
case 'oct': return 10;
case 'nov': return 11;
case 'dec': return 12;
default: return -1;
}
}
Since I know there will be doubters, test case for CharsToInt at http://ideone.com/73TNb. As a note, this magic trick will only work on certain processors. You may have to rearrange the letters in abr for some compilers.
A: What you really want is to set the month based on string input, correct? Try this:
Month(const std::string & month_name)
{
static const std::string monthNames[] = {
"Jan","Feb","Mar","Apr","May","Jun",
"Jul","Aug","Sep","Oct","Nov","Dec"
};
month = std::find(monthNames, monthNames + 12, month_name) - monthNames + 1;
}
What, that does, in a nutshell, use std::find to find the passed in name among the array entries. std::find will return a pointer to string, from which we subtract the address of the monthNames array. That gives us a value from 0-11(or 12 if it's not found), to which we add 1.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602298",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Regex to remove last / if it exists as the last character in the string I would like a regular expression or otherwise some method to remove the last character in a string if and only if that character is '/'. How can I do it?
A: string = string.replace(/\/$/, "");
$ marks the end of a string. \/ is a RegExp-escaped /. Combining both = Replace the / at the end of a line.
A: Just to give an alternative:
var str="abc/";
str.substring(0, str.length - +(str.lastIndexOf('/')==str.length-1)); // abc
var str="aabb";
str.substring(0, str.length - +(str.lastIndexOf('/')==str.length-1)); // aabb
This plays off the fact the Number(true) === 1 and Number(false) === 0
A: var str = //something;
if(str[str.length-1] === "/") {
str = str.substring(0, str.length-1);
}
A: var str = "example/";
str = str.replace(/\/$/, '');
A: var t = "example/";
t.replace(/\/$/, ""));
A: This is not regex but could solve your problem
var str = "abc/";
if(str.slice(-1) == "/"){
str = str.slice(0,-1)+ "";
}
A: $('#ssn1').keyup(function() {
var val = this.value.replace(/\D/g, '');
val = val.substr(0,9)
val = val.substr(0,3)+'-'+val.substr(3,2)+'-'+val.substr(5,4)
val = val.replace('--','').replace(/-$/g,'')
this.value = val;
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
}
|
Q: Traversing & changing child key in a multidimentional php array I have an multidimensional array that looks like this:
Array(
[135] => Array(
[150] => Array(
[151] => Array(
[1] => Array()
[153] => Array()
)
[1] => Array(
[1] => Array()
[2] => Array()
)
)
[1] => Array(
[1] => Array(
[1] => Array()
[2] => Array()
)
[2] => Array(
[1] => Array()
[2] => Array()
)
)
)
)
I would like to change to the following:
Array(
[135] => Array(
[150|135] => Array(
[151|150] => Array(
[1|151] => Array()
[153|151] => Array()
)
[1|150] => Array(
[1|1] => Array()
[2|1] => Array()
)
)
[1|135] => Array(
[1|1] => Array(
[1|1] => Array()
[2|1] => Array()
)
[2|1] => Array(
[1|2] => Array()
[2|2] => Array()
)
)
)
)
I mean each child key will have his key | parent key format. Tree label is fixed. No more or less depth than shown in the above code.
What is the best way to do this? Thank you for any assistance
A: Try this:
$arr = Array ( [135] => Array ( [150] => Array ( [151] => Array ( [1] => Array ( )))));
foreach($arr as $key1 => $value1)
{
if(is_array($value1))
{
foreach($value1 as $key2 => $value2)
{
if(is_array($value2))
{
foreach($value2 as $key3 => $value3)
{
if(is_array($value3))
{
foreach($value3 as $key4 => $value4)
{
if(is_array($value4))
{
foreach($value4 as $key5 => $value5)
{
$value4[$key5.'|'.$key4] = $value5;
unset($value4[$key5]);
}
}
else
{
$value3[$key4.'|'.$key3] = $value4;
unset($value3[$key4]);
}
}
}
else
{
$value2[$key3.'|'.$key2] = $value3;
unset($value2[$key3]);
}
}
}
else
{
$value1[$key2.'|'.$key1] = $value2;
unset($value1[$key2]);
}
}
}
}
I think this can give you some idea but i have not tested this so i am not very sure about the correctness.
A: There's no need for crazy nested foreach() loops to solve this. Recursion is your friend:
function get_fancy_array($arr, $parent_id=null) {
$fancy_arr = array();
// turn e.g. 'parent' or 'parent|child' into '|parent' and NULL into ''
$parent_id_sufx = $parent_id === null ?
'' : '|' . explode('|', (strint)$parent_id, 1)[0];
foreach($arr as $key => $val) {
$key = (string)$key . $parent_id_sufx;
if( is_array($val) ) {
// it's an array, so recursively do the same thing at the next level
$fancy_array[$key] = get_fancy_arr($val, $key);
} else {
$fancy_array[$key] = $val;
}
}
return $fancy_arr;
}
// Usage:
$arr = array( /* your big nested array here */ );
$fancier_arr = get_fancy_array($arr);
print_r($fancier_arr);
A: You can exactly do like you asked: Traverse and change keys (Demo):
/**
* traverse array and
* add parent key to children key
*
* @param array $a (return)
* @param int $p (optional) parent key
*/
function changeKeys(array &$a, $p = null)
{
static $f = __FUNCTION__;
foreach($a as $k => &$v)
{
# test if already processed
if (is_string($k))
return;
# traverse children if children exists
if ($v)
$f($v, $k);
# rename key if parent exists
if ($p)
{
$a["$k|$p"] = &$v;
unset($a[$k]);
}
}
}
This function traverses with recursion (the function calls itself) so it can operate on multiple levels all the same.
Changing array keys is actually not really possible, there is not function like array_rename_key or such. Instead, the item with the new key is added and then the item with the old key is removed. To not duplicate values, a reference/alias is used for this in the example above:
$a["$k|$p"] = &$v;
unset($a[$k]);
$a is the array, $v is the value of the current element, $k the key and $p the parent's key.
As new elements are added at the end of the array, inside the foreach a check is needed to quit if a key has been already processed (it's a new key, all new keys are strings).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to store values in the database for a complex shopping cart I'm working on a shopping cart with a little bit complex way of storing products in cart.
For each product that a user can add in cart there is a table like this:
In this table the user enters the quantity for the specified size and color. What would be the best way to store this values in a database table so that I can easily get and display them later?
I'm using PHP and a MySQL database.
Now my table looks like bellow but I'm having trouble getting the values when someone requests more than one size per color.
CREATE TABLE IF NOT EXISTS `site_platform_cart` (
`cart_id` int(10) unsigned NOT NULL auto_increment,
`cart_product_id` int(10) unsigned NOT NULL,
`cart_product_name` varchar(256) collate latin1_general_ci NOT NULL,
`cart_product_photo` varchar(256) collate latin1_general_ci NOT NULL,
`cart_product_color_name` varchar(128) collate latin1_general_ci NOT NULL,
`cart_product_color_image` varchar(128) collate latin1_general_ci NOT NULL,
`cart_product_color` tinyint(4) NOT NULL,
`cart_product_size` tinyint(2) NOT NULL,
`cart_product_quantity` tinyint(3) unsigned NOT NULL,
`cart_product_price` varchar(12) collate latin1_general_ci NOT NULL,
`cart_date` date NOT NULL,
`cart_user_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`cart_id`)
) ENGINE=MyISAM
Thank you.
A: This is what I would do:
Add a new row in the database for each Color/Size combination. So something like this:
INSERT INTO chart (user_id,item_id,color,size,quantity,cart_date) VALUES (.....
You could also, which might be a better idea, add the Chart items in the $_SESSION. This way your database isn't getting polluted
A: I would normalize this data in the database as pairs. Have a column for the user, the product, the color, the size, and the quantity ordered. Each square on the UI you posted would be a row in the database.
That would be flexible as you could easily add more products, colors, sizes, etc. Querying for a user, a product, colors, etc would all be very easy.
A: Your cart is nothing more than a representation of a sales order, and you should remember this. You need two tables (at minimum) to represent a sales order: one containing information on the overall order, the other containing information on all of the lines of the order.
Hopefully you have some kind of an 'Items' table, and hopefully each item key is different for each color/size combination (in other words, each color/size combo is a separate product).
If it is, simply store the item number and quantity in the line table for the order as you would in any other store.
A: There is no best way. I would use a table that stores all possible colors. A second table to store all possible sizes. A third order table would contain quantities and references to the size and color tables.
A: Okay, I'm going to put in my two cents' worth after deliberating over exactly what you are trying to achieve here.
The most pressing problem, I think, is the way you've designed the database. I had to deal with a similar problem before, and what was finally used as a solution was something like this:
table: Colours
ColourID* | ColourDescription
table: Sizes
SizeID* | SizeDescription
table: GenericItem
GenericID* | Item Description | Price | Etc
table: Item
ItemID* | ParentItem | SizeID | ColourID | AvailableStock | Etc
The Colours and Sizes tables store every size and colour that is available within your produt range. The GenericItem table stores each product you stock. For example, a Joe Bloggs V-Neck T-Shirt. Finally, the Item table stores each unique item - eg: Large Red Joe Bloggs V-Neck T-Shirt. You give it a unique item ID, and can easily reference the additional information from the GenericItem table.
Now, in terms of the cart, you can have tables like such:
table: Cart
CartID* | CartUserID | CartDate | Etc
This table would hold the information for each specific cart. And now, expanding on Topener's answer, you would separately hold information for each cart line:
table: CartLine
CartLineID* | CartID | ItemID | Quantity | Etc
This way, you an keep your data much more normalised and easily accessible, and allows you to store each cart in the database.
To retrieve this data, all you would need to do is store the CartID inside the $_session and have all your queries stem from that. For example, to reshow order lines: SELECT * FROM CartLine WHERE CartID = $_SESSION['CartID']
To display the grid now, all you need to do is create an array based around something like SELECT * FROM Item WHERE ParentItem = 'GenericID'. In this example, I assume that you have the generic item's ID already as a variable somewhere to display all the information about it on the page. Then, you can use the information there to map each textbox to an index of the array.
Hopefully, this will point you in the right direction.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Facebook settings for posting music to Timeline I'm working on an app to post music to the Facebook timeline, but having problems when I POST as recommended in the doc. I use OAuth 2 to successfully get the user's Facebook ID and a valid session_token, but then, when I post this...
POST https://graph.facebook.com/<user_id>/music.listens?song=<song's URL>&expires_in=<seconds>&access_token=<session_token>
I get the following error message back from Facebook:
{\"error\":{\"message\":\"An unexpected error has occurred. Please retry your request later.\",\"type\":\"OAuthException\"
So far...
*
*I've ruled out invalid and expired tokens.
*I'm requesting (and receiving) multiple permissions, including publish_checkins, publish_stream, user_likes, friends_likes, and create_event.
*I've set up all of my metatags according to the Facbook's OpenGraph music documentation.
At this point, it seems that all of the permissions, tokens, etc. are in order. Are there some Application settings (possibly related to the "og" namespace) that need to be set? Other permissions that need to be requested?
A: You need to be whitelisted to use that feature (per the intro in the OG Music doc). To apply to be whitelisted, follow the instructions in the Open Graph Builtin Actions docs. Hope that helps!
A: I'm not experienced enough to give you good answers, but I can tell you how I dealt with my oauth errors and see if they're of any help to you.
*
*One of my errors came from when after I initialized the app (javascript sdk). I tried to post to timeline before facebook had completed the initialization and authorizationn process. I then edited the my post to timeline function to wait until facebook had responded before executing.
*My other errors were from silly mistakes where I hadn't properly defined the actions and objects in my application settings yet. I didn't check the advanced options in the action type and object settings to find the exact url the objects resided in.
*Does your url have & signs in them? The api seems to treat & signs as parameter separators. In my urls, I replaced &variable= with :variable= and reseparated the url parameters afterwards to ensure my parameters didn't get cut off.
Hope at least some of that was helpful.
A: Have you run the Facebook Debugger?
(they just changed the name & URL)
http://developers.facebook.com/tools/debug
Just paste your URL (or Access Token) in the field and click "Debug". It doesn't find all issues but it will point out any obvious problems and explains how to fix them.
If you don't see your problem/fix there, let us know!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602310",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Why can't I install plugin for android development in netbeans? I'm using netbeans 6.7.1.
I followed the instructions from here to install the plugin for android development.
I've riched into the step where I should choose 'Android' in “Availalble Plugins” tab,and then get into the installation,and get an error list of other plug in's that are not updated enoughf for the android.
Are you familiar with it?
Can I download & install only these I missing,or should I download Netbeans in a more progress version??
Thanks!!
Izabela
A: Open plugin manager. To do this go to Tools | Plugins. Here you need to navigate to Settings tab and add an address of our update center that is
http://nbandroid.org/updates/updates.xml if you use NetBeans version 7.3 - 8.0
http://nbandroid.org/release81/updates/updates.xml if you use NetBeans 8.1 (or newer)
Previous update center hosted at kenai.com site is removed now as it caused confusion about current version and what is supported and what not.
Obviously your version 6.7.1 is not supported and you have to upgrade your netbeans too.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602315",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Name/UID on page tab without authentication? I had previously thought there was no way to get a user's information, specifically their userid, without first getting them to authenticate your app. I see that this page, however, does that on a custom page tab:
http://www.facebook.com/AutoCADWS?sk=app_4949752878
Not only does this page tab get the viewing user's name, but it also gets their profile url, which includes their userid. How do they accomplish this without authentication? If this is possible, could someone point me to example code where I can see just how it implement it on my own page tabs?
A: The page you linked to uses FBML, which is no longer available for new Apps.
So, there is no way to do this without user authorization.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602320",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Ninject working with WCF Web API Preview 5 Can anybody point me in the right direction to get Ninject working with WCF Web API Preview 5? I have it successfully up and running in my ASP.NET MVC 3 project and also in another internal WCF Service using the Ninject.Extensions.Wcf library. However I cannot get it to work when creating a new MVC 3 project and getting the WebApi.All library from NuGet.
I have looked at this stackoverflow post Setting up Ninject with the new WCF Web API but cannot get it working which I believe could be to do with some of the changes in the latest release.
I am also unsure which Ninject Libraries to reference beyond the main one. Do I use the Ninject.MVC3 , Ninject.Extensions.Wcf.
Any help on this would be much appreciated.
****UPDATE**
Code I am using which is from the answer in the question mentioned above. I have this in its own class file.
public class NinjectResourceFactory : IResourceFactory
{
private readonly IKernel _kernel;
public NinjectResourceFactory(IKernel kernel)
{
_kernel = kernel;
}
public object GetInstance(Type serviceType, InstanceContext instanceContext, HttpRequestMessage request)
{
return _kernel.Get(serviceType);
}
public void ReleaseInstance(InstanceContext instanceContext, object service)
{
// no op
}
}
This I have in my global.asax:
var configuration = HttpConfiguration.Create().SetResourceFactory(new NinjectResourceFactory());
RouteTable.Routes.MapServiceRoute<myResource>("resource", configuration);
The issue I am having is that the IResourceFactory interface is not recognised and that the HttpConfiguration.Create() no longer exists so I need to set the SetResourceFactory some other way which I have tried to do using the HttpConfiguration().CreateInstance method but no joy.
A: Following is my code with Ninject and WebApi,it works.
Create a class inherites from WebApiConfiguration
public class NinjectWebApiConfiguration : WebApiConfiguration {
private IKernel kernel = new StandardKernel();
public NinjectWebApiConfiguration() {
AddBindings();
CreateInstance = (serviceType, context, request) => kernel.Get(serviceType);
}
private void AddBindings() {
kernel.Bind<IProductRepository>().To<MockProductRepository>();
}
}
and use the NinjectWebApiConfiguration in RegisterRoutes
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
var config = new NinjectWebApiConfiguration() {
EnableTestClient = true
};
routes.MapServiceRoute<ContactsApi>("api/contacts", config);
}
A: In P5 you have to derive from WebApiConfiguration and use your derived configuration:
public class NinjectConfiguration : WebApiConfiguration
{
public NinjectConfiguration(IKernel kernel)
{
CreateInstance((t, i, m) =>
{
return kernel.Get(t);
});
}
}
A: There are great answers to the question here but I would like to show you the way with default WebApi configuration:
protected void Application_Start(object sender, EventArgs e) {
RouteTable.Routes.SetDefaultHttpConfiguration(new Microsoft.ApplicationServer.Http.WebApiConfiguration() {
CreateInstance = (serviceType, context, request) => GetKernel().Get(serviceType)
});
RouteTable.Routes.MapServiceRoute<People.PeopleApi>("Api/People");
}
private IKernel GetKernel() {
IKernel kernel = new StandardKernel();
kernel.Bind<People.Infrastructure.IPeopleRepository>().
To<People.Models.PeopleRepository>();
return kernel;
}
The below blog post talks a little bit about Ninject integration on WCF Web API:
http://www.tugberkugurlu.com/archive/introduction-to-wcf-web-api-new-rest-face-ofnet
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602327",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Get filtered result from BindingSource to table/dataset? I'm using a BindingSource connected to a DataGridView to filter the data shown.
I would like to know what is the best way to get the filtered result to some other thing than a GridView?
I ask this as I would like to use the filtered result for a few ComboBoxes. Right now I populate these by the DataTable that gets filtered by the BindingSource.
So in short, how do I get filtered BindingSource result as source for something else than a DataGridView?
A: Actually I believe I finally found a solution.
sourceDataTable.DefaultView.RowFilter = bindingSource.Filter;
DataTable destinationDataTable = sourceDataTable.DefaultView.ToTable();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602328",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: how to remove jar from Maven Dependencies in eclipse I am trying to get rid of a jar from my Maven Dependencies folder which is automatically generated in eclipse. As this folder is not editable, I tried deleting the corresponding jar manually from .m2/repository and also removed the jar from my pom file and refreshed eclipse project. But no impact. Jar continues to stay in dependencies folder in eclipse. Then, I re-started my laptop. now jar is re-populated in .m2/repository and of course its in maven dependencies folder in eclipse as well. any suggestions.
A: If the jar is a dependency of another library you have included in your POM then you may have to exclude that library in the POM. The spring framework must have some kind of logging but if you do not want to use apache commons logging and would rather use something else you must exclude the offending library:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
commons-logging-1.1.1.jar will nolonger litter my maven dependencies.
One thing to note is that you must exclude it from every dependency that requires it (e.g. if you have spring-context and spring-core in your pom you must put the <exclusions> section in each <dependency></dependency>).
Eclipse m2 plugin has a nifty little extension that allows you to right click on the jar then select Maven -> Exclude Maven artifact...
A: I have the same problem and figured out how to do it.
*
*If you are not using that JAR file, you can:
*
*Right-click on the project
*Choose [delete]
*Do NOT check "Delete project contents on disk"
*Click OK
*Wait for it to complete
*Import your project to your workspace again (Existing Maven Projects)
Now the unused JAR files are gone.
*If you are using (part of) that JAR file, you can do as tribeca said.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602334",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: How (can) I access the Microphone on the iOS the way Google Voice does? Apple hasn't approved Google Voice as an App so Google created a web "app". So somehow they are accessing the microphone thru the browser. The browser doesn't have access to the Mic so I'm wondering how they (and thus I) did that.
Only thing I can think of is something like PhoneGap or Titanium.
A: It's not possible to access the microphone or the camera from a web app running within Safari on iOS. It may be possible in a few years once the W3C finalizes HTML5, but it's a long way off. I believe Google Voice's servers actually call your phone and then the audio runs over your phone's voice connection.
If you're willing to make yourself a minimal native app, there is a solution that will let you do most everything as a web app, using native code only for the audio-related stuff:
*
*Create your app as a web app. Design and build everything so it looks great in Safari on the iPad.
*Create a new native app that will act as a shell for your website. It can just be a very basic Objective-C app with a web view in it.
*When your web app needs to open up an audio recording interface, make it request an url (via javascript or via the user clicking a link) like this one:
startaudio://whatever-variables-you-need-to-pass
*Implement the UIWebView delegate function webView:shouldLoadRequest: in your Objective-C code. Check each URI that the web view tries to load and intercept your custom "startaudio://" url. At this point, your app would bring up the audio interface in native Objective-C, perhaps over top of the website view.
*Upload recorded audio data to your server in Objective-C (probably) and then use [webView executeJavascript: ] to tell the browser that the audio recorder has been dismissed.
Hope that helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: JAX-B is marshalling everything I have a class with an @XmlRootElement(name="objectName",namespace="https:blahblah") and some attributes in the class all with @XmlElement(namespace="https:blahblah")
But now I have some element without an XmlElement annotation. Why is it also marshalled?
I only want to marshal annotated attributes.
Code looks like this:
JAXBContext jc = JAXBContext.newInstance(SomeClass.class);
Marshaller m = jc.createMarshaller();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document doc = dbf.newDocumentBuilder().newDocument();
m.marshal(someInstanceOfSomeClass, doc );
A: Make the attributes you don't want to marshal either transient or annotate them with @XmlTransient. As for the exact why I refer you to the specification.
A: JAXB is configuration by exception, this means that it has default rules for converting Java objects to XML. You only need to supply metadata where you need to override the default rules, this greatly reduces the amount of configuration that must be done.
*
*http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted/TheBasics
You can specify @XmlAccessorType(XmlAccessType.NONE) so that only the annotated fields/properties are marshalled.
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class Root {
@XmlElement
private String foo; // Will be marshalled
private String bar; // Will not be marshalled
}
For More Information
*
*http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602338",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Does MASM change instructions behind your back? I was surprised by the following when reading the HLA faq:
MASM has a nasty habit of changing instructions behind your
back. HLA also seems to have this same problem.
I then searched the web but found nothing regarding this. Is it true or just a myth?
A: MASM can change things on you. For example, it can fix your conditional jumps. That is if you write:
add ax,bx
jnz NotZero
...
NotZero:
If NotZero is outside the range of a conditional jump, MASM can rewrite your code as:
add ax,bx
jz Zero
jmp NotZero
Zero:
...
NotZero:
As I recall, there are command line switches to prevent that. You can also specifically say, jnz near NotZero to prevent it. If you do that and the target is outside the range of the conditional, you'll get an error.
I recall that MASM did some other, similar, things, but it's been a very long time. I don't recall what those specific things were.
A: This probably is not what you're looking for, but I've experienced cases where MASM doesn't produce the same output for the same input as other similar assemblers (NASM, for example). That is, a slightly different byte-sequence that disassembles to the same thing.
Typically, it's not an issue at all though, and the only reason I even noticed it was because of a weird case that I needed certain bits in the instruction to be a particular value; with one assembler it was fine, and with the other, it wasn't and I had to apply manual fix-ups.
Hope that helps.
A: It's kind of half-true. Some instructions can be encoded in more than one way, and at times (for reasons they've never explained) Microsoft has changed how they encode a few particular instructions.
Since version 6, it's also had a multi-pass mode that can/will encode jumps using the smallest form of a jump that will "reach" the destination. Up through 5.x, you had to manually specify near vs. far jumps, and if you guessed wrong, on the second pass it would produce a "phase error". Starting with v6, it'll automatically adjust the size. Since that changes the size of the instruction, that can force other surrounding jumps to change as well (and, likewise, in the other direction, a smaller encoding for a jump may reduce code size that another jump could reach it's destination with a smaller encoding).
This is not, however, a "nasty habit" from most people's perspective -- quite the contrary, most people rather like it to automatically encode the instructions as efficiently as possible. There are a few cases (e.g., self-modifying code) where you need to prevent it, but those are the ones that usually qualify as "nasty habits" (at least if you really do them habitually).
A: I think this "changing" is about instruction scheduling and peep-hole optimizations. You can escape this when you write your code with "cat >pgm.o".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: VC++ Project, want to compile within another IDE but something is missing I am fairly new to C++.
I want to write plugins for an application called Cinema 4D.
Maxon, the maker of C4D, provides an API for doing this. The header-files are located in a special folder.
The "cinema4dskd" is a Visual Studio project containing sample plugins. Within this project there is another subproject called _api .
The popupwindow is the "Project dependencies" dialog.
The _api sub project seems to be a link to a file that is present on my localdrive but it is not within the cinema4dsdk.vcproj.
All files within the _api project are located in a folder in the Cinema 4D installation path also called _api.
It is full of header and .cpp files.
This is basically what I need to compile plugins for Cinema 4D, including "c4d.h" in my source code.
But this is where the problems start.
I'm trying to compile a plugin within Code::Blocks, I have added all paths to "c4d.h", etc. But every compiler (gcc, and even msvc !) tell me thousands of warnings about:
C:\Programs\MAXON\Cinema 4D R12\resource\_api\ge_prepass.h |2668|warning: multi-character character constant|
And finally an error that C4DGLuint isn't declared. Why does it work in VC++ but not with any other compiler ? I must have missed something, but I really don't know what.
I don't think I am allowed to share this project, as the _api is owned by Maxon GmbH, but if you really need it I beg you to download the Cinema 4D Demo version where the cinema4dskd project is included.
Tell me if you need any further information, I hope you have an idea what may be missing. Why the heck can VC++ compile the Plugins right, but I can't using the command-line or any other IDE ?
Thank you very much.
Niklas
Updates:
Example of multicharacter constant error:
C:\Users\niklas\Documents\CodeBlocks\Cinema4D\_api\src\gui.h|690|warning: multi-character character constant|
C:\Users\niklas\Documents\CodeBlocks\Cinema4D\_api\src\gui.h|693|warning: multi-character character constant|
690: BFM_SETVIEWPORTORIGIN = 'cORG',
691: BFM_SETVIEWPORTORIGIN_X=1,
692: BFM_SETVIEWPORTORIGIN_Y=2,
693: BFM_SETVIEWPORTSIZE = 'cSIZ',
A: 'cORG'
is a so-called multi character literal. Its value does not fit into a char variable, you will need an 'int' to hold it, and according to this post
C++ multicharacter literal
it is compiler-specific how this thing is interpreted. Seems the other compiler you have tested does not support those kind of literals.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602341",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Rails Delete Resource Identifier on Redirect I have a project using jQuery Mobile (uses resource identifier heavily) with Facebook authentication. Recently Facebook started adding #_=_ to callbacks (see here). This is killing jQuery Mobile.
Is it possible to do an automatic redirect for any routes matching #_=_ to the stripped counterpart? Is it possible to specify a resource identifier (#) when doing a redirect to? Any other possible fixes? I currently use a javascript redirect but this causes duplicate page loads and issues with some of the analytics.
A: Added in the following work around until Facebook fixes it (seems to work):
# app/controllers/omniauth_controller.rb
def create
...
js_redirect_to(user_path)
end
private
def js_redirect_to(path)
@location = path
render "shared/redirect"
end
# app/views/shared/redirect.html.haml
:javascript
window.location = '#{@location}'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Add custom fields to shopping cart display - Ubercart 3 I have Drupal 7 and UC 3 running with custom fields. I want to be able to display those fields in the shopping cart but can't seems to be able to do it. That's my first module creation attempt!
I try to use hook_form_alter(&$form, &$form_state, $form_id) {} in a custom module:
function swcart_form_alter(&$form, &$form_state, $form_id) {
switch($form_id) {
case 'uc_cart_view_form':
// Adding Grade column
$form['items']['#columns']['grade'] = array('cell' => 'Grade', 'weight' => 3.5);
for($i=0; $i < count($form['items']); $i++) {
if(isset($form['items'][$i]['nid'])) {
// Loading the node so we can retrieve the information we need.
$product = node_load($form['items'][$i]['nid']['#value']);
// Adding the 'Grade' to the product that is in the user's cart.
$form['items'][$i]['grade']['#value'] = $product -> field_product_term_data;
}
}
break;
}
}
The column 'Grade' shows up but no data in the table. What should I do? Do I have to modify the TAPir table? hook an other uc_cart function?
Thanks
A: This two links of Ubercart 3 API should help:
hook_tapir_table_alter
uc_cart_view_table
In the first link there's an example for adding column with data.
EDIT: Finished up with adding price per 1 product column by using such code. Hope this will help someone to overcome ubercart's inflexibility.
function YOUR_MODULE_NAME_form_uc_cart_view_form_alter(&$form, &$form_state) {
$form['items']['#columns']['remove']['weight'] = 6;
$form['items']['#columns']['total']['weight'] = 5;
$form['items']['#columns']['qty']['weight'] = 4;
$form['items']['#columns']['price'] = array(
'cell' => t('Price'),
'weight' => 3,
);
}
function YOUR_MODULE_NAME_tapir_table_alter(&$table, $table_id) {
if ($table_id == 'uc_cart_view_table') {
foreach (element_children($table) as $key) {
if (!empty($table['#parameters'][1][$key]['nid'])) {
$node = node_load($table['#parameters'][1][$key]['nid']['#value']);
$table[$key]['price'] = array(
'#markup' => theme('uc_product_price',array('element' => array('#value' => $node->sell_price))),
);
}
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602347",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: click events on nested list items each with their own click handler I have nested unordered lists and click handlers on each li element. When clicking on a nested li, it's firing both events. Is there anyway to prevent this behavior?
<ul>
<li>thundercats
<ul>
<li>panthero</li>
<li>cheetarah</li>
</ul>
</li>
</ul>
So in the above list clicking "thundercats" would fire one event setting a value to "thundercats", clicking on panthero would fire another event setting a value to panthero.
Unfortunately clicking panthero causes the value to be set properly for an instant and then the click handler on thundercats fires and overwrites the value. Is there a way to prevent that?
A: You need to use event.stopPropagation. This will keep the click event from bubbling up the DOM tree.
$(document).ready( function () {
$('li').click(function (evt) {
// Your code here
// Stop the event propagation
evt.stopPropagation();
})
});
A: One option is to prevent the event bubbling up the DOM tree. This will work, but it's not optimal because sometimes event bubbling is very useful. It's nicer to check to see if the event originated on the correct element:
$('li').click(function(event) {
if (this === event.target) {
// do your code
}
});
This code works because this and event.target both point to DOM elements. this is the element where the event handler is handled (where the code is run) while event.target is the element where the event originated, i.e. the element that was clicked. If they are the same element, the event was triggered on the same element as where it is being handled; this is where you want the code to be run, and nowhere else. Comparing the elements with === accomplishes this.
A: It should be as simple as adding:
return false;
...to your event handler function.
When an event handler returns false, it stops event propagation (it's effectively the same as calling .preventDefault() and .stopPropagation() on the event object). It'd definitely be helpful to see your code, but it sounds like this will do it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Batched queries with SQL Server Compact 4.0 and alternatives if unsupported? I'm trying to execute a query which contains "batched" commands, and supposedly this wasn't supported by Compact 3.5, however I want to avoid using SQL Express or a bigger solution that makes deployment on desktops cumbersome.
For example:
String query = String.Format("SELECT * FROM [Mytable] WHERE [Id] = 2; DROP TABLE...");
SqlCeCommand cmd= new SqlCeCommand(query , db.Connection);
The application is a testbed for common .NET secure development problems, so I need to support batched queries in order to support SQL injection issues. Funny as it gets, I can't just roll a huge deployment burden for an entire class of students and make each one of them install SQL Server Express.
Any comments appreciated!
A: Unsupported... I moved the code base to SQLite3. Works like a charm. Considering it's public domain I would recommend people using Compact to ditch it for SQLite!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Events not passed to toolbar button when there is a popup over it - Firefox add-on I am having a toolbar button inside a box. And a panel as well inside the same box.
<box>
<panel />
<toolbarbutton />
</box>
When mouseover event is triggered for the toolbarbutton, I am showing the panel using openPopup method below the toolbar button.
The problem is when the panel is visible and try to click on the toolbar button, the panel is closed. But, the event is not getting propagated further. I need to click the toolbarbutton.
I tried adding allowevents="true" to the panel element. It is not working.
A: If you are opening it on mouseover event then it is probably a tooltip rather than a real panel - and you want tooltip behavior for it. So it makes sense to actually use the <tooltip> widget instead of <panel> (didn't test but I think that it should give you the behavior you are looking for). The API is pretty much the same for both.
A: Use noautohide. Set it to true.
Here is the link
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Sending broadcast from service while bound Ok so I have a simple Android app that I want it to go through all of my pictures and set a random one to the background of an activity (linear layout). I have a service that give a url when a certain function (getUrl()) is called from the bound service class.
I would now like to create a loop within the service (my idea open to better ones) and every n seconds broadcast a message with the new url for the photo. Then I want to use a listener inside the activity to receive the message from the broadcast receiver and change the background image.
I am having some real trouble trying to figure out how to broadcast from within the impl innerclass of the service. Do I just have to use a synchronous service or something?
A: use the way
Intent mintent = new Intent();
mintent.setAction("com.action");
mintent.putExtra("url", "yourURl);
sendBroadcast(mintent);
register the same action in your main activity and in the receiver use handler to update the UI or what ever
if you get any sort of run time error in context then make a global context by extending the Application class and define the getMyContext(); which you will access in service to send broadcast like the
getMyContext().sendBroadcast(mintent)
A: I solved this through the use of Broadcast Receivers and broadcasts. I broadcast from the Picture service and listen for that broadcast on the other service.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602359",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to find all the php files under current directory and add a line How do you do that in terminal or anywhere else?
echo "//test comment" > find . -type f -name "*.js"
doesn't work. I just want to add a line on top of each .js files. Thanks.
A: #!/bin/bash
echo "//test comment" > myline
for file in *.js; do
cp myline dummy
cat $file >> dummy
cp dummy $file
done
or:
#!/bin/bash
for file in *.js; do
sed -i '1i //test comment' $file
done
A: Try something like this:
find . -type f -name "*.js" -exec echo >> {} \;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602365",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I create test plans using Microsoft Test Manager / Visual Studio 2010 Ultimate? They keep on being removed on creation One of my colleagues is facing an issue with creating a test plan using Microsoft Test Manager 2010. We are using TFS 2010 and Visual Studio Ultimate. He is able to successfully "create" the test plan, but as soon as he is done, the test plan is removed. If he refreshes, then the test plan disappears and if he attempts to click on it, he gets the following error -
The test plan has been removed
The test plan you tried to connect to has been removed, please select another plan to connect to.
I made sure he has the correct access rights to Manage Test Plans within the Areas and Iterations security. One thing that concerns me, however, is if I try to see the ACL for this from TfsSecurity.exe, nothing comes up. I have made sure the URI of the project is accurate as well. The command I am using is:
tfssecurity /acl CSS
--> $PROJECT:vstfs:///Classification/TeamProject/11ebab88-2892-4c85-b650-83720f194c21
--> /Collection:[our collection address]
No results are returned from this command, which concerns me because I am able to see some security settings for the Area level from within Visual Studio.
Any ideas what could be happening?
A: I figured it out - you need both 'Manage Test Plans' and 'View this Node' in order to actually manage the test plans. Only having one of the rights will either allow you to create new test plans or view existing test plans, depending on which right you have. The combination of the two allows you to create, edit, view, and delete test plans.
It is kind of counter-intuitive, especially since the description of the 'View this node' right is "Users who have this permission can view the security settings for this node."
The "View this Node" permission in TFS 2010 has changed to "View permissions for this node" in TFS 2012.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Active Record accepts nested attributes for - creating record with overridden class_name When I save the form (last piece of code shown here) I get an error saying: unknown attribute: person
I'm thinking this is because I have overridden the class name of the administrator attribute.
Any ideas?
class Event < ActiveRecord::Base
#start_date, end_date, title
has_one :administrator, :class_name => "Person"
has_one :account_manager, :class_name => "Person"
accepts_nested_attributes_for :administrator
end
class Person < ActiveRecord::Base
#fname, lname, bday
belongs_to :event
end
event_controller#new
@event = Event.new
@event.build_administrator
event_controller#create
@event = Event.new(params[:event])
#=> unknown attribute: person
view
<%= form_for @event do |f| %>
<%= f.text_field.title %>
<%= f.fields_for :administrator do |administrator| %>
<%= administrator.text_field :lname %>
<% end %>
<%= f.submit "Save" %>
<% end %>
I also notice that the field is generated with a name of event[person][lname] which will be a problem as event will need to accept nested attributes for account_manager
A: Edit: Came across this, and I think it's the more proper way to do it.
<%= form_for @event do |f| %>
<%= f.text_field.title %>
<%= f.fields_for @event.administrator, :administrator_attributes do |administrator| %>
<%= administrator.text_field :lname %>
<% end %>
<%= f.submit "Save" %>
<% end %>
Less proper way, but works well:
class EventsController < ApplicationController
before_filter :fix_administrator_attribs, :only => [:create, :update]
# ...
protected
def fix_administrator_attribs
if params[:event][administrator]
administrator = params[:event][:administrator]
params[:event].delete(:administrator)
params[:event].update({:administrator_attributes => administrator})
end
end
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602367",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery mouseleave trigger on every pixel, when flash movie is below div I have a problem with a flash movie, that is initated below a div element with z-index: 2000;. I have a onMouseDown event, on the div - which is triggering fine, and I have $(divelement).hover(functionIn(),functionOut()) attached. (The onClick event is captured by the underlying flash regardless of z-index)
In FF and IE9 this is all working as expected, but in IE8 the functionOut() and functionIn() is triggered on every pixel! What's a good way to fix this?
Possible to add some sort of pixel boundaries based on the element size and position to aid .hover() ?
A: I found a fix for this now. By using a 1px transparent gif as background on the overlaying div, the mouseleave isn't triggered until it actually should be :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602369",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Combine two tables by column should be easy:
I have two tables:
table 1
ID NAME NEWID
1 DOG
2 CAT
3 HORSE
table 2
NAME ID
DOG 100
CAT 200
Horse 300
I need the result to be as follows:
ID NAME NEWID
1 DOG 100
2 CAT 200
3 HORSE 300
My thoughts are:
Update table1
set NewId = (select ID from table2 where Id =NewID)
it says: Invalid column name NewId
A: Because this is a fairly basic and oft-seen question, I assume you are new to the SQL Server product with affect from its 2008 R2 version.
I encourage you not to seek to write new code using the proprietary UPDATE..FROM syntax, arguably only retained in the product to remain compatible with legacy code.
Also note the UPDATE..FROM syntax can cause unexpected and unpredictable behaviour. e.g. if your table2 contained a second row for HORSE with a different ID value e.g.
CREATE TABLE table1 (ID INTEGER, NAME VARCHAR(10), NEWID INTEGER);
CREATE TABLE table2 (NAME VARCHAR(10), ID INTEGER);
INSERT INTO table1 VALUES (1, 'DOG', NULL),
(2, 'CAT', NULL),
(3, 'HORSE', NULL);
INSERT INTO table2 VALUES ('DOG', 100),
('CAT', 200),
('HORSE', 300),
('HORSE', 400);
There are two possible values for HORSE, 300 and 400. Which one will be picked is undocumented behaviour and can be unpredictable.
I instead encourage you to use the MERGE syntax, being an extension to Standard SQL e.g.
MERGE INTO table1
USING table2
ON table1.NAME = table2.NAME
WHEN MATCHED THEN
UPDATE
SET NEWID = table2.ID;
Note that with the addition of the row as described above, the MERGE syntax will raise an error ("The MERGE statement attempted to UPDATE or DELETE the same row more than once..."), which is more desirable than silently using an arbitrary and potentially incorrect value. Consider that if the designers of SQL Server today really think the UPDATE..FROM behaviour is desirable then why didn't they make MERGE work the same way?
A: Kind of confusing, as it seems you would need to match on name, and not Id? Assuming that is the case:
UPDATE
t1
SET
t1.NEWID = t2.ID
FROM
table1 t1
INNER JOIN table2 AS t2 ON t1.NAME = t2.NAME;
A: The only way to map these to tables is by name, so you need to tweak you UPDATE a little bit:
UPDATE table1
SET NEWID = (
SELECT ID
FROM table2
WHERE table2.NAME = table1.NAME
);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602375",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Understanding android service From here,
It said Service is not a separate process and it is not a thread.
But how can it "A facility for the application to tell the system about something it wants to be doing in the background" ?
How can something being done in background without being a process or a thread?
A: A service is more or less a potentially-long lived Android object. In other words, Android will instantiate a service object for you and keep it alive for you until you tell Android you are done with it.
It is common for services to start a background thread to perform some task. Once they complete their task, they tell Android that the service can be stopped. Once your service is stopped, Android will call onDestroy on it. Now that Android knows your service is done, if the rest of your application isn't running, Android may decide to destroy the process your application was using to reclaim memory. It wasn't doing this before since your service was running.
Think of it this way (note, some things are left out as to not overwhelm you):
*
*Android creates an instance of your service
*Android calls onStart on your service and you start a thread
*Execution returns back to Android and it sees your service is still running so it doesn't call onDestroy
*Some time passes where your background work is being done
*You call stopService on your service or your service is unbound
*Android now sees the service object can be destroyed and collected
*Android calls onDestroy on your service and removes it from its own internal list of running services
A:
How can something being done in background without being a process or a thread?
Simple, is not a process but is part of some process. This means there could very well be a single process that handles all services in the system, similar to how widgets are handled at the home activity.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: It's possible open multiple connections to multiple sites using only one thread? Update
I use a FixedThreadPool already. What happens is that each thread open one connection for one site. What I want to do is something asynchronous.
*
*Send request to a server
*Go to next request without need to wait the first request to complete
*When a request was established, do something informing another thread that connection was established and ready for download.
I think this will speed up the execution because will use less threads for opening the same or more connection that the currently performance.
In the current way, each thread wait a time without work waiting the connection establishes. In this new way, it will be always working.
The Question
I want to know if there is a way to open connection to multiple sites with only one thread.
This is because I'm doing an webcrawler, I already did a thread to open a connection, but after a certain number of threads, this will not help because the processor sharing will increase a lot.
I want this to speed up the number of pages downloaded. It's possible do this? How?
This code open a connection and do some processing. It's executed by the threads that open a connection
/*
* Open connection to a server
*/
boolean openConnection(Link link) throws Exception {
//set the connection paramenters
HttpURLConnection conn = (HttpURLConnection) new URL(link.getOriginalURL().getURL()).openConnection();
conn.setRequestProperty("User-Agent", ROBOT_NAME);
conn.setInstanceFollowRedirects(true);
conn.setConnectTimeout(READ_TIMEOUT);
conn.setReadTimeout(READ_TIMEOUT);
link.setConnection(conn);
//open the connection
conn.connect();
//check the server answer
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
return false;
}
//analyse the URL of the redirected URL
urlAnalyzer.fillURL(link.getRedirectedURL(), getRedirectedURL(link.getConnection()));
return true;
}
This executes the connection openers, each one in one thread
/*
* Start the execution of the connection openers
*/
private void executeConnectionOpeners() {
LOGGER.info("Starting connection openners.");
/* Execution */
NameThreadFactory ntf = new NameThreadFactory("Connection Opener");
crawlerOpenerExecutor = Executors.newFixedThreadPool(nOpeners, ntf);
for (int i = 0; i < nOpeners; i++) {
crawlerOpenerExecutor.submit(new ConnectionOpener(this));
}
/* End of execution */
LOGGER.info(nOpeners + " connection openers created and running.");
}
A: Fetching web pages isn't a particularly processor-intensive job: you've going to spend almost all of your time waiting for the network unless you're fetching a lot of small pages from very fast local connections.
Of course, you should look at how many threads it's actually worth using, via benchmarking - you'll probably want to have a fixed set of threads working off a shared producer/consumer queue. (You don't want to create a genuine new thread for each request.)
Now it should be possible to use only a very few threads if you can perform the fetch asynchronously (potentially with NIO) but I would personally check whether the "separate threads" approach is actually maxing out your CPU first. It's probably going to make the code much simpler than using asynchrony, and if the bottleneck is really the network, then you'll end up with harder-to-maintain code for little (if any) benefit.
A: Check out and see if you like Java 7's AsynchronousSocketChannel. Basically, you issue a read request, and when bytes are available, it'll call your callback. Of course, the callback must be invoked on some thread; you have some options to config the threading policy.
A: I've used xlightweb for similar purpose, i.e. asynchronous HTTP.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android, change alpha on touch I set the alpha of my image view like so:
myImageView.setAlpha(0);
Then on touch:
myImageView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
v.setAlpha(100);
But the alpha doesn't change when I touch the image, I know the touch is picked up as I can log a string to check.
EDIT
If I set my original alpha to 0 and then add a fade in animation, the fade in animation doesnt work, here's the animation:
fadeInAnimation = new AlphaAnimation(0.00f, 1.00f);
fadeInAnimation.setDuration(1000);
If I set the alpha of the original view to something like 0.10 then it fades from 0 to 0.10 not all the way to 1.00f
A: setAlpha takes a float from 0 to 1 where 0 means completely transparent and 1 means fully opaque. Try an input of 0.5f and see what happens.
EDIT:
One way to implement an Animation Listener:
public class myActivity extends Activity{
@Override
public void onCreate(Bundle noNeed){
**** setup ****
fadeInAnimation = new AlphaAnimation(0.00f, 1.00f);
fadeInAnimation.setDuration(1000);
fadeInAnimation.setAnimationListener(new myAnimationListener());
}
private class myAnimationListener implement Animation.AnimationListener{
public void onAnimationStart(Animation animation){
** Do stuff you want to do just before the animation **
}
public void onAnimationRepeat(Animation animation){
** Do stuff you want to do as an animation repeats itself
(i.e. it has started and finish at least once and will go again) **
}
public void onAnimationEnd(Animation animation){
** Do stuff you want to do once an animation finishes **
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Mapping value in junction table to Entity I have a USER table and a COURSE table. A USER can have many COURSES, and a COURSE many USERS. The junction table contains a ROLE value that determines what role the user has in a COURSE (i.e. Instructor, Student, etc.). I need to some how associate this role with the COURSE for each USER.
If I put the role in the Course class, it can't work, since a Course has many users, and vice versa in the User class.
Here's what I have so far:
@Entity
@Table(name = "USERS")
public class User {
@Id
@Column(name = "PK1")
private Long id;
@Column(name = "USER_ID")
private String userId;
@ManyToMany
@JoinTable(name = "COURSE_USERS",
joinColumns = @JoinColumn(name = "USERS_PK1", referencedColumnName = "PK1"),
inverseJoinColumns = @JoinColumn(name = "CRSMAIN_PK1", referencedColumnName = "PK1"))
private Collection<Course> courses;
...
@Entity
@Table(name = "COURSE")
@SecondaryTable(name = "COURSE_USERS",
pkJoinColumns = @PrimaryKeyJoinColumn(name = "CRSMAIN_PK1"))
public class Course {
@Id
@Column(name = "PK1")
private Long id;
// THIS PROBABLY WON'T WORK //
@Column(name = "ROLE", table = "COURSE_USERS")
private Character role;
@Column(name = "AVAILABLE_IND")
private boolean available;
@Column(name = "COURSE_NAME")
private String name;
@Transient
private String url;
...
Note: I cannot change the database schema, so the junction table is nonnegotiable.
A: There is third entity in your case, and it wants to come out. You can call it CourseAssignment. CourseAssignment will contain role, and ManyToOne relationship to both User and Role. And additionally of course OneToMany relationship from Course to CourseAssignment and from User to CourseAssignment.
Something like this will work (I didn't tried it, so something can be missing, but you will get idea.
@Entity
@Table(name = "COURSE_USERS")
@IdClass(CourseAssignmentId.class)
public class CourseAssignment {
@Id
@ManyToOne
@JoinColumn(name="USERS_PK1")
private User user;
@Id
@ManyToOne
@JoinColumn(name="CRSMAIN_PK1")
private Course course;
@Column(name = "ROLE")
private Character role;
}
//and then of course IdClass, because combined key:
@Embeddable
public class CourseAssignmentId implements Serializable{
@Column(name="USERS_PK1")
private Long user;
@Column(name="CRSMAIN_PK1")
private Long course;
}
User { ..
@OneToMany(mappedBy = "user")
private Collection<CourseAssignment> courseAssignments;
...
}
Course {..
@OneToMany(mappedBy = "course")
private Collection<CourseAssignment> course;
..
}
And of course remove those existing relationship connected attributes.
A: As you say, adding the role to the user doesn't make sense since the user may have many courses, and adding the role to the course won't work because a course may have many users.
So you need another entity. Something like:
@Entity
@Table(name = "COURSE_USERS")
// @pkJoinColumns = probably some combination of user/course
public class CourseUser {
@Column(name = "ROLE")
private Character role;
@Column(name = "USERS_PK1")
private User user;
@Column(name = "CRSMAIN_PK1")
private Course course;
}
And each User would have many CourseUsers and each Course would have many CourseUsers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7602386",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.