text
stringlengths 8
267k
| meta
dict |
---|---|
Q: Working with a remainder of Zero with modulo operation? I'm having some difficulty working with a remainder of zero with the modulo operator.
Basically this is a line of my code
fday= (day+24) % 30
I'm trying to just add 24 to any day and take the remainder of it. However, if a user enters 6 for the day, the result is zero which I don't want.
How can I make the operation return 6 if 6 is entered? Is there a better way to do this?
Update:
I'm trying to take a previously defined variable (day) and add 24 days to that value.
However if a user enters the 25th day of the month, and then I add 24 to it I get 49, but 49 days arent in a month.
That's why I'm trying to use the modulo operation to give me the remainder instead, because it works for the 30 days in one month thing.
Another example:
If 5 was input, it would be 5 +24 which is 29 and then 29%30 = 29. So 5 works for what I'm trying to do (which is to just add 24 days to the value and still keep the output under 30 (because there are only 30 days in a month for the purposes of what I'm doing).
A: You say in the comments that for 5 you want 29, for 6 you want 6, and for 7 you want 1. That doesn't make sense. The correct value for 6 is 30 not 6 or 0 when you're calculating a day modulo 30.
In math, division by 30 gives a remainder between 0 and 29 -- that's what modulo 30 is. What you want is a number between 1 and 30.
So you need to take the day, subtract 1 (to get a day between 0 and 29 instead of 1 and 30), add 24, then do the modulo 30, then add 1 (to get back a day between 1 and 30.
result = ((day - 1 + 24) % 30) + 1
That way you'll always get the correct number between 1 and 30 and you don't have to think of 6 as a special case.
A: Consider using the functionality in the datetime module instead of trying to reinvent it:
>>> from datetime import date, timedelta
>>> for month in (4, 5):
... for day in (5, 6, 7, 8):
... start = date(2011, month, day)
... later = start + timedelta(days=24)
... print str(start), str(later)
...
2011-04-05 2011-04-29
2011-04-06 2011-04-30
2011-04-07 2011-05-01
2011-04-08 2011-05-02
2011-05-05 2011-05-29
2011-05-06 2011-05-30
2011-05-07 2011-05-31
2011-05-08 2011-06-01
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623373",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to invoke method on PSObject from managed C++ I'm trying to execute a WMI function using the PowerShell class from a managed C++ function.
But I can't work out how to call a method on the object that is returned in the PSObject list from the PowerShell.Invoke() method.
(On the command line I would just do (gwmi ....).RequestStateChange(2) - but I can't see how to add the () using the few methods of the PowerShell class.
System::Management::Automation::PowerShell ^ ps = System::Management::Automation::PowerShell::Create();
ps->AddCommand("Get-WMIObject");
ps->AddParameter("namespace", "root/virtualization");
p->AddParameter("class", "Msvm_ComputerSystem");
// we could add a filter to only return the VM in question but
// I had problems with quoting so choose the
// simplier route.
System::Collections::ObjectModel::Collection<System::Management::Automation::PSObject^>^ result = ps->Invoke();
System::String ^s = gcnew System::String( id.c_str() );
for (int i = 0; i < result->Count; i++ ) {
if ( System::String::Compare( dynamic_cast<System::String ^>(result[i]->Members["Name"]->Value), s) == 0 ) {
// Now what ? I want to call the RequestStateChange method on this VM
return;
}
}
A: Why do you want to us PowerShell to query WMI you can use managed class ManagementObjectSearcher for that :
ManagementObjectSearcher ComputerInfos = new ManagementObjectSearcher("select * from Win32_ComputerSystem");
A: I know this is a bit stale, but I had similar problem in C# and found this topic as only one describing my problem. The solution I got is pretty basic, which is no wonder since I am beginner with PowerShell. I hope this would answer this problem as well to anyone that may stumble here.
PSObject has .BaseObject property that is used to access underlying object. So if you know the type of the object that has desired method (which you probably do, otherwise I'm not sure how can you expect any specific method), you can simply try casting.
SomeClass x = result[i].BaseObject as SomeClass;
if (x == null)
{
//some handling
}
x.SpecificMethod();
This is C# casting, but you get the idea.
Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623374",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Shared preferences is not applied right away I have a list of activities on clicking one of which i will get a ListView.
On this ListView here, I can apply the preferences using a menu button. But this preferences is not applied right away to the ListView.
I have to go back and navigate my way through the parent list of activities and when i click then only I get the preferences that I want is applied.
cant we get this preferences/settings applied right away after we apply it?
A: But the view I am applying is through a cursoradapter. When I put this cursor inside OnSharedPreferenceChangeListener it gives me some constructor error "The constructor MyCountriesActivity.MySimpleCursorAdapter(new SharedPreferences.OnSharedPreferenceChangeListener(){}, int, Cursor, String[], int[]) is undefined". I tried to adjust the constructor in MySimpleCursorAdapter accordingly but I am not being able to do that. What is the solution?
OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
// Implementation
int sort = prefs.getInt("sort_pref", -1); // -1 will be the result if no preference was set before
if(sort == 1)
sortOrder = "year";//sort on year
else if (sort == 2)
sortOrder = "country";//sort on country
ContentResolver contentResolver = getContentResolver();
Cursor c = contentResolver.query(CONTENT_URI, null, null, null, sortOrder);
String[] from = new String[] { "year", "country" };
int[] to = new int[] { R.id.year, R.id.country };
SimpleCursorAdapter sca = new MySimpleCursorAdapter(this, R.layout.country_row,
c, from, to);
setListAdapter(sca);
}
};
prefs.registerOnSharedPreferenceChangeListener(listener);
}
class MySimpleCursorAdapter extends SimpleCursorAdapter{
public MySimpleCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to) {
super(context, layout, c, from, to);
// TODO Auto-generated constructor stub
}
@Override // Called when updating the ListView
public View getView(int position, View convertView, ViewGroup parent) {
/* Reuse super handling ==> A TextView from R.layout.list_item */
View v = super.getView(position,convertView,parent);
TextView tYear = (TextView) v.findViewById(R.id.year);
TextView tCountry = (TextView) v.findViewById(R.id.country);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean font_size = prefs.getBoolean("fontSize", false);
boolean italic_font = prefs.getBoolean("fontItalic", false);
String listpref = prefs.getString("bgColor", "#ffffff80");
//System.out.println(listpref);
tYear.setBackgroundColor(Color.parseColor(listpref));
tCountry.setBackgroundColor(Color.parseColor(listpref));
if (font_size){
tYear.setTextSize(25);
tCountry.setTextSize(25);
}
if (italic_font){
tYear.setTypeface(null, Typeface.ITALIC);
tCountry.setTypeface(null, Typeface.ITALIC);
}
return v;
}
}
A: You can add OnSharedPreferenceChangeListener to your Activity:
public class MyList extends ListActivity implements OnSharedPreferenceChangeListener {
and define the onSharedPreferenceChange() method to manually alter settings immediately. You'll have to use SharedPreferences.registerOnSharedPreferenceChangeListener(this) as well.
A: OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
int sort = prefs.getInt("sort_pref", -1); // -1 will be the result if no preference was set before
if(sort == 1)
sortOrder = "year";//sort on year
else if (sort == 2)
sortOrder = "country";//sort on country
ContentResolver contentResolver = getContentResolver();
Cursor c = contentResolver.query(CONTENT_URI, null, null, null, sortOrder);
String[] from = new String[] { "year", "country" };
int[] to = new int[] { R.id.year, R.id.country };
SimpleCursorAdapter sca = new MySimpleCursorAdapter(getBaseContext(), R.layout.country_row,
c, from, to);
setListAdapter(sca);
//System.out.println("sjfs");
}
};
prefs.registerOnSharedPreferenceChangeListener(listener);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there an assembler available for Mac OS 7.5.2? Following my last quesiton (Is there a compiler available for Mac OS 7.5.2?), I'm wondering if there is an assembler that I can download for Mac OS 7.5.2? I'm not particularly interested in finding an IDE, but I may need a suitable text editor. Also, it would be nice if the program could fit on a 1.4MB floppy disk (since I'm struggling to find a way to network my old PowerBook).
A: I have been looking for a System 6 assembler myself. The closest thing I've come across is Fantasm/LIDE which should run on System 7.1. I found one of the downloads (LIDE3Dec2002.sit), but as it is just 6.61 MB, it may not be complete.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623377",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Replacing the elements that meet special condition in List with Python in a functional way I have a list [1, 2, 3, -100, 2, -100].
I need to replace -100 with "ERROR", and others to their corresponding string.
I could code like this.
resList = []
for val in list:
if val == -100:
resList.append("ERROR")
else:
resList.append("%d" % val)
How can I do the same thing in a functional way.
I tried mapping.
resList = map(lambda w: if w == -100: "ERROR" else:("%d" % val), list)
However it doesn't compile as it has syntax error.
What's wrong with them?
A: This one doesn't work:
resList = map(lambda w: if w == -100: "ERROR" else:("%d" % val), list)
It fails because you can't have a block inside a lambda expression.
I prefer the list comprehension approach:
resList = ['ERROR' if item == -100 else item for item in yourlist]
This shouldn't generate any errors. If you are getting errors, it's because there are errors elsewhere in your program. Or perhaps the indentation is wrong. Post the specific error message you get.
Also, I'd advise you not to use the name list for local variables because it hides the builtin with the same name.
A: this works:
["ERROR" if -100 == val else str(val) for val in list]
A: The map will work if you use the python ternary operator correctly and the "w" lambda parameter consistently.
map(lambda w: "ERROR" if w == -100 else ("%d" % w), list)
A: This code will do this:
list = [1, 2, 3, -100, 2, -100]
resList = ['ERROR' if x == -100 else str(x) for x in list ]
A: This is some weird looking code, but it works:
resList = ["%s%s" % ("ERROR" * (val == -100), ("%d" % val) * (val != -100)) for val in list]
produces:
['1', '2', '3', 'ERROR', '2', 'ERROR']
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: sleep system call in thread I am using pthread library for multi-threading. Inside thread function, I use sleep system call. Will this block a single thread or the whole process. Thanks.
A: Generally, sleep affects only the calling thread. Real, kernel-managed threads run independently of each other. In an app that has "green" threads, though (not native to the OS; managed by the app itself), a system call that blocks may block everything. But that kind of brokenness is rather rare -- software managing green threads tends to provide a whole runtime environment, including ways to sleep without resorting to a system call.
The better question is...do you really need to sleep at all? Time-based synchronization tends to lead to race conditions and fragile apps. There's a way for threads to wait on and trigger each other; that leads to better determinism.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623381",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Native bitmap processing and ALPHA_8 I'm trying to convert an image to grayscale through a native function, using a piece of code taken from Android in Action (2nd ed.; you can also see it here). Unfortunately, the returned bitmap object, instead of grayscale, ends up empty.
This is how I load the (.png) image:
Bitmap original = BitmapFactory.decodeResource(this.getResources(), R.drawable.sample, options);
There is a number of safety conditions that the bitmap passes (please check below). Here's the native function definition in Java:
public native void convertToGray(Bitmap bitmapIn,Bitmap bitmapOut);
and the call:
// Grayscale bitmap (initially empty)
Bitmap gray = Bitmap.createBitmap(original.getWidth(),original.getHeight(),Config.ALPHA_8);
// Native function call
convertToGray(original,gray);
And here's the function:
JNIEXPORT void JNICALL Java_com_example_Preprocessor_convertToGray(JNIEnv * env, jobject obj, jobject bitmapcolor,jobject bitmapgray)
{
AndroidBitmapInfo infocolor;
AndroidBitmapInfo infogray;
void* pixelscolor;
void* pixelsgray;
int ret;
int y;
int x;
LOGI("convertToGray");
if ((ret = AndroidBitmap_getInfo(env, bitmapcolor, &infocolor)) < 0) {
LOGE("AndroidBitmap_getInfo() failed ! error=%d", ret);
return;
}
if ((ret = AndroidBitmap_getInfo(env, bitmapgray, &infogray)) < 0) {
LOGE("AndroidBitmap_getInfo() failed ! error=%d", ret);
return;
}
LOGI("color image :: width is %d; height is %d; stride is %d; format is %d;flags is %d",infocolor.width,infocolor.height,infocolor.stride,infocolor.format,infocolor.flags);
if (infocolor.format != ANDROID_BITMAP_FORMAT_RGBA_8888) {
LOGE("Bitmap format is not RGBA_8888 !");
return;
}
LOGI("gray image :: width is %d; height is %d; stride is %d; format is %d;flags is %d",infogray.width,infogray.height,infogray.stride,infogray.format,infogray.flags);
if (infogray.format != ANDROID_BITMAP_FORMAT_A_8) {
LOGE("Bitmap format is not A_8 !");
return;
}
if ((ret = AndroidBitmap_lockPixels(env, bitmapcolor, &pixelscolor)) < 0) {
LOGE("AndroidBitmap_lockPixels() failed ! error=%d", ret);
}
if ((ret = AndroidBitmap_lockPixels(env, bitmapgray, &pixelsgray)) < 0) {
LOGE("AndroidBitmap_lockPixels() failed ! error=%d", ret);
}
// modify pixels with image processing algorithm
for (y=0;y<infocolor.height;y++) {
argb * line = (argb *) pixelscolor;
uint8_t * grayline = (uint8_t *) pixelsgray;
for (x=0;x<infocolor.width;x++) {
grayline[x] = 0.3 * line[x].red + 0.59 * line[x].green + 0.11*line[x].blue;
}
pixelscolor = (char *)pixelscolor + infocolor.stride;
pixelsgray = (char *) pixelsgray + infogray.stride;
}
LOGI("Done! Unlocking pixels...");
AndroidBitmap_unlockPixels(env, bitmapcolor);
AndroidBitmap_unlockPixels(env, bitmapgray);
}
The color bitmap gets passed correctly, and the processing part of the code appears to be working fine, but bitmapgray stays empty. I guess I'm missing something crucial here.
Test environment: emulator, v2.2. With this version, the function works when the native code is called from the main thread. On a 2.3 emulator, the function doesn't work regardless of the thread that calls the C code, or the way the bitmap is loaded. Android NDK: 4b & 6b.
UPDATE #1: You'll find the complete source code here.
UPDATE #2: RGB_565 instead of ALPHA_8 gives some results. It appears not even setPixels() in Java works for ALPHA_8, and I'm having
problems finding info on this config type. Any kind of help would be
much appreciated.
A: I had similar problem.
First of all, I used android RGBA_8888 format for infogray instead of A_8 (the original bitmap was created using ARGB_8888 format).
Then if you use argb struct for grayline instead of uint_8, you can fill the pixels like this:
for (y = 0; y < infocolor.height; ++y) {
argb* line = (argb*) pixelscolor;
argb* grayline = (argb*) pixelsgray;
for (x = 0; x < infocolor.width; ++x) {
grayline[x].red = grayline[x].green = grayline[x].blue = 0.3 * line[x].red + 0.59 * line[x].green + 0.11 * line[x].blue;
}
pixelscolor = (char*)pixelscolor + infocolor.stride;
pixelsgray = (char*)pixelsgray + infogray.stride;
}
A: i had the same problems.
I did not try much to make ALPHA_8 work but using ARGB_8888 fixes the problem.
Btw, in reply to @white_pawn's comment (sorry i cannot reply to comments)
The argb struct in IBM's example is in wrong order. in my emulators or phone,
converting it to RGBA fixes the issue (this is probably the reason why your image looks blue because you use alpa for blue). Though I'm not sure if this order is hardware dependent.
typedef struct
{
uint8_t red;
uint8_t green;
uint8_t blue;
uint8_t alpha;
} argb;
A: I had the same problem and found what went wrong! When you use APHA_8 you need to change background to #ffffffff,
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffffff">
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: C++11 Pointer Uniquify Helper Function In C++11, I'm missing a syntatic sugar for uniquifying a pointer into std::unique_ptr. I therefore wrote the following litte helper function std::uniquify_ptr typically used to easy (non-constructor) assignment of mutable class members (typically different kinds of caches).
#include <memory>
namespace std
{
template<typename T>
inline unique_ptr<T> uniquify_ptr(T* ptr)
{
return unique_ptr<T>(ptr);
}
}
Am I missing something from a safety point of view here? Is some similar function already available?
A: No, there is no similar function already available. How is
auto ptr(std::uniquify_ptr(new T()));
any better than
std::unique_ptr<T> ptr(new T());
? I.e., why should this exist? It's not saving you much if anything.
A: unique_ptr<T> can already directly construct from a T*, so there's little need. Such a factory function has little use except for syntactic sugar, e.g., auto x = make_unique<T>(...);. Also, your move is redundant.
A: @Schaub: I'm using this to change the value of an existing mutable std::unique_ptr class member. In that case
m_hashA = std::uniquify(new Hashes(cnt));
is more convenient than
m_hashA = std::unique_ptr<Hashes>(new Hashes(cnt)));
vere the member is declared as
mutable std::unique_ptr<Hashes> m_hashA; ///< Hash Table for Alternatives.
Thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623383",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why doesn't this code work to set up basic Android OpenGL? Hey I am trying to just set up the basic structure for some basic graphics. However, when I run this code the app makes me force quit on the emulator. I am using Android 2.3.
I used this website to get this far http://developer.android.com/resources/tutorials/opengl/opengl-es10.html
Please help. I am familiar with OpenGL just not for Android
public class SampleActivity extends Activity {
/** Called when the activity is first created. */
private GLSurfaceView mGLView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGLView = new GLSurfaceView(this);
setContentView(mGLView);
}
@Override protected void onPause()
{
super.onPause();
mGLView.onPause();
}
@Override protected void onResume()
{
super.onResume();
mGLView.onResume();
}
}
class SampleSurfaceView extends GLSurfaceView
{
public Sample2SurfaceView(Context context) {
super(context);
setRenderer(new SampleRenderer());
}
}
public class SampleRenderer implements GLSurfaceView.Renderer
{
private FloatBuffer triangleVB;
public void onSurfaceCreated(GL10 gl, EGLConfig config)
{
gl.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
}
public void onDrawFrame(GL10 gl)
{ // Redraw background color
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
}
public void onSurfaceChanged(GL10 gl, int width, int height)
{
gl.glViewport(0, 0, width, height);
}
10-03 00:25:57.561: ERROR/AndroidRuntime(330): FATAL EXCEPTION: main
10-03 00:25:57.561: ERROR/AndroidRuntime(330): java.lang.RuntimeException: Unable to resume activity {android.SampleActivity}: java.lang.NullPointerException
10-03 00:25:57.561: ERROR/AndroidRuntime(330): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2120)
10-03 00:25:57.561: ERROR/AndroidRuntime(330): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2135)
10-03 00:25:57.561: ERROR/AndroidRuntime(330): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1668)
10-03 00:25:57.561: ERROR/AndroidRuntime(330): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
10-03 00:25:57.561: ERROR/AndroidRuntime(330): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
10-03 00:25:57.561: ERROR/AndroidRuntime(330): at android.os.Handler.dispatchMessage(Handler.java:99)
10-03 00:25:57.561: ERROR/AndroidRuntime(330): at android.os.Looper.loop(Looper.java:123)
10-03 00:25:57.561: ERROR/AndroidRuntime(330): at android.app.ActivityThread.main(ActivityThread.java:3683)
10-03 00:25:57.561: ERROR/AndroidRuntime(330): at java.lang.reflect.Method.invokeNative(Native Method)
10-03 00:25:57.561: ERROR/AndroidRuntime(330): at java.lang.reflect.Method.invoke(Method.java:507)
10-03 00:25:57.561: ERROR/AndroidRuntime(330): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
10-03 00:25:57.561: ERROR/AndroidRuntime(330): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
10-03 00:25:57.561: ERROR/AndroidRuntime(330): at dalvik.system.NativeStart.main(Native Method)
10-03 00:25:57.561: ERROR/AndroidRuntime(330): Caused by: java.lang.NullPointerException
10-03 00:25:57.561: ERROR/AndroidRuntime(330): at android.opengl.GLSurfaceView.onResume(GLSurfaceView.java:512)
10-03 00:25:57.561: ERROR/AndroidRuntime(330): at android.TagToMobileAlbum.TagToMobileAlbumActivity.onResume(TagToMobileAlbumActivity.java:28)
10-03 00:25:57.561: ERROR/AndroidRuntime(330): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1150)
10-03 00:25:57.561: ERROR/AndroidRuntime(330): at android.app.Activity.performResume(Activity.java:3832)
10-03 00:25:57.561: ERROR/AndroidRuntime(330): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2110)
10-03 00:25:57.561: ERROR/AndroidRuntime(330): ... 12 more
10-03 00:34:05.661: ERROR/AndroidRuntime(340): FATAL EXCEPTION: main
10-03 00:34:05.661: ERROR/AndroidRuntime(340): java.lang.RuntimeException: Unable to resume activity {android.TagToMobileAlbum/android.TagToMobileAlbum.TagToMobileAlbumActivity}: java.lang.NullPointerException
10-03 00:34:05.661: ERROR/AndroidRuntime(340): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2120)
10-03 00:34:05.661: ERROR/AndroidRuntime(340): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2135)
10-03 00:34:05.661: ERROR/AndroidRuntime(340): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1668)
10-03 00:34:05.661: ERROR/AndroidRuntime(340): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
10-03 00:34:05.661: ERROR/AndroidRuntime(340): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
10-03 00:34:05.661: ERROR/AndroidRuntime(340): at android.os.Handler.dispatchMessage(Handler.java:99)
10-03 00:34:05.661: ERROR/AndroidRuntime(340): at android.os.Looper.loop(Looper.java:123)
10-03 00:34:05.661: ERROR/AndroidRuntime(340): at android.app.ActivityThread.main(ActivityThread.java:3683)
10-03 00:34:05.661: ERROR/AndroidRuntime(340): at java.lang.reflect.Method.invokeNative(Native Method)
10-03 00:34:05.661: ERROR/AndroidRuntime(340): at java.lang.reflect.Method.invoke(Method.java:507)
10-03 00:34:05.661: ERROR/AndroidRuntime(340): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
10-03 00:34:05.661: ERROR/AndroidRuntime(340): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
10-03 00:34:05.661: ERROR/AndroidRuntime(340): at dalvik.system.NativeStart.main(Native Method)
10-03 00:34:05.661: ERROR/AndroidRuntime(340): Caused by: java.lang.NullPointerException
10-03 00:34:05.661: ERROR/AndroidRuntime(340): at android.opengl.GLSurfaceView.onResume(GLSurfaceView.java:512)
10-03 00:34:05.661: ERROR/AndroidRuntime(340): at android.SampleActivity.onResume(
SampleActivity.java:28)
10-03 00:34:05.661: ERROR/AndroidRuntime(340): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1150)
10-03 00:34:05.661: ERROR/AndroidRuntime(340): at android.app.Activity.performResume(Activity.java:3832)
10-03 00:34:05.661: ERROR/AndroidRuntime(340): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2110)
10-03 00:34:05.661: ERROR/AndroidRuntime(340): ... 12 more
A: I was having the same problem and, from looking at other sample code, managed to solve it. I'm not sure why it makes a difference but I moved the call to setRenderer into the Activity constructor and this seems to have solved the problem. So your onCreate would be something like:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGLView = new GLSurfaceView(this);
mGLView.setRenderer(new SampleRenderer())
setContentView(mGLView);
}
A: 1) Your constructor for SampleSurfaceView does not match the name of the class.
2) You need to set the SurfaceView's Renderer before you set the ContentView.
Among other things, you don't ever seem to be using SampleSurfaceView. If you want to extend GLSurfaceView, you need to use that extended class. Switch your private GLSurfaceView and all instances of it to SampleSurfaceView. Currently your SampleSurfaceView class is never used.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SSL configuration with play framework and the chain file I have configured play internal web-server with SSL with following configuration:
https.port=9443
certificate.key.file=conf/host.key
certificate.file=conf/host.cert
but the problem is that the newest firefox is unable to authenticate and gives the following message:
The certificate is not trusted because no issuer chain was provided.
in Apache2 you can specify the chain file with SSLCertificateChainFile, anyone knows how to do it in play?
thanks!
A: Latest Update: Even after combining chain file with main cirtificate, firefox is complaining about untrusted connection. I am giving up. I will use Appache httpd in the front.
Finally, I was able to setup ssl with godaddy cirtificates, directly in play framework webserver.
In application.conf add the lines.
%prod.http.port=80
%prod.https.port=443
%prod.certificate.key.file=conf/hostname.key
%prod.certificate.file=conf/hostname.combined.crt
Combine the CA signed certificate and the bundle file into one.
openssl x509 -inform PEM -in hostname.crt -text > hostname.combined.crt
openssl x509 -inform PEM -in "sf_bundle.crt" -text >> hostname.combined.crt
And copy the following files to your conf folder (Don't put it in a sub-folder. It will not work)
sf_bundle.crt
hostname.crt
hostname.csr
hostname.key
A: In another forum, I came across a solution with which you can combine your certificate and chain file into one file. This way you don’t have to specify a separate chain file. Hope this helps.
http://help.globalscape.com/help/eft5/admin/certificate_chaining.htm
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623392",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Undefined References In Antlr C Runtime Example I'm having a problem running the C runtime example at http://www.antlr.org/depot/examples-v3/C/treeparser from Antlr.
I've downloaded and installed the C runtime from http://www.antlr.org/download/C. The library libantlr3c.a is located in /usr/local/lib, and the antlr headers are located in /usr/local/include. Is this the right antlr library? In other examples I've seen the "antlr3c" library mentioned, whereas mine has the "lib" infront.
I downloaded the example files and placed them in a folder named "example" in /home/fraser/examples. Then I let Antlr create the auto-generated Parser and Lexer files, and from there I run:
gcc *.c -o test -I. -L -llibantlr3c
and it gives me the following errors:
/tmp/ccvXlH3T.o: In function `LangDumpDeclNewSSD':
LangDumpDecl.c:(.text+0x89): undefined reference to `antlr3TreeParserNewStream'
/tmp/cc3TwzKz.o: In function `LangLexerNewSSD':
LangLexer.c:(.text+0xd3): undefined reference to `antlr3LexerNewStream'
/tmp/ccpfbaFf.o: In function `LangParserNewSSD':
LangParser.c:(.text+0x8c): undefined reference to `antlr3ParserNewStream'
LangParser.c:(.text+0xf1): undefined reference to `ANTLR3_TREE_ADAPTORNew'
LangParser.c:(.text+0x103): undefined reference to `antlr3VectorFactoryNew'
/tmp/ccpfbaFf.o: In function `decl':
LangParser.c:(.text+0x6ca): undefined reference to `antlr3RewriteRuleSubtreeStreamNewAE'
LangParser.c:(.text+0x76f): undefined reference to `antlr3RewriteRuleTOKENStreamNewAE'
LangParser.c:(.text+0x811): undefined reference to `antlr3RewriteRuleTOKENStreamNewAE'
LangParser.c:(.text+0x85d): undefined reference to `antlr3RewriteRuleSubtreeStreamNewAEE'
/tmp/ccED3tJV.o: In function `main':
main.c:(.text+0x46): undefined reference to `antlr3AsciiFileStreamNew'
main.c:(.text+0xe0): undefined reference to `antlr3CommonTokenStreamSourceNew'
main.c:(.text+0x1d0): undefined reference to `antlr3CommonTreeNodeStreamNewTree'
collect2: ld returned 1 exit status
My only previous experience with Antlr was in Java, and my only prior C/C++ experience has been with Visual Studio, so I'm new to linkages and command-line compilation, etc. So I'm guessing this is a very simple error involving the wrong linkages, or the wrong antlr library.
Apologies and thanks in advance.
A: You are using the -L option without a parameter. The option -llibantlr3c is being treated like the directory parameter of -L instead of a library to link. Because the antlr library isn't being included in the link, you are getting all the missing symbols. Also, -l prepends 'lib' to the library name, so try
gcc *.c -o test -I. -lantlr3c
If libantlr3c.a file is in a nonstandard directory, then add that directory with the -L flag
A: After ver 3.4, Pls, change to
input = antlr3FileStreamNew ((pANTLR3_UINT8)argv[1], ANTLR3_ENC_8BIT);
Not, antlr3AsciiFileStreamNew(argv[1]) as examples
refer Shinji Nakamatsu
http://www.antlr.org/wiki/display/ANTLR3/Five+minute+introduction+to+ANTLR+3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623393",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What's easiest way to get a previous iPhone app version onto my device? (for testing upgrade to upcoming app version) Background: Have got v2 of an iPhone application in XCode now, with v1 on the app store. So on my iPhone I have working versions of v2.
Aim: So I want a quick way to load the true original version onto my one and only iPhone device I have for testing.
Question: What's the best/quickest way to do this. I don't have a good option currently. I have thought of:
*
*Download from iTunes - but this is a bit of a pain (i.e. assumes I really just want the current version, to overwrite the upcoming latest version I've deployed to the device from XCode).
*Copying the files from the iPhone using something like "Phone Disk" (http://www.macroplant.com/phonedisk/) to my Mac, test the upgrade deployment of v2, and then when wanting to rollback then using Phone Disk (a) delete existing files on iPhone, and (b) copy back original files I'd saved off. I could NOT get this to work however. Was problematic transferring files across, and when I got them all back onto the iPhone and tried to run it it wouldn't start :(
(Note - From other advise I could probably just replace the sqlite file for the purpose of testing the core data migration, but for the purpose of this question I was targeting getting the actual true previous version in place)
A: The way most developers do this is with a backup or version control checkin of every submitted app version. Just restore from backup or checkout from source control into a different directory from the working copy, open that project, build and install.
I usually change the Bundle ID, Bundle Display name, and product name in the copy of old version (add a V0100 suffix or some such), which allows me to run the old version alongside the current build of the app for comparison testing, etc. But for upgrade testing, you would have to leave them the same, or use a temporary ID and name for both the previous and upgraded app versions. This rename allow you to do this upgrade multiple times. Just keep rev'ing the suffixes. Just don't forget to change them back when done testing.
A: Is your device jailbroken? It may actually help if (in this case) it is.
I'd download the IPA version you're looking for through google or something, then, with AppSync installed on your device, sync the app through iTunes.
The only problem You might see with this is that the newer version's user data MAY be deleted.
Try this at your own risk. I am not saying it will work, but I have done so in the past. And don't use jailbreak illegally, use it responsibly.
Edit: didn't see you had the previous version already. Maybe just bundle it up into an IPA, then use the method I said.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Override Ctrl-C I am supposed override the CtrlC signal and use it to print a message. It is not supposed to end the program.
What happens so far is that when CtrlC is pressed it prints the message, but ends the program.
When I asked my professor he told me to do this:
You need to make your signal handler keep from continuing to process the signal. Right now the signal is being handled by your code and then going on to the parent handler.
Is there a method I am supposed to add or do i need to move the signal installers someplace?
This is my code so far:
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <signal.h>
#include "Input.h"
#include "CircleBuff.h"
//void handler_function(int signal_id);
void catch_int(int sig_num){
//reset the signal handler again to catch_int, for next time
signal(SIGINT, catch_int);
//print message
printf("Print History");
fflush(stdout);
}
void printHistory(CircleBuff hist){
cout << "Complete History:\n" << endl;
hist.print();
cout << endl;
}
int main(int argc, char** argv){
struct sigaction signal_action; /* define table */
signal_action.sa_handler = catch_int; /* insert handler function */
signal_action.sa_flags = 0; /* init the flags field */
sigemptyset( &signal_action.sa_mask ); /* are no masked interrupts */
sigaction( SIGINT, &signal_action, NULL ); /* install the signal_action */
do{
//My code: where the value report will be assigned within.
} while(report != 1)
}
A: Whoa, way too much code to sift through. However, if you use the C standard library, you should get the desired behaviour. Here's a C++ version:
#include <iostream>
#include <csignal>
sig_atomic_t sigflag = 0;
void sighandler(int s)
{
// std::cerr << "Caught signal " << s << ".\n"; // this is undefined behaviour
sigflag = 1; // something like that
}
int main()
{
std::signal(SIGINT, sighandler);
// ... your program here ...
// example: baby's first loop (Ctrl-D to end)
char c;
while (std::cin >> c)
{
if (sigflag != 0) { std::cerr << "Signal!\n"; sigflag = 0; }
}
}
This will catch Ctrl-C (which raises SIGINT), and the signal handler is not replaced, so it'll fire every time, and nobody is terminating the program.
Note that signal handlers are inherited by fork()ed children.
The Posix function sigaction() allows you to register "one-shot" handlers which are replaced by the standard handler after they're invoked once. That's more advanced and Posix-specific, though.
Edit: As @Dietrich points out, you should never do any real work inside a signal handler. Rather, you should set a flag (I provided an example), and check for that flag inside your loop (and print the message there). I'll amend the example for that, too.
A: Have you considered that inside your while loop there may be an interruptable function failing with 'EINTR'. You could might be able to fix it by using :
sa.sa_flags = SA_RESTART;
Or, just checking errno for it and looping. Are you sure the program isn't reaching the end of termination. Try putting a print statement at the end of main.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623401",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: How to convert a std::istream to std::wistream I have an istream and some code expects a wistream.
I literally want every char of a source stream zero extended to a wchar_t. I don't care about code pages, I don't care about localization, I simply want to seamlessly pipe this input, what's the fastest way to do it?
A: You can write a read buffer to adapt the underlying stream buffer in the istream to your wistream:
class adapting_wistreambuf : public wstreambuf {
streambuf *parent;
public:
adapting_istreambuf(streambuf *parent_) : parent(parent_) { }
int_type underflow() {
return (int_type)parent->snextc();
}
};
Later:
istream &somestream = ...;
adapting_wistreambuf sb(somestream.rdbuf());
wistream wistream(&sb);
// now work with wistream
This implements only the bare minimum of streambuf's interface. You could add buffer management code to improve performance if you need to.
A: I think it is not possible without writing a complicated* wrapper around an std::wistream to provide an std::istream interface. The difference between the two is the char type used when instantiating these classes from templates, thus making std::istream (char_type = char) and std::wistream (char_type = wchar_t) in two different class hierarchies. They only share std::ios_base as a common base class, which does not provide something useful for your current problem.
Because of that, the following piece of code will not compile (it tries to replace the internal std::streambuf of s2 with s1's one, thus making I/O operations on s2 performing on the data from the file) :
std::wifstream s1 ;
std::istringstream s2 ;
// assuming s1 and s2 are correctly initialized ...
s2.ios::rdbuf(s1.rdbuf()) ; // will not compile, unfortunately, unless the char type
// is the same for the two streams :(
I'm not aware of a simple solution, perhaps a Boost IOStreams Filter can be used (I never tried :( ).
If you're not dealing with binary data, and your stream length isn't too big, try reading all the data to a string and then convert (zero extend as you say) into an std::wistringstream.
* : complicated means that you have reasonable knowledge about std::streams. I confess I'm not comfortable with streams.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623403",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: simple C++ comparision if statement I have a function in C++ that takes a char array thingArray[6] and places ' ' onto each place.
like:
for (int i =0; i<5; i++)
{
thingArray[i] = ' ';
}
now I have another function that sticks a character if it finds an empty space in the array. please say the array now looks like: 'w',' ','R','E',' ','E',
if I do:
for (int i = 0;i<5;i++)
{
if (thingArray[i] == ' ')
{
thingArray[i] = 'M';
}
}
It should be pretty intuitive that the for loop will traverse the array and find the ' ' and stick an 'M' in it's place. Sometimes it will not work. This is my first time coding in a language that uses pointers so I think that may be one of my issues.
Any suggestions, or a better way of doing this would be great!
Thanks.
A: If thingArray is a string literal, then it's actually constant and you can't change the value of its elements.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623404",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to highlight the menu item for the sort type of data on the page? In this site I would like to highlight the type of sort on the menu. I found many source to do this with css or javascript but I could not understand them enough to apply them to this site (they seem to be for pull-down menus). Can you direct me about how to do this with the css that I have now for this page? It is just one page, sorted 5 different ways. My main.css is below. Thanks!
.admin-content {width: 95%;
margin-top: 0px
margin-bottom: auto;
margin-right: 5px;
margin-left: 5px;
padding: 0px;}
.image-submit {width: 550px; margin-top: 0px margin-bottom: auto; margin-right: 50px; margin-left: 70px; padding: 15px;}
.image-page {width: 90%; padding: 15px;}
body { font-size: small; font-family: Verdana, Helvetica, sans-serif; }
a:link { color:#000000; text-decoration:none; }
a:visited { color:#000000; text-decoration:none; }
a:hover { text-decoration: underline; color: #0066CC; }
a:active { text-decoration: none }
tr {font-size: small; font-family: Verdana, Helvetica, sans-serif; }
.small {color: #808080; font-size: x-small; }
.xxsmall {color: #808080; font-size: xx-small; line-height:60%}
.small-tags {font-size: x-small; }
.large {color: #0033FF; font-size: 130%; }
.smaller-line-height {line-height:10%}
.medium {font-size: medium; }
Update
I updated the script according to Alon's answer but this is not working. What am I doing wrong?
I added the js to the header:
<head>
...
self.response.out.write("""<script language="Javascript" type="text/javascript">
var url = window.location.href,
sort_by = url.split("=");
if (sort_by.length == 2) {
document.getElementById(sort_by[1]).className = "active";
}</script>""")
...
</head>
changed the urls:
self.response.out.write("""<p>
<b>sort by: </b><a href="/displayimage?sort_by=color">color</a> |
<a id="number_of_attorneys" href="/displayimage?sort_by=number_of_attorneys">number of attorneys</a> |
<a id="number_of_partners" href="/displayimage?sort_by=number_of_partners">number of partners</a> |
<a id="number_of_associates" href="/displayimage?sort_by=number_of_associates">number of associates</a> |
<a id="associate_salary" href="/displayimage?sort_by=associate_salary">associate salary</a> |
</p>""")
and I added the .active { color:red; } to main.css.
.active { color:red; }
But this is not working as expected. Is .active { color:red; } conflicting with a:active { text-decoration: none } in the css? I removed a:active { text-decoration: none } but it didn't make a difference.
A: your html should be
<a id="number_of_attorneys" href="/displayimage?sort_by=number_of_attorneys">number of attorneys</a> |
<a id="number_of_partners" href="/displayimage?sort_by=number_of_partners">number of partners</a> |
<a id="number_of_associates" href="/displayimage?sort_by=number_of_associates">number of associates</a> |
<a id="associate_salary" href="/displayimage?sort_by=associate_salary">associate salary</a> |
your javascript code should be something like
var url = window.location.href,
sort_by = url.split("=");
if (sort_by.length == 2) {
document.getElementById(sort_by[1]).className = "active";
}
you should also add class active to your css with the highlight style
.active { color:red; }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Learning the reddit JSON API using Apigee. How do I submit a story? Accordng to https://github.com/reddit/reddit/wiki/API I need to:
"Post the following to http://www.reddit.com/api/submit:
uh=f0f0f0f0&kind=link&url=yourlink.com&sr=funny
&title=omg-look-at-this&id%23newlink&r=funny&renderstyle=html
I believe uh is the modhash that that you get after loging in like this:
http://www.reddit.com/api/login/joe?user=joe&passwd=passw0rd&api_type=json
But whenever I try to make a submission, I get this:
https://apigee.com/console/apigee-console-snapshots-1317445200000_ba798aaf-165d-40c3-8aec-17673087f9ff/rendersnapshotview
Any help would be greatly appreciated.
A: Be sure that you're sending back the reddit_session cookie they send/set with the login response when you post your submission. You need this as well as the uh/modhash.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Will having an iFrame on someone else's domain transfer pagerank to my site? I am having a hard time finding a good answer to this question. I see that Google treats the content in the iframe as its own seperate site, but what I want to know is if it transfers any pagerank to my site. What I am letting other sites embed is an interactive javascript app.
I have an iframe embed that looks something like
<iframe width='895' height='656' src='http://domain.com/script.php?var=whatever' scrolling="no" style='border:none;'>Stuff about the <a href='http://domain.com/other_page'>Keywords</a> and my site.</iframe>
Will the link inside the iframe tags transfer pagerank to me or no?
A: I don't think so. The pagerank at the best of my knowledge is forwarded just in the case of link.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Change animation in runtime I want to achieve simple tasks - before dialog is dismissed, I want to set different close animation depending on my logic (getWindow().getAttributes().windowAnimations = ...). For examle, I have 2 buttons on dialog and i want to slide left if first is pressed, slide right if second is pressed. I have created style file with some animations for android:windowExitAnimation and android:windowEnterAnimation and they work if passed in custom dialog constructor. But I cant override windowAnimations within the code as constructor approach can no be used as I need different animations. How can it be done and why this code is not working?
// close button
_button_close = (ImageButton)findViewById(R.id.buttonClose);
if (_button_close != null)
{
_button_close.setOnClickListener(
new Button.OnClickListener()
{
public void onClick(View v)
{
// set animation
getWindow().getAttributes().windowAnimations = R.style.DialogSlideOutLeft;
// close form
dismiss();
}
}
);
}
A: I have had same problem.
Here is my solution:`
alertCheckIn = new Dialog(this);
alertCheckIn.setTitle("Check-In");
alertCheckIn.setContentView(textEntryView); //my custom dialog layout
lpDialog = alertCheckIn.getWindow().getAttributes();
lpDialog.windowAnimations = R.style.FadeInDropOutDialogAnimation;
alertCheckIn.getWindow().setAttributes(lpDialog);
alertCheckIn.show();
`
and then when i want to switch animation:
`
lpDialog.windowAnimations = R.style.FadeInSlideLeftOutDialogAnimation;
alertCheckIn.getWindow().setAttributes(lpDialog);
alertCheckIn.cancel();`
when:
private WindowManager.LayoutParams lpDialog;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623414",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: timertask-based logout give me problems In this website I need a system that logs the user out after 10 minutes.
In order to login I use a simple procedure of inserting a user (in my case called Lid) instance, and the logout invalidates the session, additionally, when the user logs in a timertask within a timer starts, and after 10 minutes invalidates the session.
Here is the code:
MyTask task = null;
private void setCurrent(String key, Object o) {
getRequest().getSession().setAttribute(key, o);
}
private <T> T getCurrent(String key) {
T value = (T) getRequest().getSession().getAttribute(key);
return value;
}
public void logIn(Lid lid) {
setCurrent("lid", lid);
Timer timer = new Timer();
task = new MyTask(getRequest().getSession());
System.out.println(task.toString());
timer.schedule(task,10*60*1000);
}
public void logOut() {
task.cancel();
getRequest().getSession().invalidate();
}
This is the MyTask code:
public class MyTask extends TimerTask {
HttpSession session = null;
public MyTask(HttpSession session) {
this.session=session;
}
@Override
public void run() {
session.invalidate();
}
}
The problem is that when I voluntarily log out, it throws an exception because it says that the task variable is null, and so it becomes not possible to call cancel() on the task variable.
But I don't get it, after logging in the variable is instantiated, its not null.
Do you have some advise about this?
Thank you
A: Why not just let the web container handle session time-out for you? If you put below code in your web.xml all inactive sessions will expire in 10 minutes:
<session-config>
<session-timeout>10</session-timeout>
</session-config>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Android memory leak example from Google I/O I just had a look at the google io video "memory management for android". Slides are available here http://dubroy.com/memory_management_for_android_apps.pdf. The memory leak example is on slide 36.
I do not understand why this causes a leak after orientation change. I do understand that leak is an inner class and has a reference to the outer class. Also, I do understand that the static variable "leak" references the "Leaky" object..thus the whole activity. I think that's special because of the static keyword. Static variables have a certain memory and are probably not gc'ed (at least as long as the application runs)?!?
Well, what happens on oriantation change? A new activity instance is created and the activities onCreate is called. leak == null is false. Leak still points to the "old" activity. That's a leak. The old activity cant be gc'ed, right?
Why does memory usage increase with every oriantation change? In my (wrong) understanding I'd assume that just the first activity can't be gc'ed. The other activites that are created because of oriantation change can be gc'ed because they aren't referenced by that static variable "leak".
However..obviously..I'm completely wrong!
A: A classic explanation of the orientation change Context memory leak from Google blog. You were most of the way there, I think, noting static reference of the inner to the outer class.
A: You don't understand because you made a critical error. leak == null is true in the newly created activity. leak doesn't still point to the "old" activity.
Why? I thought leak was static you ask. Well. . .
So, first time around, the activity is created, leak is null, then onCreate() and leak now references a Leaky object. If I create more instances of that activity, their leak's will not be null and reference that same object.
But, what happens when you flip orientation is that the activity is destroyed. So, there is no existing instance of an activity object. Android then creates a new activity, where leak is null (because as far as Android is concerned, no other instance of the activity exists).
However, to the garbage collector, someone does hold a reference to the destroyed activity, namely its inner Leaky class. So it won't free that memory. Hence, as you continue to change orientation, you keep leaking an activities worth of memory.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623423",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Raven DB: How is 'smuggler' different from 'Import/Export'? With Raven DB, there is a program called "Smuggler" which allows dumps to be taken of Raven DB. However, there is also an option within Raven DB Management Studio to 'Import/Export' database.
What is the difference?
A: There is no difference, Import/Export uses the same code as smuggler
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623428",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: TYPEFACE.JS Selecting different fonts I'm trying to create a font preview form like on dafont.com or a similar website using typeface.js.
I'm having trouble getting typeface.js to render font for anything but a heading tag. Further, how can I choose which font to use from a dropdown?
Thanks SO much!
A: Have you read the documentation?
Have you converted your fonts for use with typeface?
From the Typeface website:
By default typeface.js will render text for heading elements (h1, h2, etc.) when those elements' styles reference typeface.js fonts.
Remember that heading styles are bold by default, so you'll either need to add font-weight: normal to you heading styles, or load the bold version of the font if that's what you're after.
Any other HTML element referencing a typeface.js font needs to have typeface-js in its list of class names. If you have an element that already has a class name, for example, , you can just add another class name by saying .
You'll have to load external stylesheets before loading typeface.js. Otherwise, Firefox 3 might not have applied the styles when typeface.js tries to draw the text.
Unfortunately, specifying the font-stretch property will only work with inline CSS and not from any stylesheet.
In some circumstances in IE7 you may see a couple of milliseconds' delay before the browser shows typeface.js text after the page is rendered, producing a "flicker" effect. One way to get around this is to manually put a call to _typeface_js.initialize() just before your closing tag.
If your looking to dynamicly change the font displayed in a single canvas, you would probably have to read the documentation for typeface.js and see if there is some way to do that, there is also a forum on the typeface website. Otherwise you would have to write something yourself that interacts with the typeface script to change the displayed font.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sharepoint 2010 List Creation Limit Does anyone knows if sharepoint 2010 have some kind of limitation related to list creation? I need to create a web application with 120.000 lists for a specific reason. It is that possible? There will be some performance issues?
Cheers,
A: I don't think theres a limitation for how many lists you can create, however, there is an overall limitation of list items / size. Check out this article.
If you really need to create that many lists, you might want to redo your solution design.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What conditions must be met for iPad/iPhone hardware accelerated animations? I'm just wandering what I must do to get hardware accelerated animations ? Do I have to se doctype HTML5 or can I use HTML4.01 or something similar ? Are there any other limitations / things I must do/use?
Also, where can I find a list of css properties (animations?) that are hardware acceleratedon iOS ?
A: Opacity and translate3d are hardware accelerated, pretty much everything else isn't. This changes in iOS5
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Regex work in chrome and explorer but not in firefox I am using Jquery to validate my textbox. my particular regex condition is...
/^[A-Za-z.-\s]*$/.. that is alphabets, space, hyphen, and dots.
Issue is it work great and efficiently in Chrome and explorer but firefox gives error for this regex. I checked using firebug. Even it also not work for firefox.
Error: invalid range in character class
A: To avoid the hyphen having a special meaning (range of characters) you should put it at the end of the character class:
[A-Za-z.\s-]
Alternatively you can escape it:
[A-Za-z.\-\s]
A: Escape the hyphen:
/^[A-Za-z.\-\s]*$/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to trigger the select event handler in jqueryui autocomplete combobox? I have a jqueryui autocomplete combo-box widget in which once the user selects something in the combobox, the select event handler within the combo-box makes an ajax call to render content in another div element. EG:
[combo-box] > [div]
The div contains content in which the user can then click submit to go to a different page.
I am running into a problem in which if the user clicks on the back button AFTER having made a selection within the combo-box and then clicking within the div to go to the next page, the combo-box will display the last selected value, but the div will display the value as it was originally rendered on the page, prior to the ajax request (which populated the div with dynamic content). As a result, the displayed value within the combo-box is now inconsistent with the displayed content in the div.
The solution to this problem requires that I trigger the select of a certain value within the combo-box when the page is first loaded, so that the select event handler within the jqueryui autocomplete combobox code is run, which will reload the div.
What is the best way to do so?
A: You could store the selected value into a hidden input and on page load paint the content div with the value in the hidden input (if any)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Issue with SBJsonParser my iPhone application is receiving from my web service this json string:
{"res":true,"users":[{"id":"79","username":""},{"id":"81","username":""},{"id":"83","username":""},{"id":"80","username":""},{"id":"82","username":""}]}
I'm handling it with the following code:
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
NSError *error = nil;
NSDictionary *dictionary = [jsonParser objectWithString:responseString error:&error];
where responseString is the string received with the JSON.
Now if i check for [[dictionary valueForKey:@"res"] boolValue] it is correctly a boolean.
The problem is with [dictionary objectForKey:@"users"] I don't understand what kind of object it is.
I try also with this:
NSLog(@"Is of type NSString?: %@", ([[dictionary objectForKey:@"users"] isMemberOfClass:[NSString class]])? @"Yes" : @"No");
NSLog(@"Is of type NSArray?: %@", ([[dictionary objectForKey:@"users"] isMemberOfClass:[NSArray class]])? @"Yes" : @"No");
NSLog(@"Is of type NSMutableArray?: %@", ([[dictionary objectForKey:@"users"] isMemberOfClass:[NSMutableArray class]])? @"Yes" : @"No");
NSLog(@"Is of type NSDictionary?: %@", ([[dictionary objectForKey:@"users"] isMemberOfClass:[NSDictionary class]])? @"Yes" : @"No");
NSLog(@"Is of type NSMutableDictionary?: %@", ([[dictionary objectForKey:@"users"] isMemberOfClass:[NSMutableDictionary class]])? @"Yes" : @"No");
but it always says No.
Thank you for your help.
A: You should use isKindOfClass: instead of isMemberOfClass: because collections are usually implemented as class clusters in Cocoa.
Also, NSLog(@"%@", NSStringFromClass([[dictionary objectForKey:@"users"] class])) is much shorter to write than checking every possible class individually.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Handle Malformed Remote JSONP Response this is a continuation of my original question here link
You can see through my rather lengthy conversion with aaronfrost that we determined the jquery was loading in the .php (as seen on the network tab in CHROME) however it's trying to be ran as a script immediately. My question is where or not it's possible to load that in as plain text and simply then do a js parse out the needed data. Doesn't have to be jQuery this was just the route we were going in this example. I've also tried with the following code and recieve the exact same "Unexpected token" error. I think if there were a way to just some how handle the malformed JSON client side we would be able to make this work, in a ugly sort of way.
If javascript doesn't work do you think going the route of a java applet (preserve client cookies, non-server side) would achieve the desired end result i'm looking for?
<script type="application/javascript" src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js"></script>
<script type="application/javascript">
var url = 'http://www.makecashnow.mobi/jsonp_test.php';
//<!-[CDATA[
function JSONscriptRequest(fullUrl) {
// REST request path
this.fullUrl = fullUrl;
// Keep IE from caching requests
//this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
// Get the DOM location to put the script tag
this.headLoc = document.getElementsByTagName("head").item(0);
// Generate a unique script tag id
this.scriptId = 'JscriptId' + JSONscriptRequest.scriptCounter++;
}
// Static script ID counter
JSONscriptRequest.scriptCounter = 1;
// buildScriptTag method
//
JSONscriptRequest.prototype.buildScriptTag = function () {
// Create the script tag
this.scriptObj = document.createElement("script");
// Add script object attributes
this.scriptObj.setAttribute("type", "text/javascript");
this.scriptObj.setAttribute("charset", "utf-8");
//this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
this.scriptObj.setAttribute("src", this.fullUrl);
this.scriptObj.setAttribute("id", this.scriptId);
}
// removeScriptTag method
//
JSONscriptRequest.prototype.removeScriptTag = function () {
// Destroy the script tag
this.headLoc.removeChild(this.scriptObj);
}
// addScriptTag method
//
JSONscriptRequest.prototype.addScriptTag = function () {
// Create the script tag
this.headLoc.appendChild(this.scriptObj);
}
var obj = new JSONscriptRequest(url);
obj.buildScriptTag();
obj.addScriptTag();
//]]>
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: EF and POCOs. How to properly set up my project Recently I started working with EF 4.1 in .NET and had sort of positive experience until today when I tried to set up my own project (so far I was working on projects started by somebody else).
The thing just doesn't want to work out of the box. I don't do anything special. Actually, first it worked, then it stopped working out of blue and now after 4 hours of wasting my time I am writing this post.
My solution consists of 3 projects:
WebApp (where my app live)
DataAccess
BusinessObjects
DataAccess contains EntityModel.edmx and EntityModel.Context.tt file.
BusinessObjects contains EntityModel.tt with all underlying objects. I used ADO.NET DbContext generator to generate objects.
Namespace for EntityModel.Context.tt is set to BusinessObjects.
WebApp and DataAccess are referencing BusinessObjects project.
BusinessObjects doesn't reference anything.
(I believe I did set up this correctly. EntityModle.tt is able to see edmx file and objects get created when I edit file.)
So, at this point projects compile nicely with no errors.
In my next step I am adding EntityDataSource to my default.aspx page and after I choose my connection in datasource configuration (one from web.config) I get error: The metadata specified in this connection string could not be loaded. Consider rebuilding web project... Unable to load specified metadata resource.
I had this problem before when I would misspell something in my connection string, change model name, or similar, but now I didn't do anything. I recreated edmx file and its POCOs several times making sure I copy connection string from app.config. It simply doesn't work.
Any help is appreciated.
Thanks.
A: You will have to change the connection string in your web.config as such:
connectionString="metadata=res://*/;provider=System.Data.SqlClient;provider...etc...
Basically: metadata=res://*/; will try to find the embedded metadata files (csdl, msl, ssdl) in all the referenced assemblies in the project and you'll have a better luck locating the embedded resources that are generated as artifacts of the edmx file.
Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ASP.NET: Implementing ISessionIDManager for cookieless sessions? Question:
I'm writing a custom session provider.
So far it works excellently.
I decided I wanted to add a customized ISessionIDManager, to control the session id.
It already works fine for cookie sessions.
But when I swich to cookieless, like this:
<sessionState mode="Custom" customProvider="custom_provider" cookieless="true" timeout="1"
sessionIDManagerType="Samples.AspNet.Session.MySessionIDManager"
sqlConnectionString="Data Source=localhost;Initial Catalog=TestDB;User Id=SomeUser;Password=SomePassword;"
sqlCommandTimeout="10"
>
<!-- timeout in minutes-->
<providers>
<add name="custom_provider" type="Test.WebSession.CustomSessionStoreProvider" />
</providers>
</sessionState>
Then it redirects to:
http://localhost:52897/(77bb065f-d2e9-4cfc-8117-8b89a40e00d8)/default.aspx
and this throws HTTP 404.
I understand why, as there is no such folder.
But when you use the default session manager (the one that ships with asp.net), and switch to cookieless, the URL looks like this:
http://localhost:52897/(S(sq2abm453wnasg45pvboee45))/DisplaySessionValues.aspx
and there is no HTTP 404...
I tried adding the (S and ) to my session-id in brackets in the url, but that didn't help.
What am I missing ?
using System;
using System.Configuration;
using System.Web.Configuration;
using System.Web;
using System.Web.SessionState;
// http://allantech.blogspot.com/2011/04/cookieless-session-state-in-aspnet.html
// http://forums.asp.net/t/1082784.aspx/1
// http://stackoverflow.com/questions/4612310/implementing-a-custom-sessionidmanager
// http://msdn.microsoft.com/en-us/library/system.web.sessionstate.isessionidmanager.aspx
// http://msdn.microsoft.com/en-us/library/system.web.sessionstate.isessionidmanager(v=vs.80).aspx
namespace Samples.AspNet.Session
{
// Samples.AspNet.Session.MySessionIDManager
public class MySessionIDManager : IHttpModule, ISessionIDManager
{
protected SessionStateSection pConfig = null;
internal const string HeaderName = "AspFilterSessionId";
protected void InitializeModule()
{
// Obtain session-state configuration settings.
if (pConfig == null)
{
Configuration cfg =
WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
pConfig = (SessionStateSection)cfg.GetSection("system.web/sessionState");
} // End if (pConfig == null)
}
//
// IHttpModule Members
//
//
// IHttpModule.Init
//
public void Init(HttpApplication app)
{
//InitializeModule();
} // End Sub Init
//
// IHttpModule.Dispose
//
public void Dispose()
{
} // End Sub Dispose
//
// ISessionIDManager Members
//
//
// ISessionIDManager.Initialize
//
public void Initialize()
{
InitializeModule();
} // End Sub Initialize
//
// ISessionIDManager.InitializeRequest
//
public bool InitializeRequest(
HttpContext context,
bool suppressAutoDetectRedirect,
out bool supportSessionIDReissue
)
{
if (pConfig.Cookieless == HttpCookieMode.UseCookies)
{
supportSessionIDReissue = false;
return false;
}
else
{
supportSessionIDReissue = true;
return context.Response.IsRequestBeingRedirected;
}
} // End Function InitializeRequest
//
// ISessionIDManager.GetSessionID
//
public string GetSessionID(HttpContext context)
{
string id = null;
if (pConfig.Cookieless == HttpCookieMode.UseUri)
{
string tmp = context.Request.Headers[HeaderName];
if (tmp != null)
id = HttpUtility.UrlDecode(id);
// Retrieve the SessionID from the URI.
}
else
{
if (context.Request.Cookies.Count > 0)
{
id = context.Request.Cookies[pConfig.CookieName].Value;
id = HttpUtility.UrlDecode(id);
}
}
// Verify that the retrieved SessionID is valid. If not, return null.
if (!Validate(id))
id = null;
return id;
} // End Function GetSessionID
//
// ISessionIDManager.CreateSessionID
//
public string CreateSessionID(HttpContext context)
{
return System.Guid.NewGuid().ToString();
} // End Function CreateSessionID
//
// ISessionIDManager.RemoveSessionID
//
public void RemoveSessionID(HttpContext context)
{
context.Response.Cookies.Remove(pConfig.CookieName);
} // End Sub RemoveSessionID
public static string InsertSessionId(string id, string path)
{
string dir = GetDirectory(path);
if (!dir.EndsWith("/"))
dir += "/";
string appvpath = HttpRuntime.AppDomainAppVirtualPath;
if (!appvpath.EndsWith("/"))
appvpath += "/";
if (path.StartsWith(appvpath))
path = path.Substring(appvpath.Length);
if (path[0] == '/')
path = path.Length > 1 ? path.Substring(1) : "";
// //http://localhost:52897/(S(sq2abm453wnasg45pvboee45))/DisplaySessionValues.aspx
return Canonic(appvpath + "(" + id + ")/" + path);
//return Canonic(appvpath + "(S(" + id + "))/" + path);
}
public static bool IsRooted(string path)
{
if (path == null || path.Length == 0)
return true;
char c = path[0];
if (c == '/' || c == '\\')
return true;
return false;
}
public static string Canonic(string path)
{
char[] path_sep = { '\\', '/' };
bool isRooted = IsRooted(path);
bool endsWithSlash = path.EndsWith("/");
string[] parts = path.Split(path_sep);
int end = parts.Length;
int dest = 0;
for (int i = 0; i < end; i++)
{
string current = parts[i];
if (current.Length == 0)
continue;
if (current == ".")
continue;
if (current == "..")
{
dest--;
continue;
}
if (dest < 0)
if (!isRooted)
throw new HttpException("Invalid path.");
else
dest = 0;
parts[dest++] = current;
}
if (dest < 0)
throw new HttpException("Invalid path.");
if (dest == 0)
return "/";
string str = String.Join("/", parts, 0, dest);
str = RemoveDoubleSlashes(str);
if (isRooted)
str = "/" + str;
if (endsWithSlash)
str = str + "/";
return str;
}
public static string GetDirectory(string url)
{
url = url.Replace('\\', '/');
int last = url.LastIndexOf('/');
if (last > 0)
{
if (last < url.Length)
last++;
return RemoveDoubleSlashes(url.Substring(0, last));
}
return "/";
}
public static string RemoveDoubleSlashes (string input)
{
// MS VirtualPathUtility removes duplicate '/'
int index = -1;
for (int i = 1; i < input.Length; i++)
if (input [i] == '/' && input [i - 1] == '/') {
index = i - 1;
break;
}
if (index == -1) // common case optimization
return input;
System.Text.StringBuilder sb = new System.Text.StringBuilder(input.Length);
sb.Append (input, 0, index);
for (int i = index; i < input.Length; i++) {
if (input [i] == '/') {
int next = i + 1;
if (next < input.Length && input [next] == '/')
continue;
sb.Append ('/');
}
else {
sb.Append (input [i]);
}
}
return sb.ToString ();
}
// http://www.dotnetfunda.com/articles/article1531-how-to-add-custom-headers-into-readonly-httprequest-object-using-httpmodule-.aspx
public void SetHeader(string strHeaderName, string strValue)
{
//get a reference
System.Collections.Specialized.NameValueCollection headers = HttpContext.Current.Request.Headers;
//get a type
Type t = headers.GetType();
//get the property
System.Reflection.PropertyInfo prop = t.GetProperty(
"IsReadOnly",
System.Reflection.BindingFlags.Instance
| System.Reflection.BindingFlags.IgnoreCase
| System.Reflection.BindingFlags.NonPublic
| System.Reflection.BindingFlags.FlattenHierarchy
| System.Reflection.BindingFlags.NonPublic
| System.Reflection.BindingFlags.Public
| System.Reflection.BindingFlags.FlattenHierarchy
);
//unset readonly
prop.SetValue(headers, false, null); // Set Read-Only to false
//add a header
//HttpContext.Current.Request.Headers.Add(strHeaderName, strValue);
//headers.Add(strHeaderName, strValue);
t.InvokeMember("BaseAdd",
System.Reflection.BindingFlags.InvokeMethod
| System.Reflection.BindingFlags.NonPublic
| System.Reflection.BindingFlags.Instance,
null,
headers,
new object[] { strHeaderName, new System.Collections.ArrayList { strValue } }
);
prop.SetValue(headers, true, null); // Reset Read-Only to true
// Victory !
//string strCheckHeaders = string.Join(Environment.NewLine, HttpContext.Current.Request.Headers.AllKeys);
}
//
// ISessionIDManager.SaveSessionID
//
public void SaveSessionID(HttpContext context, string id, out bool redirected, out bool cookieAdded)
{
if (!Validate(id))
throw new HttpException("Invalid session ID");
Type t = base.GetType();
redirected = false;
cookieAdded = false;
if (pConfig.Cookieless == HttpCookieMode.UseUri)
{
// Add the SessionID to the URI. Set the redirected variable as appropriate.
//context.Request.Headers.Add(HeaderName, id);
//context.Request.Headers.Set(HeaderName, id);
SetHeader(HeaderName, id);
cookieAdded = false;
redirected = true;
UriBuilder newUri = new UriBuilder(context.Request.Url);
newUri.Path = InsertSessionId(id, context.Request.FilePath);
//http://localhost:52897/(S(sq2abm453wnasg45pvboee45))/DisplaySessionValues.aspx
context.Response.Redirect(newUri.Uri.PathAndQuery, false);
context.ApplicationInstance.CompleteRequest(); // Important !
return;
}
else
{
context.Response.Cookies.Add(new HttpCookie(pConfig.CookieName, id));
cookieAdded = true;
}
} // End Sub SaveSessionID
//
// ISessionIDManager.Validate
//
public bool Validate(string id)
{
try
{
Guid testGuid = new Guid(id);
if (id == testGuid.ToString())
return true;
}
catch
{
}
return false;
} // End Function Validate
} // End Class MySessionIDManager : IHttpModule, ISessionIDManager
} // End Namespace Samples.AspNet.Session
A: Creating a custom session id manager from scratch seems like a lot of work. What about inheriting from System.Web.SessionState.SessionIDManager class and overriding the CreateSessionID method?
public class MySessionIDManager : SessionIDManager, ISessionIDManager
{
public override string CreateSessionID(HttpContext context)
{
return System.Guid.NewGuid().ToString("N");
}
}
A: When all else fails, crack open the .NET implementation with Reflector or ILSpy and see what they are doing different.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623453",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Getting the average RGB color of a CGImageRef in iOS I've been struggling with this for a couple of hours, and I'm hoping someone else has some insight. I'm looking for a way to get the average RGB color of a 1x1 UIImage. So far I've created a CGImageRef from the UIImage, but I'm really new to CoreGraphics, so I'm not sure where to go from there. Any help is appreciated. Thanks!
A: If you have a CGImage, you get the data by calling
CGDataProviderRef CGImageGetDataProvider (
CGImageRef image
);
CGImage doc
Then you can copy the data
CFDataRef CGDataProviderCopyData(
CGDataProviderRef provider
);
CGDataProvider doc
Since CFData is the same as NSData you can cast it and retrieve the bytes
- (const void *)bytes
CFData doc
NSData doc
Now you have the raw bytes, you can do anything with them, use
CGImageAlphaInfo CGImageGetAlphaInfo (
CGImageRef image
);
CGBitmapInfo CGImageGetBitmapInfo (
CGImageRef image
);
to get information how is the image data stored in the bytes you got.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why do I get a segmentation fault while iterating through this vector? I need to go through this vector and delete the duplicates. A segmentation fault is occurring somewhere within this code. My guess is that it has something to do with deleting elements while the iterator is going through, but I don't really have a concrete understanding of how these iterators are actually working yet, so I can't figure it out.
vector<char *>::iterator iter;
for (iter = v->begin(); iter != v->end()-1; iter++ ){
char *aString = *iter;
int n = 1;
while(iter+n != v->end()){
int comparison = strcmp(aString, *(iter+n));
if(comparison == 0){
v->erase(iter + n);
}
n++;
}
}
A: You are not properly iterating through the remainder of the vector. An alternative to what Beta suggested is to use erase-remove with remove_if. Like this:
bool compare_strings(char * aString,char * bString)
{
return 0==strcmp(aString,bString);
}
void remove_duplicates(vector<char *> * v)
{
vector<char *>::iterator iter;
for (iter = v->begin(); iter != v->end(); iter++ ) {
v->erase(std::remove_if(iter+1,v->end(),compare_strings),v->end());
}
}
A: Really, you just have a couple off-by-one problems here. You were comparing incorrectly against end() and incrementing n when you erased an element:
for (iter = v->begin(); iter != v->end()-1; iter++ ){
^^^^^^^^
And
while(iter+n != v->end())
^^
The following will do what you want (and demonstrate that it works):
int main()
{
std::vector<const char*> v (4, "this");
std::vector<const char *>::iterator iter;
for (iter = v.begin(); iter < v.end(); iter++ ) {
std::cout << *iter << " ";
}
std::cout << std::endl;
for (iter = v.begin(); iter < v.end(); iter++ ){
const char *aString = *iter;
int n = 1;
while(iter+n < v.end()){
int comparison = strcmp(aString, *(iter+n));
if(comparison == 0){
v.erase(iter + n);
}
else
n++;
}
}
for (iter = v.begin(); iter < v.end(); iter++ ) {
std::cout << *iter << std::endl;
}
}
Output is:
this this this this
this
A: When you erase an element from the vector, the vector gets one element shorter. Try this:
if(comparison == 0){
v->erase(iter + n);
}
else{
n++;
}
A: Erasing from a vector invalidates all iterators from the erasee onwards, so you should probably not construct your loop the way you do, and rather use a standard idiom like this:
for (auto it = v.begin(); it != v.end(); ++it) // no end() - 1 -- may not be legal!
{
for (auto jt = it; jt != v.end(); )
{
if (jt == it) continue;
if (strcmp(*it, *jt) == 0)
{
jt = v.erase(jt);
}
else
{
++jt;
}
}
}
This code avoids the check for an empty vector, which your code fails to account for.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP Authentication class for Twitter and Facebook I'm looking for a simple PHP class that supports Twitter and Facebook authentication. I don't need to access their respective API's or post anything. just simple, painless, basic auth.
A: Maybe janrain coud fit you if you don't have enough traffic or you are able to pay some bucks on this
http://www.janrain.com
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623460",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: compact storage for non static binary trees I have seen array based implementations of static binary trees which do not waste memory for pointers and instead do operations on the current index to go to its parent or children. Is there any articles that talk about similar methods for binary trees where you will have to insert or delete. I can see that array will no longer be useful for this unless you have an upper bound on the number of insertions that are allowed.
A: It's always possible to build a binary tree in an array, using simple arithmetic to find child nodes from the parent. A common method (particularly for binary heaps) is to use the following...
left_child_index = (2 * parent_index) + 1
right_child_index = (2 * parent_index) + 2
So the root node at 0 has children at 1 and 2, the node at 1 has children at 3 and 4 etc.
The downside of this scheme is that while you gain space by not storing pointers, you generally lose space by needing to leave gaps in the array for unused nodes. Binary heaps avoid this by being complete binary trees - every node in the range for the current number of items is valid. This works for heaps, but cannot work for binary search tree operations.
As long as you can resize your arrays (e.g. std::vector in C++), you don't need to place an upper bound on the number of inserts, but you can end up with a lot of gaps in the deeper parts of your array, especially if the tree gets unbalanced.
You also need some way to determine if a position in the array contains a valid node or not - either a flag or a data value that cannot occur in a valid node. Flags could potentially be stored as a packed bit-array, separate from the main nodes.
Another disadvantage is that restructuring the tree means moving data around - not just adjusting pointers. Pointer rotations (needed for many balanced binary trees, such as red-black trees and AVL trees) become potentially very costly operations - they don't just need to move the usual three nodes, but the entire subtree descended from the rotated nodes.
That said, if your items are very small, and if either your tree will stay small or you're OK with a simple unbalanced tree, it's just about possible that this scheme could be useful. This could just about be plausible as a set-of-integers data structure, maybe.
BTW - "plausible" doesn't mean "recommended". Even if you manage to find a case where it's more efficient, I'd find it hard to believe the development time was justified.
Possibly more useful...
Multiway trees contain small arrays of items in each node, rather than the usual one key. They are most often used for database indexes on hard disk. The most well known are B trees, B+ trees and B* trees.
Multiway trees have child node pointers, but for a node that can hold at most n keys, the number of child pointers is typically either n or n+1 - not twice n. Also, a common strategy is to use different node layouts for branch and leaf nodes. Only branch nodes have child pointers. Every data item is in a leaf node, and only leaf nodes contain non-key data. Branch nodes are purely used to guide searches. Since leaf nodes are by far the most numerous nodes, not having child pointers in them is a useful saving.
However - multiway tree nodes are rarely packed full. Again, there's a space overhead for unused array slots. The usual rule is that every node (except the root) must be at least half full. Some implementations put quite a bit of effort into avoiding splitting nodes, and thereby minimizing space overheads, but there is generally an expected overhead roughly proportional to the number of items.
I've also heard of a form of tree that holds multiple keys per node, but only has two child pointers per node. I can't even remember what this is called, I'm afraid.
It's also possible to store (parent pointer, child pointer) pairs in a separate data structure. This is fairly common for representing trees in databases, using a table of (parent ID, child ID) pairs, or a table of (parent ID, sibling index, child ID) triples or whatever. One advantage is that you don't need to store the 'null' pointers.
However, possibly the best option, rather than trying to reduce or eliminate the overhead for storing pointers, is to put that overhead to better use. Threaded binary trees make better use of child pointers for supporting efficient traversals of the tree - http://en.wikipedia.org/wiki/Threaded_binary_tree.
A: In C++ at least, part of the benefit of using an array instead of individually allocated structures is to avoid the overhead of creating each object. (An array of structures in C++ is continuous in memory, with no headers or allocation alignment issues) Saving one pointer might be small by comparison.
Unfortunately, in Java an array of Objects don't work that way, so using an array won't give you the benefit you might imagine. In C++ a reference to each object is calculated, but in Java a reference to each object is stored in memory, even if they happen to be continuous.
The only thing Java does for you is to use 32-bit references in a 64-bit JVM.
Unless you have a memory limited device, or an exceedingly large data structure (e.g. many millions of elements), you are highly unlikely to notice the difference and you can buy 16 GB for less than £100.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623462",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What's the best way of constantly resizing elements with the mouse? What's the best way of constantly resizing elements using clicking and holding a resize image in the bottom-right corner of the element? Is there a specific empty element that has resizing built in or a style to use that would be better than using a while loop in JavaScript?
A: Here you go man:
http://jsfiddle.net/d9hsG/
function c(a){console.log(a)}
function coords(el){
var curleft, curtop;
curleft=curtop=0;
do{
curleft+=el.offsetLeft;
curtop+=el.offsetTop;
} while(el=el.offsetParent);
return [curleft,curtop];
}
Resizer = {
attach: function(el,minh,minw){
var rs=el.resizer=el.getElementsByClassName('drag')[0];
rs.resizeParent=el;
if(minh==undefined){
el.minh=rs.offsetHeight*2;
}
if(minw==undefined){
el.minw=rs.offsetWidth*2;
}
rs.onmousedown = Resizer.begin;
},
begin: function(e){
var el=Resizer.el=this.resizeParent;
var e=e||window.event;
this.lastx=e.clientX;
this.lasty=e.clientY;
document.onmousemove=Resizer.resize;
document.onmouseup=Resizer.end;
return false;
},
resize: function(e){
var e = e || window.event;
var x,y,mx,my,el,rs,neww,newh;
el=Resizer.el;
rs=el.resizer;
mx=e.clientX;
my=e.clientY;
neww=(el.clientWidth-(rs.lastx-mx));
newh=(el.clientHeight-(rs.lasty-my));
if(neww>=el.minw){
el.style.width=neww+'px';
rs.lastx=mx;
}
else{
rs.lastx-=parseInt(el.style.width)-el.minw;
el.style.width=el.minw+'px';
}
if(newh>=el.minh){
el.style.height=newh+'px';
rs.lasty=my;
}
else{
rs.lasty-=parseInt(el.style.height)-el.minh;
el.style.height=el.minh+'px';
}
return false;
},
end: function(){
document.onmouseup=null;
document.onmousemove=null;
}
};
window.onload=function(){
Resizer.attach(document.getElementsByClassName('resize')[0]);
}
Your HTML needs to look like:
<div class="resize"><
div class="drag"></div>
</div>
Neither one needs to be a div, but the resizeable one's class needs to be "resize" and the draggable element's class needs to be "drag".
Attach it with:
Resizer.attach(element);
...where element is the one to be resized.
Works on multiple elements, as shown in the jsfiddle. You can also pass in a minimum height and minimum width. If you don't, it automatically makes them twice the height of the draggable element.
It currently does have a problem when you're scrolled all the way down. I'm not sure how to counter it, but I'll work on it more later.
A: The general approach goes something like this:
*
*When onmousedown fires on the resize target, start tracking onmousemove
*When onmousemove fires, resize the element
*When onmouseup fires, clear the onmousemove handler
So basically you just respond to events, there are no while loops or anything involved.
It can be somewhat tricky to accomplish so that it works nicely, so I would suggest seeing if there's a JS library you could use. A pretty simple way to get this behavior would be to use jQuery UI's resizable component
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623464",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: NHibernate - Is there a way to map a formula that uses sql function and returns Table?! I have a sql function that returns table and I need to map it to a collection i'm trying with formula but as far as i can tell formula is good only to single returned value (right?!?)
is there a way to use formula and map it to a DataTable or some other collection
<propery name="Prop" type="DataTable" formula="select function(...)"/>
if not what are my other options?!
thanks!
A: http://ayende.com/blog/1720/using-sql-functions-in-nhibernate
For return value you can use DTO or Persistence class
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623465",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can encode('ascii', 'ignore') throw a UnicodeDecodeError? This line
data = get_url_contents(r[0]).encode('ascii', 'ignore')
produces this error
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 11450: ordinal not in range(128)
Why? I assumed that because I'm using 'ignore' that it should be impossible to have decode errors when saving the output to a value to a string variable.
A: Due to a quirk of Python 2, you can call encode on a byte string (i.e. text that's already encoded). In this case, it first tries to convert it to a unicode object by decoding with ascii. So, if get_url_contents is returning a byte string, your line effectively does this:
get_url_contents(r[0]).decode('ascii').encode('ascii', 'ignore')
In Python 3, byte strings don't have an encode method, so the same problem would just cause an AttributeError.
(Of course, I don't know that this is the problem - it could be related to the get_url_contents function. But what I've described above is my best guess)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623476",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Advice needed: Geolocation for c# web app - need country location to set what user can see or not My scenario is I want to trap the user's country when they access the web page. Based on the user's country i want to set a cookie that will allow me to do a simple "if" statement in the code behind that would let them to see certain information on web pages.
I started doing some research and i can use the Google Geocode V3 and get the country from code behind c#. But to get the Google Geocode to work i need to pass in the longitude and latitude.
And the only way i've seen this is from Javascript call like:
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
});
}
So i'm hoping for some advice if I'm doing this right.
On the loaded method in my c# code I think I can get the javascript to run by ScriptManager.RegisterStartUpScript method. So my challenge now is getting the latitude and longitude values. Since i'm not going a button event or something, i need to get those values out and then pass them into my c# method that would get the country code using the Google Geocode.
Does that sound right? If this is the right path, can someone suggest how i could get those values from the javascript?
thanks.
A: You could make an Ajax call to your server which contains the client's geolocation.
What about using RegionInfo.CurrentRegion instead? That will give you the country according to the browser headers assuming you have globalization culture turned to auto. This is simpler, but will also not be 100% correct all the time since the user can change their culture settings.
You may also want to look into using IP address based geolocation which might be a little more accurate.
It would help to know why you're trying to do this.
A: Most sites that really need to make sure that content stays within national boundaries work with content that is chargeable - for instance, most music sites, Amazon, and so on.
Their simple, yet effective, technique is to use the country on the user's billing address on their credit card.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: html
* adding unwanted space underneath every
* I am getting an unwanted visual quirk from creating <li>'s within an <ul>. It is producing an unwanted space underneath each item.
This is the simplified code that I am currently using.
<ul style="margin:0; padding:0;">
<li style="border:1px solid #000; margin:0; padding:0;">Item 1</li>
<li style="border:1px solid #000; margin:0; padding:0;">Item 2</li>
<li style="border:1px solid #000; margin:0; padding:0;">Item 3</li>
<li style="border:1px solid #000; margin:0; padding:0;">Item 4</li>
<li style="border:1px solid #000; margin:0; padding:0;">Item 5</li>
</ul>
If you notice, there is a space underneath the text for each <li> even though I've stated that I want my margin and padding to be 0.
This happening in both Google Chrome v14 and Firefox v4.
Here's the screenshow:
I updated the jsfiddle to include the image: http://jsfiddle.net/Ab5e9/4/
edit: added the margin:0 and padding:0 to each <li>
edit: added image and jsfiddle
A: You've stated that you want no padding and no margin on the ul only.
You need to do that for the lis to.
Either do this
<li style="border:1px solid #000; margin:0; padding:0;">Item 1</li>
or add these styles to your stylesheet (better as you only need to do it once AND it makes your HTML less cluttered)
ul{
margin:0;
padding:0;
}
li{
border:1px solid #000;
margin:0;
padding:0;
}
Example: http://jsfiddle.net/jasongennaro/Ab5e9/
EDIT
As per the comment from @EverTheLearner
I don't know how else to describe it. There is a space
there. Its very tiny but its there. Look at the space
above the text and then the space below the text. There is a
difference there.
here is what I see when I increase the zoom on the browser to 250%
There must be something else there. Please post a link to a live example.
EDIT 2
Following the updated fiddle, the problem is not between the lis but between the text and the bottom of the li.
One way to get rid of this is the change the line-height.
In the example below, I set it to .8em
Example 2: http://jsfiddle.net/jasongennaro/Ab5e9/1/
A: As stated above by Jason Gennaro, the issue with the "space" lies in the default line-height property for your text. You can alter that attribute like so:
CSS
li {
line-height: .8em; /* 1em = standard line height */
}
A: Margin and padding of 0 on an unordered list does not mean margin and padding of 0 on each list item inside it.
If you want a list item to have a specific margin and/or padding, then you have to set that on the list item.
A: Since your example includes an image, perhaps that is where your issue is to be found. Descenders on text can cause even empty inline elements to have height, if I understand it aright. Try vertical-align: baseline or bottom on your image; I've addressed similar-seeming problems in this way before, at any rate.
Edit: my bad, your second arrow points at an image-less li; nevertheless I'll leave this here in case it points you in the right direction,
A: Without seeing the code in context of everything else, it's hard to say. But try setting line-height: 1em;. It could be the line-height is set to something more, causing the space.
A: All HTML elements automatically adds a small amount of padding between one line and the next (this is so one line isn't touching the next all the time, that would look awful).
And padding isn't allowed negative values, so you can't actually make the boxes any smaller (vertically). Except that you can adjust the line-height. However, you can move the boxes closer together by giving the margin property a negative value.
I used ul li {margin-top:-2px; margin-bottom:-2px} you can continue to move them closer together but if you do move them any closer together it looks weird because the boxes overlap.
I set the line-height to 1 to minimize space between the lines and then I moved the boxes closer together. My example is as close together as you can get the boxes.
Example: http://jsfiddle.net/MarkKramer/Ab5e9/12/
also, it was a waste of your time typing the same inline style for every li you should've just typed the style into a style sheet, like I did in the example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Zero Threaded Process? Does a process have to have at least one thread in it? Is it possible for a process to be void of any threads, or does this not make sense?
A: A process usually has at least one thread. Wikipedia has the definition:
a thread of execution is the smallest unit of processing that can be scheduled by an operating system. The implementation of threads and processes differs from one operating system to another, but in most cases, a thread is contained inside a process.
The MSDN backs this up:
A processor executes threads, not processes, so each application has at least one process, and a process always has at least one thread of execution, known as the primary thread.
Though it does go on to say:
A process can have zero or more single-threaded apartments and zero or one multithreaded apartment.
Which implies that if both the number of single-threaded apartments and multithreaded apartments could be zero. However, the process wouldn't do much :)
A: In Unix-like operating systems, it's possible to have a zombie process, where an entry still exists in the process table even though there are no (longer) any threads.
A: You can choose not to use an explicit threading library, or an operating system that has no concept of threads (and so doesn't call it a thread), but for most modern programming all programs have at least one thread of execution (generally referred to as a main thread or UI thread or similar). If that exits, so does the process.
Thought experiment: what would a process with zero threads of execution do?
A: In theory, I don't see why not. But it would be impossible with the popular operating systems.
A process typically consists of a few different parts:
*
*Threads
*Memory space
*File discriptors
*Environment (root directory, current directory, etc.)
*Privileges (UID, etc.)
*Et cetera
In theory, a process could exist with no threads as an RPC server. Other processes would make RPC calls which spawn threads in the server process, and then the threads disappear when the function returns. I don't know of any operating systems that work this way.
On most OSs, the process exits either when the last thread exits, or when the main thread exits.
Note: This ignores the "useless" cases such as zombie processes, which have no threads but don't do anything.
A: "main" itself is thread. Its a thread that gets executed. So, every process runs on at least one thread.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: String of boolean values to an array? I created the code below to print out all of the values of a string to 'true' or 'false'. I would like to fill an array with all the printed values "True true false true...." Right now when I print out the values of the String str if it is not in the loop I only get the first value of the first character.
// First find out how many words and store in numWords
// Use "isDelim()" to determine delimiters versus words
//
// Create wordArr big enough to hold numWords Strings
// Fill up wordArr with words found in "phrase" parameter
public void Parse(String phrase) {
int len = phrase.length();
String str = null;
int isTrueCount = 0;
int isFalseCount = 0;
for (int i = 0; i < (len); i++) {
str = String.valueOf(!isDelim(phrase.charAt(i)));
System.out.println(str);
if (str == "true") {
isTrueCount++;
} else {
isFalseCount++;
}
}
System.out.println(isTrueCount);
System.out.println(isFalseCount);
}
Length of len is any arbitrary string/text file/keyboard input. I am hoping to use the true and false values within an array to pick out the true number of words from delims.
A: Don't use Strings for this as it adds unnecessary complexity. Simply increment your variable if the statement is true:
for (int i = 0; i < phrase.length(); i++) {
if (!isDelim(phrase.charAt(i))) {
isTrue++;
} else {
isFalse++;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623494",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Enlightening Usage of C++11 decltype I've just seen this really nice talk Rock Hard: C++ Evolving by Boris Jabes. In the section of the talk concerning Higher-Order Generic Programming he says that the following is an example of a function that is more generic with regards to its return type and leads to fewer template function overloads
template <typename Func>
auto deduce(const Func & f) -> decltype(f())
{..}
This however can be realized using plain template syntax as follows
template <typename Func>
Func deduce(const Func & f)
{..}
so I guess the example chosen doesn't really show the unique power of decltype. Can anyone give an example of such a more enlightening usage of decltype?
A: Your suspicions are incorrect.
void f() { }
Now deduce(&f) has type void, but with your rewrite, it has type void(*)(). In any case, everywhere you want to get the type of an expression or declaration, you use decltype (note the subtle difference in between these two. decltype(x) is not necessarily the same as decltype((x))).
For example, it's likely your Standard library implementation somewhere contains lines like
using size_t = decltype(sizeof(0));
using ptrdiff_t = decltype((int*)0 - (int*)0);
using nullptr_t = decltype(nullptr);
Finding out the correct return type of add has been a challenging problem throughout past C++. This is now an easy exercise.
template<typename A, typename B>
auto add(A const& a, B const& b) -> decltype(a + b) { return a + b; }
Little known is that you can use decltype before :: and in a pseudo destructor name
// has no effect
(0).~decltype(0)();
// it and ite will be iterators into an initializer list
auto x = { 1, 2, 3 };
decltype(x)::iterator it = x.begin(), ite = x.end();
A: std::for_each(c.begin(), c.end(), [](decltype (c.front()) val){val*=2;});
Autodeducting the value_type of the container c can't be done without decltype.
A: One place that I use it, is where I need to make a variable that must have same type of another variable . but I'm not sure if in future the type will stay same or not .
void foo(int a)//maybe in future type of a changed
{
decltype(a) b;
//do something with b
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623496",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Weird unresolved external errors I'm getting some Unresolved External Errors I can't seem to find a solution for:
1>MyApp.obj : error LNK2019: unresolved external symbol "public: void __thiscall Path::AddPoint(struct Point2D const &)" (?AddPoint@Path@@QAEXABUPoint2D@@@Z) referenced in function "public: static long __stdcall MyApp::WndProc(struct HWND__ *,unsigned int,unsigned int,long)" (?WndProc@MyApp@@SGJPAUHWND__@@IIJ@Z)
1>MyApp.obj : error LNK2019: unresolved external symbol "public: void __thiscall Path::ClrPath(void)" (?ClrPath@Path@@QAEXXZ) referenced in function "public: static long __stdcall MyApp::WndProc(struct HWND__ *,unsigned int,unsigned int,long)" (?WndProc@MyApp@@SGJPAUHWND__@@IIJ@Z)
1>MyApp.obj : error LNK2019: unresolved external symbol "public: enum TOOL __thiscall Path::GetTool(void)" (?GetTool@Path@@QAE?AW4TOOL@@XZ) referenced in function "public: static long __stdcall MyApp::WndProc(struct HWND__ *,unsigned int,unsigned int,long)" (?WndProc@MyApp@@SGJPAUHWND__@@IIJ@Z)
1>MyApp.obj : error LNK2019: unresolved external symbol "public: void __thiscall Path::SetTool(enum TOOL)" (?SetTool@Path@@QAEXW4TOOL@@@Z) referenced in function "public: static long __stdcall MyApp::WndProc(struct HWND__ *,unsigned int,unsigned int,long)" (?WndProc@MyApp@@SGJPAUHWND__@@IIJ@Z)
The weird thing is, I'm pretty sure I included everything correctly. Also, there's always one function that works of that class: DrawTo().
I tried to remove the 'inline' declaration for the other functions but it didn't seem to matter.
I also tried to rebuild it once, with just putting some extra endline in between two functions, and it compiled! Next time I tried compiling it didn't work again...
So I'm not entirely sure if I'm doing something wrong, or if it's the compiler... (Default VS2010 compiler) (actually, what's the name of that compiler? [comment or edit] )
Does anyone know what this could mean?
Here's the relevant code: (if you need to see more, comment and I'll edit)
Path.h
#pragma once
#ifndef PATH_H
#define PATH_H
#include "Defines.h"
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include "MyVector.h"
#include "Point2D.h"
#include "Tool.h"
class Path
{
public:
Path();
virtual ~Path();
bool DrawTo(HDC hDC);
inline void AddPoint(const Point2D& rkPoint);
inline Point2D GetPointAt(int iIndex) const;
inline int GetPointCount() const;
inline TOOL GetTool();
inline void SetTool(TOOL t);
inline void SetColor1(COLORREF);
inline void SetColor2(COLORREF);
inline void ClrPath();
private:
MyVector<Point2D> m_PointVector;
TOOL m_Tool;
COLORREF m_Colour1;
COLORREF m_Colour2;
};
#endif
Path.cpp
#include "Path.h"
Path::Path()
{
m_Tool = Tool_Pen;
m_Colour1 = RGB(0,0,0);
m_Colour2 = RGB(255,255,255);
}
Path::~Path()
{}
bool Path::DrawTo(HDC hDC)
{
if(hDC == NULL || m_PointVector.GetLength() <= 0) {
return false;
}
switch (m_Tool) {
case Tool_Pen:
{
//////
break;
}
case Tool_Line:
{
/////
break;
}
case Tool_Ellipse:
{
//////
break;
}
case Tool_Rectangle:
{
//////
break;
}
case Tool_LineTrack:
{
//////
break;
}
}
return true;
}
Point2D Path::GetPointAt(int iIndex) const {
return m_PointVector.At(iIndex);
}
int Path::GetPointCount() const {
return m_PointVector.GetLength();
}
void Path::AddPoint(const Point2D& rkPoint) {
m_PointVector.PushBack(rkPoint);
}
TOOL Path::GetTool() {
return m_Tool;
}
void Path::SetTool(TOOL t) {
m_Tool = t;
}
void Path::SetColor1(COLORREF col) {
m_Colour1 = col;
}
void Path::SetColor2(COLORREF col) {
m_Colour2 = col;
}
void Path::ClrPath() {
m_PointVector.ClrAll();
}
MyApp.h
#pragma once
#ifndef MYAPP_H
#define MYAPP_H
#include "Defines.h"
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <string>
#include <iostream>
//app includes:
#include "MyHelperFuncs_Win32.h"
#include "BitmapPainter.h"
#include "Path.h"
//-------------
class MyApp
{
public:
MyApp();
virtual ~MyApp();
static LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
void Paint();
private:
void InitWindows();
HWND m_hWnd;
HDC m_hDC;
PAINTSTRUCT m_PaintStruct;
//app-specific:
BitmapPainter* m_pBitmapPainter;
Path* m_pPath;
//------------
};
#endif
MyApp::WndProc()
LRESULT MyApp::WndProc(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam)
{
if(iMsg == WM_CREATE)
{
CREATESTRUCT *pCS = (CREATESTRUCT*)lParam;
SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG)pCS->lpCreateParams);
}
else
{
//retrieve the stored "this" pointer
MyApp* pApp = (MyApp*)GetWindowLongPtr(hWnd, GWLP_USERDATA);
switch (iMsg)
{
case WM_PAINT:
{
pApp->Paint();
return 0;
}
case WM_COMMAND:
{
int wmId = LOWORD(wParam);
int wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_NEW:
{
//////
return 0;
case IDM_LOAD:
{
//////
return 0;
}
case IDM_SAVE:
{
//////
return 0;
}
case IDM_SAVEAS:
{
//////
return 0;
}
case IDM_EXIT:
{
DestroyWindow(hWnd);
return 0;
}
case IDM_COLOURMAIN:
{
//////
return 0;
}
case IDM_COLOURSECONDARY:
{
//////
return 0;
}
case IDM_PEN:
{
pApp->m_pPath->SetTool(Tool_Pen);
return 0;
}
case IDM_LINE:
{
pApp->m_pPath->SetTool(Tool_Line);
return 0;
}
case IDM_ELLIPSE:
{
pApp->m_pPath->SetTool(Tool_Ellipse);
return 0;
}
case IDM_RECTANGLE:
{
pApp->m_pPath->SetTool(Tool_Rectangle);
return 0;
}
case IDM_LINETRACK:
{
pApp->m_pPath->SetTool(Tool_LineTrack);
return 0;
}
default:
{
//////
return 0;
}
}
}
case WM_LBUTTONUP:
{
OutputDebugString(_T("Left Button Up\n "));
if(wParam & MK_CONTROL)OutputDebugString(_T("The CTRL key is down.\n "));
int x = LOWORD(lParam);
int y = HIWORD(lParam);
switch(pApp->m_pPath->GetTool()) {
case Tool_Pen:
{
pApp->m_pPath->DrawTo(pApp->m_hDC);
pApp->m_pPath->ClrPath();
InvalidateRect(pApp->m_hWnd,NULL,true);
}
}
return 0;
}
case WM_LBUTTONDOWN:
{
OutputDebugString(_T("Left Button Down\n "));
if(wParam & MK_CONTROL)OutputDebugString(_T("The CTRL key is down.\n "));
int x = LOWORD(lParam);
int y = HIWORD(lParam);
return 0;
}
case WM_RBUTTONUP:
{
OutputDebugString(_T("Right Button Up\n "));
if(wParam & MK_CONTROL)OutputDebugString(_T("The CTRL key is down.\n "));
int x = LOWORD(lParam);
int y = HIWORD(lParam);
return 0;
}
case WM_MOUSEMOVE:
{
OutputDebugString(_T("Mouse Moved\n "));
if(wParam & MK_CONTROL)OutputDebugString(_T("The CTRL key is down.\n "));
int x = LOWORD(lParam);
int y = HIWORD(lParam);
std::cout <<"Mouse Position: x=" << x << " y=" << y << "\n";
if (wParam & MK_LBUTTON) {
switch(pApp->m_pPath->GetTool()) {
case Tool_Pen:
{
Point2D p;
p.x = x;
p.y = y;
pApp->m_pPath->AddPoint(p);
InvalidateRect(pApp->m_hWnd,NULL,true);
}
}
}
return 0;
}
case WM_DESTROY:
{
PostQuitMessage(0);
return 0;
}
}
}
return DefWindowProc (hWnd, iMsg, wParam, lParam) ;
}
A: Take out those "inline" declarations (because code isn't inlined unless it's actually in the header file). And then do a clean build followed by a full build.
A: The only function that works is the one that is not inlined.
If you think about it you'll realize it makes sense. When the compiler is compiling MyApp.cpp it finds that you are calling a method declared as inline. So the compiler needs to copy the code for that method instead of just calling it. The problem is, how does the compiler know where that method is defined? The only way the compiler can see it is if it the implementation of the inline methods is either in Path.h or in some other header file that is included by MyApp.cpp.
So the simplest solution is for you to move the implementation of all those inline methods into the Path.h file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623503",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Loop through navigation menu with jQuery relative(?) links:
http://api.jquery.com/each/
http://api.jquery.com/jQuery.each/
hello
i got this navigation menu
<table>
<tr>
<td><div id="menuItem1" class="menuItem"><a href="http://www.w3schools.com">PORTFOLIO</a></div></td>
<td><div id="menuItem2" class="menuItem">ABOUT ME</div></td>
<td><div id="menuItem3" class="menuItem">CONTACT</div></td>
</tr>
<tr>
<td><div id="selectA1" class="selectA current"></div></td>
<td><div id="selectA2" class="selectA"></div></td>
<td><div id="selectA3" class="selectA"></div></td>
</tr>
</table>
the selectA class is a rectangle that will select the menuItem when your mouse moves over it
the long code would be like
$("#menuItem1").mouseover(function () {
$("#selectA1").stop().animate({opacity: 1},{ queue: false, duration: 200 });
});
$("#menuItem2").mouseover(function () {
$("#selectA2").stop().animate({opacity: 1},{ queue: false, duration: 200 });
});
$("#menuItem3").mouseover(function () {
$("#selectA3").stop().animate({opacity: 1},{ queue: false, duration: 200 });
});
$("#menuItem1").mouseout(function () {
$("#selectA1").stop().animate({opacity: 0},{ queue: false, duration: 400 });
});
$("#menuItem2").mouseout(function () {
$("#selectA2").stop().animate({opacity: 0},{ queue: false, duration: 400 });
});
$("#menuItem3").mouseout(function () {
$("#selectA3").stop().animate({opacity: 0},{ queue: false, duration: 400 });
});
but i thought it could be shorter if i'd loop over those
so i tried to loop through those menuItems so that the rectangle will appear for all menu items
what i tried in javascript, all didnt work
var i=1;
for (i=1;i<=3;i++) {
$("#menuItem"+i).mouseover(function () {
$("#selectA"+i).stop().animate({opacity: 1},{ queue: false, duration: 200 });
});
}
and
var i=1;
while (i<=3) {
$("#menuItem"+i).mouseover(function () {
$("#selectA"+i).stop().animate({opacity: 1},{ queue: false, duration: 200 });
});
and
$(".selectA").each(function (i) {
$("#menuItem"+i).mouseover(function () {
$("#selectA"+i).stop().animate({opacity: 1},{ queue: false, duration: 200 });
});
}
i++;
}
thank you for your help
A: First of all, you would be better off with hover rather than a mouseover/mouseout pair.
Secondly, you don't need to use each at all, there is a nice simple relationship between your .menuItem and .selectA elements: they have the same suffix number in their id attributes. So, you could do the whole thing with something simple like this:
$('.menuItem').hover(
function() {
var n = this.id.replace(/[^\d]/g, '');
$('#selectA' + n).stop().animate({ opacity: 1 },{ queue: false, duration: 200 });
},
function() {
var n = this.id.replace(/[^\d]/g, '');
$('#selectA' + n).stop().animate({ opacity: 0 },{ queue: false, duration: 200 });
}
);
Demo: http://jsfiddle.net/ambiguous/eza8b/
As far as why this:
for(var i = 1; i <= 3; i++) {
$("#menuItem" + i).mouseover(function () {
$("#selectA" + i).stop().animate({opacity: 1}, {queue: false, duration: 200 });
});
}
doesn't work goes, you're having a classic closure problem. The functions that you supply to .mouseover are closures over i so all of them end up using the last value that i had and that value is 4; that means that all of the inner selectors end up as $('selectA4') and that doesn't refer to anything useful. If you really want to use a loop then you can force i to be evaluated when you want it to be with this:
for(var i = 1; i <= 3; i++)
(function(n) {
$("#menuItem" + n).mouseover(function () {
$("#selectA" + n).stop().animate({opacity: 1}, {queue: false, duration: 200 });
});
})(i);
or this:
function build_animator(i) {
return function() {
$('#selectA' + i).stop().animate({opacity: 1}, {queue: false, duration: 200 });
};
}
for(var i = 1; i <= 3; i++)
$("#menuItem" + i).mouseover(build_animator(i));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623510",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to XOR multiple items in assembler? Just wondering if it would be possible to XOR multiple bytes in assembler.
Since you would normally do
XOR al,A
I'm just not sure how it would be done.
Any help would be appreciated, thanks.
A: Advanced architectures may provide an instruction for this. In fact, one I designed many moons ago had a 16-bit bitmask which could specify any number of the registers that you wanted to use for such an operation:
xor r3, bitmask
Each bit would be examined in turn and, if it was set to 1, r3 would be xor'ed with the relevant register. However, this only ever existed as a pre-implementaion simulator and it was deemed unnecessary. I guess they figured it was cheaper in silicon to let the user do that manually.
And advanced assemblers may also provide this functionality, perhaps allowing you to write:
xor r1, r2, r3, r4, r5, r6
and having that turned into the machine language equivalent of:
xor r1, r2
xor r1, r3
xor r1, r4
xor r1, r5
xor r1, r6
That is, of course, not really a multi-argument instruction at the machine code level, just the assembler being a little more intelligent. It's also not to be confused with real instructions that use more than two arguments with one being the destination, such as:
add r7, r3, r2 ; r7 = r3 + r2
However, this is something you would just normally do in sequence, especially if you didn't know the values you were using in advance:
xor al, bl
xor al, 0x11
If you have constant items that you wish to xor your register with, you can combine them beforehand by xoring them first, since xor is commutative:
(a xor b) xor c == a xor (b xor c)
For example, if you wanted to xor your register with 0x11 and then 0x12, you could use:
xor al, 0x03 ; 0x03 is (0x12 xor 0x11)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623514",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Specific Combinations in C#, unable to grasp it I've been looking into combinations lately, I've tried various 3rd party solutions, and tried to get my head around it myself. Without success I might add.
I need to generate a 13 length string with all possible combinations of say.. int 0-2, I.E
0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 0 0 0 0 2
0 0 0 0 0 0 0 0 0 0 0 1 0
...
2 2 2 2 2 2 2 2 2 2 2 2 2
You probably get the drill, I'm aware I could just wrap this up in loops if I wanted a dirty solution. Any guidance or pointers are appreciated.
A: I'd be happy to write the code for you, but it seems like you are looking for intuition into the problem. So maybe this feels more like a "teach a man to fish" moment.
So let me ask you a few questions:
Let's generalize the problem to strings of length N. What does the N=1 case look like? It's
0
1
2
And what does the N=2 case look like? It's
00
01
02
10
11
12
20
21
22
I wonder if you can see how, given the N=1 case, we can easily derive (aka generate) the N=2 case in a very mechanical fashion. Now if you see the pattern for this specific case, can you say what the pattern is for the general case? i.e. If you happened to already have in your hand the answer for strings of length N, and I asked you to provide me with the answer for strings of length N+1 could you do so? If so you have the very definition of a recursive algorithm.
PS I think I'd call these combinations rather than permutations.
A: I can't help thinking of this as just adding number in a N-based numeric system (in your example a 3-base system).
I would write one method (if not already there in the framework or a library) that would allow you to switch bases. I.E:
String transformNumberFrom10BaseToXBase(int number, int base)
then just write a for loop (sorry, pseudo-c-like-code :) ):
for (int i = 0; i < base ^ 13; i++) {
print transformNumberFrom10BaseToXBase(i, base)
}
Ok, hope that helps or give you an idea on how to solve it :)
A: I've written quickly function that returns list of permutations, so if you have not time to write your own method, you can use it. length is permutation length, max is maximum number (in your case, it would be 2)
static List<int[]> getPermutationList(int length, int max)
{
List<int[]> perm_list = new List<int[]>();
int[] perm = new int[length];
for (int i = 0; i < length; ++i)
perm[i] = 0;
while(true)
{
for (int i = length - 1; ; --i)
{
if (i == -1)
return perm_list;
if (perm[i] < max)
{
perm[i]++;
for (int j = i + 1; j < length; ++j)
perm[j] = 0;
break;
}
}
int[] perm_copy = new int[length];
for (int i = 0; i < length; ++i)
{
perm_copy[i] = perm[i];
}
perm_list.Add(perm_copy);
}
return perm_list;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to intercept all requests for favicon.ico in SpringMVC? I've got a controller that will respond to /favicon.ico appropriately.
But I just realized that when you're in a sub page such as /subpage/index.html the browser (at least chrome) is requesting /subpage/favicon.ico.
Is there a clean way to just respond to all favicon.ico requests? I'd rather not redirect all .ico requests if possible, but if that's the best solution, perhaps.
A: Ok, one option I just finagled out of my fingers using the controller:
@Controller
@RequestMapping("/")
public class PublicPagesController extends BaseController {
@RequestMapping("**/favicon.ico")
public String favIconForward(){
return "forward:/public/img/fav.ico";
}
// ...other stuff...
}
Note the need to use the file name fav.ico, if you try this using file name favicon.ico you'll get an infinite loop.
I previously was using this approach for just @RequestMapping("favicon.ico")
And this assumes you're serving static content out of /public with something like this:
<mvc:resources mapping="/public/**" location="/public/"/>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623524",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CakePHP; how to make find conditions dependent upon foreign key of $id parameter I'm new to programming so please forgive me if this is a noob question!
I'm using Cake to build a blog, with the models users and entries.
I have a View page for the blog entries and I would like to add a list with all the other entries that its creator has written to it.
So what I need is for the find function in my entries controller to display only the entries with the same number as the foreign key "user_id" of the currently viewed entry.
Currently, in the entries controller I have added the following:
$this->set('entries',
$this->Entry->find('all', array(
'conditions'=>array('Entry.user_id' => $id)
)
)
);
So it takes the parameter of the view action, rather than its foreign key, which isn't quite what I want.
But the problem is that I just can't think of how to get the foreign key...
Hope you can help me out with that, thanks.
A: function view($id = null){
if(!$id)$this->redirect(/*somewhere*/);
$entry = $this->Entry->read(null,$id);
$entries = $this->Entry->find('all', array(
'conditions'=>array('Entry.user_id' => $entry['Entry']['user_id')
)
);
$this->set(compact('entry','entries'));
}
You will need a certain degree of familiarity of Cake (don't just blindly copy the code). Hopefully the above code will point you to the right direction.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Installed Nginx with passenger-install-nginx-module. How do I uninstall it? I'm on Mac OSX. Nginx is installed in /opt/nginx.
How do I uninstall it? Any thoughts?
A: gem uninstall passenger
will remove passenger and all these dependencies
passenger, passenger-install-apache2-module,
passenger-install-nginx-module, passenger-config, passenger-status,
passenger-memory-stats, passenger-make-enterprisey
A: Passenger's documentation covers this:
To uninstall Phusion Passenger, please first remove all Phusion Passenger configuration directives from your web server configuration file(s). After you’ve done this, you need to remove the Phusion Passenger files.
*
*If you installed Phusion Passenger through Homebrew, then run brew uninstall passenger.
*If you installed Phusion Passenger via a Ruby gem, then run gem uninstall passenger (or, if you’re a Phusion Passenger Enterprise user, gem uninstall passenger-enterprise-server). You might have to run this as root.
*If you installed Phusion Passenger via a source tarball, then remove the directory in which you placed the extracted Phusion Passenger files. This directory is the same as the one pointed to the by PassengerRoot/passenger_root configuration directive.
*If you installed Phusion Passenger through APT or YUM, then use them to uninstall Phusion Passenger.
Nginx does not have to be recompiled after uninstalling Phusion Passenger. Altough Nginx will contain the Phusion Passenger Nginx module, the module will not do anything when all Phusion Passenger configuration directives are removed.
At that point you can remove nginx by running
sudo rm -rf /opt/nginx
if you installed it using source.
Use your package manager to remove it if you installed it that way.
A: Run following command from your terminal:
For Debian/Ubuntu
sudo apt-get remove -y passenger
Red Hat/CentOS
sudo yum remove -y passenger
macOS + Homebrew
brew uninstall passenger
Ruby gem
gem uninstall passenger
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Adding controls to GroupBox during runtime I'm trying to create a GroupBox, add a Grid (or StackPanel) to it then put some TextBlocks on it, all during runtime. This is what i've tried
GroupBox groupBox1 = new GroupBox();
Grid grid1 = new Grid();
groupBox1.Width = 85;
groupBox1.Height = 60;
grid1.Height = 85;
grid1.Width = 60;
groupBox1.Content = grid1.Children.Add(textBlock1);
groupBox1.Margin = new Thickness(50, 50, 0, 0);
mainWindow.canvas.Children.Add(groupBox1);
But all I get is a groupbox with a thick white border with nothing in it.
A: As far as I can see a Grid.Children.Add returns an int and that's not what you want to set the content of the groupBox1 to.
An untested idea from me as a non WPF expert is to set the grid as the Content of your groupbox.
grid1.Children.Add(textBlock1);
groupBox1.Content = grid1;
A: For simple checkboxes i used this code :
var container = new FlowLayoutPanel
{
FlowDirection = FlowDirection.TopDown,
Dock = DockStyle.Fill
};
myGroupBox.Controls.Add(container);
foreach (var myText in textList)
{
var checkBox = new CheckBox
{
Text = myText
};
container.Controls.Add(checkBox);
}
Of course the foreach statement is just for the example :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: attr('defaultValue') is returning undefined using jQuery 1.6.3 I have a simple script in jQuery that works perfectly with jQuery 1.5.2 as you can see in this jsFiddle. What is supposed to happen is that when you bring focus to the text field, the default value is removed. And when if you leave the field blank, the original default value is put back in place.
http://jsfiddle.net/kHBsD/
However, the same exact code, where only jQuery 1.6.3 is used instead, is not working. (Not working means that the default value remains in the text box until you manually delete it as you can see in this jsFiddle.
http://jsfiddle.net/kHBsD/1/
There are no script errors in the console and other aspects of the function are operational. You can see the hover() portion is working fine in both jsFiddles.
Summarized Version (the Root Problem)
jQuery 1.6.3 is returning undefined for .attr('defaultValue').
jsFiddle using jQuery 1.6.3 (not working)
However, jQuery 1.5.2 is returning the expected value for .attr('defaultValue').
jsFiddle using jQuery 1.5.2 (working)
Question:
Does anyone know why this would be happening? (It looks like a jQuery bug to me.)
The following is still working...
document.getElementById().defaultValue
...but I think it's pretty ugly to have to do that where jQuery is available.
I'm open to other suggestions.
A: var x=$('#q').prop('defaultValue');
A: Use prop():
$( '#q' ).prop( 'defaultValue' )
Live demo: http://jsfiddle.net/kHBsD/8/
You see, 'defaultValue' is not a content attribute (HTML attribute) as you can see for yourself if you look at your HTML source code. Instead, it's a property of the HTMLInputElement DOM element node.
See here: https://developer.mozilla.org/en/DOM/HTMLInputElement
Attributes exist in the HTML source code.
Properties exist in the DOM tree.
When the browser parses the HTML source code, the HTML <input> element is interpreted and a corresponding HTMLInputElement DOM node is created. This DOM element contains dozens of properties ('defaultValue' being one of them).
Here, I've refactored your code:
$( '.autoclear' ).
focus( function () {
if ( this.value === this.defaultValue ) {
this.value = '';
$( this ).removeClass( 'blur' ).addClass( 'focus' );
}
}).
blur( function () {
if ( this.value === '' ) {
this.value = this.defaultValue;
$( this ).removeClass( 'focus' ).addClass( 'blur' );
}
});
Live demo: http://jsfiddle.net/kHBsD/9/
prop() is not necessary - you have the this reference, so you can just access the property directly. Also those hover handlers are not needed, just use a input:hover CSS rule.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623535",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Is this a proper way of calling synchronous methods asynchronously? I was using code like this:
handler.Invoke(sender, e);
But the problem with that code is that it is synchronous and all it really does is update the GUI. It is not necessary for the server to wait for it to complete so it should be made asynchronous.
I don't really want to use BeginInvoke and EndInvoke because a callback method is not necessary in this case.
Is this a suitable alternative?
Task.Factory.StartNew(() => handler.Invoke(sender, e));
A: The way you did it is fine, another way to do this that works on .NET 3.5 is using the ThreadPool class instead
ThreadPool.QueueUserWorkItem(new WaitCallback((a) => handler.Invoke(sender, e)))
Also if handler happens to be a derived from control, you are allowed to call BeginInvoke without a corresponding EndInvoke.
A: Calls to GUI are special in that they must always be done from the GUI thread. In your own words, handler.Invoke(sender, e) "updates the GUI", yet it is (probably) not executed from the GUI thread, so it not OK in its current form.
In WinForms, you'll need to wrap your task delegate into Control.Invoke (or forget about tasks and just use Control.BeginInvoke).
If WPF, you can wrap your task delegate into Dispatcher.Invoke (or just use Dispatcher.BeginInvoke without a task).
A: I'm not familiar with C# 4's Task class, but I know BeginInvoke works just fine without EndInvoke. I sometimes write code like this:
handler.BeginInvoke(sender, e, null, null);
Edit: I was mistaken. While EndInvoke is not necessary to cause the code to execute on a new thread, the documentation clearly states that EndInvoke is important.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623544",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Where is sublime.py? Sublime Text2 text editor is extended via python scripts, using these modules:
import sublime, sublime_plugin
I've searched my computer and found sublime_plugin.py file.
But where is sublime.py?
A: I believe that Sublime is provided dynamically when you call the plugin via the console.
Remember that an import doesn't have to be a physical .py file, it can be a library or an in-memory representation.
I found a decent reference to the confusions often related to Import, it's a little old now but I believe it's still relevant:
http://effbot.org/zone/import-confusion.htm
Edit: Just to confirm that, I've checked and the Python2.6 runtime is embedded inside the executable for Sublime, and the Sublime module is defined inside there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623547",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is there a way to distinguish mice in JavaScript? I am wanting to hook up several mice - each one used for different types of input. Is there a way in JavaScript to distinguish between each mouse?
I know that JS may not seem like the right language for this, but I want to use one mouse for web navigation, and the other for Google-earth navigation. Because the Google-API is already using JS, I figured I try to keep all the code together.
A: This is not possible with JavaScript. The JS would have to have low-level access to the clients machine to make this type of distinction. Obviously, this would be a huge security risk.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623554",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to randomly generate numbers from 3000 to 80000 ending with zeros only? I would like to randomly generate numbers like:
3000 4000 5000 etc... between 3000 and 80000.
How might I do that?
A: <?php
echo $your_number = (rand(3,80) * 1000);
demo
A: I think this is what you mean:
$number = rand(3,80)*1000;
you can test with this
for ($index = 0; $index < 20; $index++) {
echo (rand(3,80)*1000)."<br />";
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Handling large String lists in java I've got a task, where I've got to go through several billion string lines and check, whether each of those is unique. All the lines themselves cannot be accommodated within the RAM memory of the PC. Also, the number of lines is likely to be larger than Integer.MAX_VALUE.
I'm assuming that the best way to handle this amount of data is to put hash codes of each of the strings into some sort of HashTable.
So, here are my questions:
*
*What should I use instead of String.hashCode()? (the return value is int, but I probably will need long)
*What is the fastest way/framework for working with lists of this size? What I mostly need is an ability to quickly check if the list contains an element or not
A: You are over thinking the problem, this can all be done very simply with one MySQL table which saves data to the disk instead of holding everything in memory. That much data was never meant to be efficiently handled by a standalone application.
CREATE TABLE TONS_OF_STRINGS
(
unique_string varchar(255) NOT NULL,
UNIQUE (unique_string)
)
Just loop through the values (assuming a comma separated list here) and try to insert each token. Each failed token is a duplicate.
public static void main(args) {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/database","username","password");
FileReader file = new FileReader("SomeGiantFile.csv");
Scanner scan = new Scanner(file);
scan.useDelimiter(",");
String token;
while ( scan.hasNext() ) {
token = scan.next();
try {
PreparedStatement ps = con.prepareStatement("Insert into TONS_OF_STRING (UNIQUE_STRING) values (?)");
ps.setString(1, token);
ps.executeUpdate();
} catch (SQLException e) {
System.out.println("Found duplicate: " + token );
}
}
con.close();
System.out.println("Well that was easy, I'm all done!");
return 0;
}
Don't forget to clear the table when you are done though, thats a lot of data.
A: It is not sufficient to simply store 32 or 64 bit hashcodes because two distinct strings (out of a few billion) can easily have the same hashcode. Once you have two strings with the same hashcode, you need to compare the actual strings to see if they are actually equal.
Here's the way I'd solve this problem:
*
*Read the file / stream of strings:
*
*Read each line
*Calculate the hash code for the line
*Write the hashcode and the string to a temporary file with a suitable field separator in between
*Use a decent external sort program to sort the temporary file using the hashcode field as the primary sort key and the string field as the secondary sort key.
*Read the temporary file a line at a time. If two successive lines have the same hashcode field and different string fields then you've found a duplicate string.
Note: This approach will work equally well with 32 or 64 bit hashcodes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623571",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Values in array of structs turning into garbage values I have an issue that's really confusing me... Below I am calling an initialize function:
void Initialize (List *L) {
char* initialize = "initialize";
int i;
for (i=0; i<MAXLISTSIZE; i++) {
strncpy(L->items[i].name,initialize,MAXNAMESIZE);
L->items[i].name[MAXNAMESIZE - 1] = '\0';
L->items[i].grade = 0;
printf("L->items[i].name = %s\n", L->items[i].name);
printf("L->items[i].grade = %d\n", L->items[i].grade);
}
L->count = 0;
}
And it seems to work, I print the values in the loop and it's fine. If I also print inside an identical loop in main to double check it works as well but If I just print the values in main after the initialize function (no print statements in Initialize) I get complete garbage.
It seems the memory I'm storing my values in isn't staying consistent and I can't figure out why.
Do I need to malloc memory for the structs? Since I don't need a variable amount of storage I thought it was not necessary... I am unsure of how to go about that.
My Structs:
typedef Student Item;
#define MAXLISTSIZE 4
typedef struct {
Item items[MAXLISTSIZE];
int count;
} List;
#define MAXNAMESIZE 20
typedef struct {
char name[MAXNAMESIZE];
int grade;
} Student;
I am simply calling Initialize from main:
int main () {
List *newList;
/*call initialize function*/
newList = callInitialize();
return 0;
}
callInitialize:
List *callInitialize () {
List *L;
List studentList;
L = &studentList;
Initialize(L);
return L;
}
A: Now that you posted the function that causes the actual problem, we see what's wrong: You are returning the address of a local variable that goes out of scope! This is not valid.
List * foo()
{
List x; // <--- x comes to life
return &x; // <--- x dies here...
}
int main()
{
List * p = foo(); // ... but its address is used here!
p->name ... // dereferencing an invalid address!!
}
Your situation calls for dynamic (or "manual") allocation, which means memory allocation whose lifetime is controlled only by you, and not by the local scope.
List * initList()
{
return malloc(sizeof(List)); // this memory is permanent
}
Any manual allocation needs to come with a clean-up routine:
void freeList(List * p)
{
free(p);
}
A: Now that you've posted the remainder of your code, the problem is obvious:
List *callInitialize () {
List *L;
List studentList;
L = &studentList;
Initialize(L);
return L;
}
Within this function you create a local variable studentList which you the pass to Initialize to set it up.
Unfortunately, the scope of the studentList variable ends when you exit the callInitialize function. That's why it may contain rubbish when you attempt to use it later on.
Despite your comment about not needing malloc because the structure is small, you do need it if you want the scope of the data to exist beyond the function it's created in.
Probably the "minimal-change" solution would be:
List *callInitialize (void) {
List *L = malloc (sizeof (List));
if (L != NULL)
Initialize(&L);
return L;
}
and then remember that it needs to be freed at some point by the caller, unless the malloc fails and this function therefore returns NULL.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Replace html of a div after anchor tag? This is a quick example not my actual code. Onclick of the div button, how do i replace the html after the anchor tag or parent div title? The jQuery code here replaces everything in the div title i only want to replace what is after the anchor tag.
script
$(function() {
$('.button').live('click',function() {
var info = $(this).next('.information').html();
$(this).next('.title').html(info);
});
});
html
<div class='container'>
<div class='button'>Click Me</div>
<div class='information' style='display:none;'>information</div>
<div class='title'><a href='http://www.example.com/' class='link'></a>title</div>
</div>
A: You should wrap that in a span
<div class='title'><a href='http://www.example.com/' class='link'></a><span>title</span></div>
and target that with
$(function() {
$('.button').live('click',function() {
var self = $(this);
var info = self.nextAll('.information').html();
self.nextAll('.title').find('span').html(info);
});
});
A: There are a couple of things I changed and I think this jsFiddle is close to what you need - http://jsfiddle.net/FloydPink/LHPT2/
1) The $title should probably be within the anchor tag
2) The information div should be before the button since you're using .prev()
Try this:
<script type="text/javascript">
$(function() {
$('.button').live('click', function() {
var info = $(this).prev('.information').html();
$(this).next('.title').children('a').text(info);
});
});
</script>
<?php
while ($row=mysql_fetch_assoc($query)) {
$id = $row['id'];
$title = $row['title'];
$information = $row['information'];
echo "<div class='container'>
<div class='information' style='display:none;'>$information</div>
<div class='button'>Click Me</div>
<div class='title'><a href='http://www.example.com/' class='link'>$title</a></div>
</div>";
}
?>
A: instead of working with prev() and next(), try to work with siblings()
$('.button').live('click',function() {
var info = $(this).siblings('.information').html();
$(this).siblings('.title').html(info);
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to establish a secure connection with MySQL/PHP I'm currently doing a Capstone project and I need to establish a secure connection between PHP and MySQL. Is it there some kind of method ?
A: You can use SSL to connect to MySQl. This specifics of this varies based on your platform.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: passing a pointer of a reference/passing a reference of a reference Do I get a usual pointer as I pass a pointer to a reference of a variable or do i get a pointer to the reference? And what do i get as I pass a reference to a reference?
I am using the stack implementation of the standard library in a class, and i want to have some wrapper methods to prevent illegal access of the stack, but i am getting strange segfaults which i narrowed down to my getter-methods considering the stack.
Should those methods give back a clean reference/pointer to the original variable stored in the stack?
int& zwei() { return stack.top() };
and
int* eins() { return &stack.top() };
A: There is no such thing as a "pointer to a reference". References are aliases, and so taking the address of any of them will give a pointer to the same object:
int a;
int & b = a;
assert(&a == &b);
Your functions both return a valid result provided that the stack object is still alive in the scope of the function return.
std::stack<int> s;
int & foo() { return s.top(); } // OK, maybe
int * goo() { return &s.top(); } // ditto
int & boo() { std::stack<int> b; return b.top(); } // No! Dangling reference!
You should also check that the stack isn't empty, in which case top() is not valid.
(I should also council against calling a variable by the same name as a type, even though the type's name is std::stack.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Trying to turn Simple_form gem's collection radio's wrapper into
* element I am using the simple_form gem (https://github.com/plataformatec/simple_form) to help out the forms in my app. But I'd like to display the many radio buttons I've got here in li tag. Simple_form now generates span wrapper tag for each radio buttons. Like this:
<%= t.input :arrives_in, :collection => [1,2,3,4], :as => :radio %>
#=> <span><input type='radio'><label>1</label></span>
any way I can have it wrap the input and label part in an li instead of span?
Thank YOU!
A: You can pass :item_wrapper_tag to you input like this:
<%= t.input :arrives_in, :collection => [1,2,3,4], :as => :radio,
:item_wrapper_tag => :li %>
You can also, pass the :collection_wrapper_tag option to change the wrapper of all radio inputs like this:
<%= t.input :arrives_in, :collection => [1,2,3,4], :as => :radio,
:item_wrapper_tag => :li,
:collection_wrapper_tag => :ul %>
A: Tried the accepted answer. It stuck bullets in front of my radio buttons fine, but it still didn't display inline. I just did it with CSS. I slapped a div with class="radio-buttons" around the buttons and label. Then I added this to my style sheet (SASS):
.radio-buttons {
margin: .5em 0;
span input {
float: left;
margin-right: .25em;
margin-top: -.25em;
}
#this grabs the MAIN label only for my radio buttons
#since the data type for the table column is string--yours may be different
label.string {
margin-bottom: .5em !important;
}
clear: both;
}
.form-block {
clear: both;
margin-top: .5em;
}
.radio-buttons span {
clear: both;
display:block;
}
This will make the radio buttons inline on ALL frameworks, though this is tweaked to look the best for Zurb Foundation. ;)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Safe dynamic include from $_GET Is this a safe way to include pages from a $_GET parameter:
$pg = basename($_GET['pg']);
if (is_file('views/' . $pg . '.php')) {
require 'views/' . $pg . '.php';
}
I sanitize the parameter using basename() and all the possible files for including are in a "views/" subdirectory. It seems safe, but I want to be sure.
The reason I want to do this, is because I currently use mod_rewrite to define all my URLs, but I want a single point of entry and I'd rather keep defining them that way than use a router. So I'd have a rule like this:
RewriteRule ^item/(\d+)/?$ index.php?pg=item&id=$1 [L, NC]
And my index.php would look like this:
ob_start();
$pg = basename($_GET['pg']);
if (is_file('views/' . $pg . '.php')) {
require 'views/' . $pg . '.php';
}
$content = ob_get_clean();
require 'template.php';
Any opinions? Thanks.
A: Wise idea is to write your own array with whitelisted files that can be included. After that, check your $_GET['pg'] against array via in_array()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623592",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Short-urls without index files? I'm wondering how urls like these are generated: http://www.example.com/Xj7hF
This is a practice I have seen used by many url shorteners as well as other websites that supposedly don't want to display data in the url in a parameter format.
Surely they can't be placing index files in the folder destination /Xj7hF etc with a redirect to the actual url, so I'm wondering how this is done.
Any help would be very appreciated!
(I'm running on a Linux server with Apache).
A: Different web development frameworks and web servers do it in different ways, but, the most common is probably using mod_rewrite with apache. Basically, the web server sends the request to a dynamic scripting language (eg. PHP) rewritten in such a way that the script doesn't need to know what the original request URI looked like and the client browser doesn't need to know what script actually processed the request.
For example, You will often see:
http://something.com/123/
This is a request for /123 which Apache may rewrite as a request to /my_script.php?id=123 based on how the user configured mod_rewrite.
(.htaccess example)
# if the request is for a file or directory that
# does not actually exist, serve index.php
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?url=$1
A: This is known as URL rewriting and is usually performed via proper configuration of the webserver. StackOverflow has several tags for this, so you should be able to find more information there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623597",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C++11 resources and compilers What is the recommended resource(s) for learning the new features in C++11? Is there any book on it yet? Does latest versions of g++/Visual Studio support it?
A: The current versions of g++ and VC++ each support some features of C++11, but neither supports everything (overall, I'd say g++ currently supports more of the new features though). MS has revealed what they plan to add to the next version of VC++; the short summary is "not a lot". Both do, however, have some fairly important new features covered pretty well (e.g., both seem to handle lambdas pretty well).
As far as resources like books go, they're currently pretty meager. C++ Concurrency in action (by Anthony Williams) covers the new threading library, but that's nearly the only one (and it's obviously covers only one new aspect).
A: C++11 was only just standardized, so any compiler support is experimental because it wasn't a standard when support was introduced. Apache has a wiki article that lists which compilers support which C++11 features.
Source: http://wiki.apache.org/stdcxx/C%2B%2B0xCompilerSupport
gcc is the best bet at this point. gcc 4.5 supports a majority of features and is in pretty much every recent Linux distribution now. Obviously newer versions are better. Their support page explains which versions support which features.
Source: http://gcc.gnu.org/projects/cxx0x.html
Visual Studio 10 has decent support. This MSDN blog article lists which features are supported in 10 and are planned for 11.
Source: http://blogs.msdn.com/b/vcblog/archive/2011/09/12/10209291.aspx
The Intel C++ compiler seems to be the only other compiler with decent support. I don't know much about it though and I don't think it's free. According to this article version 12 seems to be decent, but I'm not sure if that's released or in development.
Source: http://software.intel.com/en-us/articles/c0x-features-supported-by-intel-c-compiler/
A: The Wikipedia page about C++11 has a nice list of features, but it might not be exhaustive. The status of C++11 support in GCC can be found here, in Clang it can be found here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623598",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Exporting Excel File to View (MVC) I have to Export Data to View as Excel , Actually I have Implemented,but my doubt is when
to use
return new FileContentResult(fileContents, "application/vnd.ms-excel");
vs
return File(fileContents, "application/vnd.ms-excel");
and How can set Downloadable Filename in each of this methods?
Example 1:
public ActionResult ExcelExport()
{
byte[] fileContents = Encoding.UTF8.GetBytes(data);
return new FileContentResult(fileContents, "application/vnd.ms-excel");
}
Example:2
public ActionResult ExcelExport()
{
byte[] fileContents = Encoding.UTF8.GetBytes(data);
return File(fileContents, "application/vnd.ms-excel");
}
A: You can read about the differences between FileContentResult & FileResult here : What's the difference between the four File Results in ASP.NET MVC
You can specify the filename like this
return new FileContentResult(fileContents, "application/vnd.ms-excel") { FileDownloadName = "name.xls" };
// or
// note that this call will return a FileContentResult object
return new File(fileContents, "application/vnd.ms-excel", "name.xls");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623599",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Sync local file with HTTP server location (in Python) I have an HTTP server which host some large file and have python clients (GUI apps) which download it.
I want the clients to download the file only when needed, but have an up-to-date file on each run.
I thought each client will download the file on each run using the If-Modified-Since HTTP header with the file time of the existing file, if any. Can someone suggest how to do it in python?
Can someone suggest an alternative, easy, way to achieve my goal?
A: You can add a header called ETag, (hash of your file, md5sum or sha256 etc ), to compare if two files are different instead of last-modified date
A: I'm assuming some things right now, BUT..
One solution would be to have a separate HTTP file on the server (check.php) which creates a hash/checksum of each files you're hosting. If the files differ from the local files, then the client will download the file. This means that if the content of the file on the server changes, the client will notice the change since the checksum will differ.
do a MD5 hash of the file contents, put it in a database or something and check against it before downloading anything.
Your solution would work to, but it requires the server to actually include the "modified" date in the Header for the GET request (some server softwares does not do this).
I'd say putting up a database that looks something like:
[ID] [File_name] [File_hash]
0001 moo.txt asd124kJKJhj124kjh12j
A: It seems to me the easiest solution is hosting the file in mercurial and using mercurial api to find the file's hash, downloading the file if the hash has changed.
Calculating the hash can be done as the answer to this question; for downloading the file urllib will be enough.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623600",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: memcpy causing 'exc bad access' I'm trying to loop through an array and copy across data, but after 1023 loops, I get an exc bad access message thrown and I have a feeling it might be to do with my memory.
In my loop, I need to append data to my totalValues array, so I did this:
memcpy(totalValues + totalCopied, tempBuffer, 600 * sizeof(float));
This is done inside a loop and totalCopied keeps track of how much data has been appended to totalValues so that I know where to write from when the loop hits memcpy again. I'm not sure why I get the "exc bad access" error, but my theory is that the memory is not contiguous and, therefore, the totalValues + totalCopied line might be causing trouble. I'm not sure if an error would be thrown in this case, or if the memory would just be overwritten anyway. The interesting thing is, it always occurs after 1023 loops. If I remove the 'memcpy' line, the program loops through without any problems. Any ideas what could be causing this?
EDIT - The cause was that the memory allocation was hard coded for another file. Normally, I won't know the length of the file before the memory allocation, so how can I ensure that enough memory is allocated at runtime?
A: Sounds like you're writing more bytes than totalValues can contain. Show us how you're allocating it.
Incidentally, we usually do this kind of thing with NSData objects on iOS.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Push to remote Mercurial repository I have a Mercurial repository on a remote VPS. The VPS has SSH access enabled. What are my options for pushing code changes from my development machine to the remote VPS?
A: If your VPS has Mercurial installed, simply:
hg push ssh://username@host/path/relative/to/home
or add to the repo's hgrc
[paths]
default-push = ssh://username@host/path/relative/to/home
and just
hg push
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Is this an inefficient way to write a SQL query? Let's suppose I had a view, like this:
CREATE VIEW EmployeeView
AS
SELECT ID, Name, Salary(PaymentPlanID) AS Payment
FROM Employees
The user-defined function, Salary, is somewhat expensive.
If I wanted to do something like this,
SELECT *
FROM TempWorkers t
INNER JOIN EmployeeView e ON t.ID = e.ID
will Salary be executed on every row of Employees, or will it do the join first and then only be called on the rows filtered by the join? Could I expect the same behavior if EmployeeView was a subquery or a table valued function instead of a view?
A: The function will only be called where relevant. If your final select statement does not include that field, it's not called at all. If your final select refers to 1% of your table, it will only be called for that 1% of the table.
This is effectively the same for sub-queries/inline views. You could specify the function for a field in a sub-query, then never use that field, in which case the function never gets called.
As an aside: scalar functions are indeed notoriously expensive in many regards. You may be able to reduce it's cost by forming it as an inline table valued function.
SELECT
myTable.*,
myFunction.Value
FROM
myTable
CROSS APPLY
myFunction(myTable.field1, myTable.field2) as myFunction
As long as MyFunction is Inline (not multistatement) and returns only one row for each set of inputs, this often scales much better than Scalar Functions.
This is slightly different from making the whole view a table valued function, that returns many rows.
If such a TVF is multistatment, it WILL call the Salary function for every record. But inline functions can expanded inline, as if a SQL macro, and so only call Salary as required; like the view.
As a general rule for TVFs though, don't return records that will then be discarded.
A: It should only execute the Salary function for the joined rows. But you are not filtering the tables any further. If ID is a foreign key column and not null then it will execute that function for all the rows.
The actual execution plan is a good place to see for sure.
A: As said above, the function will only be called for relevant rows. For your further questions, and to get a really good idea of what's happening, you need to gather performance data either through SQL Profiler, or by viewing the actual execution plan and elapsed times. Then test out a few theories and find which is best performance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623608",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: MATLAB parallel computing setup I have a quad core computer; and I use the parallel computing toolbox.
I set different number for the "worker" number in the parallel computing setting, for example 2,4,8..............
However, no matter what I set, the AVERAGE cpu usage by MATLAB is exactly 25% of total CPU usage; and None of the cores run at 100% (All are around 10%-30%). I am using MATLAB to run optimization problem, so I really want my quad core computer using all its power to do the computing. Please help
A: Setting a number of workers (up to 4 on a quad-core) is not enough. You also need to use a command like parfor to signal to Matlab what part of the calculation should be distributed among the workers.
I am curious about what kind of optimization you're running. Normally, optimization problems are very difficult to parallelize, since the result of every iteration depends on the previous one. However, if you want to e.g. try and fit multiple models to the data, or if you have to fit multiple data sets, then you can easily run these in parallel as opposed to sequentially.
Note that having many cores may not be sufficient in terms of resources - if performing the optimization on one worker uses k GB of RAM, performing it on n workers requires at least n*k GB of RAM.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Inputstream reader skips over some text Hi guys so this is an exert from the code I have
public ItemList() throws Exception {
//itemList = new List<Item>() ;
List<Item> itemList = new ArrayList<Item>() ;
URL itemPhrases = new URL("http://dl.dropbox.com/u/18678304/2011/BSc2/phrases.txt"); // Initilize URL
BufferedReader in = new BufferedReader(new InputStreamReader(
itemPhrases.openStream())); // opens Stream from html
while ((inputLine = in.readLine()) != null) {
inputLine = in.readLine();
System.out.println(inputLine);
Item x = new Item(inputLine);
itemList.add(x);
} // validates and reads in list of phrases
for(Item item: itemList){
System.out.println(item.getItem());
}
in.close();// ends input stream
}
My problem is that I am trying to read in a list of phrases from the URL http://dl.dropbox.com/u/18678304/2011/BSc2/phrases.txt but when it prints out what I have collected it just prints:
aaa
bbb
ddd
I have tried researching the library and using the debugger but neither have helped.
A: You are calling in.readLine() twice in a row. Remove the second call.
A: You should remove inputLine = in.readLine(); from inside the while loop, it calls readLine() function a second time, thus skipping every second line.
Your loop should look like this:
while ((inputLine = in.readLine()) != null) {
//this line must not be here inputLine = in.readLine();
System.out.println(inputLine);
Item x = new Item(inputLine);
itemList.add(x);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: XNA C# HUD SpriteFont I added a SpriteFont to my HUD and this is what I get:
http://i557.photobucket.com/albums/ss13/KookehMonsters/Dev/Untitled-1.png
All those white spots are from my camera panning and the text following along.
What's going on?
Label displayName = new Label();
displayName.Text = "DisplayName";
displayName.Size = displayName.SpriteFont.MeasureString(displayName.Text);
displayName.Position = new Vector2((int)player.Camera.Position.X, (int)player.Camera.Position.Y);
ControlManager.Add(displayName);
ControlManager.Draw(GameRef.SpriteBatch);
Label.cs
public class Label : Control
{
public Label()
{
tabStop = false;
}
public override void Update(GameTime gameTime)
{
}
public override void Draw(SpriteBatch spriteBatch)
{
spriteBatch.DrawString(SpriteFont, Text, Position, Color);
}
public override void HandleInput()
{
}
}
Update method from GamePlayScreen.cs
public override void Update(GameTime gameTime)
{
player.Update(gameTime);
sprite.Update(gameTime);
hud.Update(gameTime);
if (InputHandler.KeyReleased(Keys.Add))
{
player.Camera.ZoomIn();
if (player.Camera.CameraMode == CameraMode.Follow)
player.Camera.LockToSprite(sprite);
}
else if (InputHandler.KeyReleased(Keys.Subtract))
{
player.Camera.ZoomOut();
if (player.Camera.CameraMode == CameraMode.Follow)
player.Camera.LockToSprite(sprite);
}
Vector2 motion = new Vector2();
if (InputHandler.KeyDown(Keys.W))
{
sprite.CurrentAnimation = AnimationKey.Up;
motion.Y = -1;
}
else if (InputHandler.KeyDown(Keys.S))
{
sprite.CurrentAnimation = AnimationKey.Down;
motion.Y = 1;
}
if (InputHandler.KeyDown(Keys.A))
{
sprite.CurrentAnimation = AnimationKey.Up;
motion.X = -1;
}
else if (InputHandler.KeyDown(Keys.D))
{
sprite.CurrentAnimation = AnimationKey.Down;
motion.X = 1;
}
if (motion != Vector2.Zero)
{
sprite.IsAnimating = true;
motion.Normalize();
sprite.Position += motion * sprite.Speed;
sprite.LockToMap();
if (player.Camera.CameraMode == CameraMode.Follow)
player.Camera.LockToSprite(sprite);
}
else
{
sprite.IsAnimating = false;
}
if (InputHandler.KeyReleased(Keys.F))
{
player.Camera.ToggleCameraMode();
if (player.Camera.CameraMode == CameraMode.Follow)
player.Camera.LockToSprite(sprite);
}
if (player.Camera.CameraMode != CameraMode.Follow)
{
if (InputHandler.KeyReleased(Keys.C))
{
player.Camera.LockToSprite(sprite);
}
}
base.Update(gameTime);
}
Draw method of GamePlayScreen.cs
public override void Draw(GameTime gameTime)
{
GameRef.SpriteBatch.Begin(
SpriteSortMode.Deferred,
BlendState.AlphaBlend,
SamplerState.PointClamp,
null,
null,
null,
player.Camera.Transformation);
map.Draw(GameRef.SpriteBatch, player.Camera);
sprite.Draw(gameTime, GameRef.SpriteBatch, player.Camera);
hud.Draw(gameTime);
base.Draw(gameTime);
GameRef.SpriteBatch.End();
}
A: Don't draw the hud with the camera transform, and of course don't update your hud positions with the camera, because they are fixed now.
public override void Draw(GameTime gameTime)
{
GameRef.SpriteBatch.Begin(
SpriteSortMode.Deferred,
BlendState.AlphaBlend,
SamplerState.PointClamp,
null,
null,
null,
player.Camera.Transformation);
map.Draw(GameRef.SpriteBatch, player.Camera);
sprite.Draw(gameTime, GameRef.SpriteBatch, player.Camera);
base.Draw(gameTime);
GameRef.SpriteBatch.End();
GameRef.SpriteBatch.Begin();
hud.Draw(gameTime);
GameRef.SpriteBatch.End();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Antialiasing PNG resize in Qt? In a PyQt based GUI program, I'm drawing a few PNG file as QPixmap after resize. So here is basically what happens:
bitmap = QPixmap( "foo.png" )
bitmap.scaleToHeight(38) # original is larger than this
scene.addItem(QGraphicsPixmapItem(bitmap)) # Add to graphics scene
The problem is: afterwards, the bitmap is rather ugly. Is there a way to do this in a antialiasing way?
A: See the documentation.
bitmap = bitmap.scaledToHeight(38, Qt.SmoothTransformation)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623631",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How do I convert a string into two integers in Clojure? A json-encoded string is passed into my function, and I need to split that string based on a delimiter, then convert the first two delimited values into integers and assign them to variables which will be used within the function. I've got code that works, though it looks clumsy to me.
(:use [clojure.string :only (split trim)])
(:use [clojure.data.json :only (json-str write-json read-json)])
(defn parse-int [s] (Integer. (re-find #"[0-9]*" s)))
(map parse-int (take 2
(map trim (seq (.split #"\|"
(read-json "\" 123 | 456 | 789 \""))))))
I've hard-coded my sample input value for simplicity and so it's easily reproduced in a REPL.
I expect the result: (123 456) (which, in my code, is assigned to (let [[a b])
As I said, this code works, but I feel I must be missing something that would make it less ugly, more idiomatic.
A: I think this is clearer:
(:use [clojure.string :only (split trim)])
(:use [clojure.data.json :only (read-json)])
(map #(Integer/valueOf (trim %))
(split (read-json input) #"\|"))
assuming input is your input string.
Integer/valueOf (alternatively Integer/parseInt) seems to be the main thing your missing. No need for regex.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623633",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how many kernels running parallel in Mathematica? Wolfram site states that typically only 4 cores are used with its Parallel feature. If you want more than 4 you need to contact them and pay up.
I have a machine with 2 quad-core hyperthreaded processors. When I run Parallel commands, it starts up 16 kernels 2 x 4 x 2 (factor of 2 for HT, I guess). So it looks like 16 kernels are used and not 4. Correct? It may be the case that my university's license allows for > 4 cores. I just wanted to check to see if I am actually using all available cores.
Thanks.
A: A standard Mathematica license will have 2 kernels and then 4 sub-kernels for each of the kernels. So that would be 8 if your program used more than 1 normal kernel. Subkernels are essentially what you use for parallel processing.
If you wanted to see how many subkernels you were allowed, please either
(1) Contact Wolfram customer support about this at [email protected]
(2) Check your user portal account at user.wolfram.com. After entering in your password, go to "My Products and Services" and select the copy of Mathematica you are interesting in looking at. In that products page, you will see an entry called "Processes" which will tell you how many different processes your license gives you.
You can use commands such as $KernelCount to see how many subkernels are running.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How to build FourSquare like leaderboard (users above and below you) I'm looking for a way to implement Foursquare's style of leaderboard where instead of showing you the top 10 for example it shows the you 2 people above you and 2 people below you between your friends.
I'm hoping to avoid having to pull down everyones scores and do some array manipulation. Is there anyway I can do this with a smart SQL statement?
A: You could (assuming table USER has an integer column SCORE):
select * from USER where SCORE < myscore order by SCORE DESC limit 2;
select * from USER where SCORE >= myscore order by SCORE ASC limit 2;
Is this what you mean?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: xpath dom preg_match I have this code with google map coordinates inside and i try to get coordinates but somewhere is a problem; The code is:
<iframe width="430" scrolling="no" height="250" frameborder="0" src="http://maps.google.cz/maps/ms?msa=0&hl=cs&brcurrent=5,0,0&ie=UTF8&vpsrc=6&msid=207589766138527801127.0004aadb2c99231cecabd&ll=44.782627,20.48152&spn=0.003808,0.009205&z=16&output=embed" marginwidth="0" marginheight="0"/>
and i try to get coordinates with this code:
$string = curl($e->textContent);
preg_match('#&ll=(.*?)&#is', $string, $matches);
list($lat, $lng) = explode(',', $matches[1]);
$data['lat'] = $lat;
$data['lng'] = $lng;
but dont work!
WHERE IS THE PROBLEM? WHERE I WRONG! (sorry for english)
This is my full code, but dont work:
function curl($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_ENCODING, "gzip");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
libxml_use_internal_errors(true);
$dom = new DOMDocument();
@$dom->loadHTMLFile('http://www.kupoman.rs/aktivne-ponude/');
$xpath = new DOMXPath($dom);
$entries = $xpath->query("//div[@class='dealcontent']/h1/a/@href");
$output = array();
$i = 1;
foreach($entries as $e) {
$dom2 = new DOMDocument();
@$dom2->loadHTMLFile($e->textContent);
$xpath2 = new DOMXPath($dom2);
$data = array();
$string = $xpath2->query("//iframe/@src")->item(0)->textContent;
$data['link']= ($e->textContent);
$data['naslov'] = trim($xpath2->query("//div[@class='dealcontent']/h1")->item(0)->textContent);
$data['slika'] = trim($xpath2->query("//div[@class='slideshow']/img[1]/@src")->item(0)->textContent);
preg_match('/.*&ll=([\d.,]+)&.*/', $string, $matches);
list($lat, $lng) = explode(',', $matches[1]);
$data['lat'] = $lat;
$data['lng'] = $lng;
all is good but coordinates is 0,0 :(
A: There's a lot wrong. There's no xpath expression, your regex is wrong and you are calling curl for some reason. Maybe you're trying to do something like this:
$dom = new DOMDocument();
@$dom->loadHTML('<iframe width="430" scrolling="no" height="250" frameborder="0" src="http://maps.google.cz/maps/ms?msa=0&hl=cs&brcurrent=5,0,0&ie=UTF8&vpsrc=6&msid=207589766138527801127.0004aadb2c99231cecabd&ll=44.782627,20.48152&spn=0.003808,0.009205&z=16&output=embed" marginwidth="0" marginheight="0"/>');
$xpath = new DOMXPath($dom);
$string = $xpath->query("//iframe/@src")->item(0)->textContent;
preg_match('/.*&ll=([\d.,]+)&.*/', $string, $matches);
list($lat, $lng) = explode(',', $matches[1]);
$data['lat'] = $lat;
$data['lng'] = $lng;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: resetting a stringstream How do I "reset" the state of a stringstream to what it was when I created it?
int firstValue = 1;
int secondValue = 2;
std::wstringstream ss;
ss << "Hello: " << firstValue;
std::wstring firstText(ss.str());
//print the value of firstText here
//How do I "reset" the stringstream here?
//I would like it behave as if I had created
// stringstream ss2 and used it below.
ss << "Bye: " << secondValue;
std::wstring secondText(ss.str());
//print the value of secondText here
A: Building on answer above, we also need to reset any formatting. In all we are resetting the buffer contents, the stream state flags, and any formatting to their defaults when a new std::stringstream instance is constructed.
void reset(std::stringstream& stream)
{
const static std::stringstream initial;
stream.str(std::string());
stream.clear();
stream.copyfmt(initial);
}
A: This is the way I usually do it:
ss.str("");
ss.clear(); // Clear state flags.
A: I would do
std::wstringstream temp;
ss.swap(temp);
Edit: fixed the error reported by christianparpart and Nemo. Thanks.
PS: The above code creates a new stringstream object on the stack and swaps everything in ss with those in the new object.
Advantages:
*
*It guarantees ss will now be in a fresh-new state.
*The new object is created inline and on the stack, so that the compiler can easily optimize the code. At the end, it will be like resetting all ss internal data to initial state.
More:
*
*Compared to assignment operator: STL swap methods can be faster than assignment operator in the cases where the new object has an allocated buffer in the heap. In such a case, assignment operator has to allocate the buffer for the new object, then it MAY need to allocate another buffer for the old object, and then copy the data from the new object's buffer to the old object's new buffer. It is very easy to implement a fast swap, which just swaps pointers of the buffers for example.
*C++11. I have seen some implementation of move assignment operator that is slower than swap, although that can be fixed, but probably STL developer won't want to leave a moved object with a lot of data
*std::move() doesn't guarantee the moved object is emptied. return std::move(m_container); doesn't clear m_container. So you will have to do
auto to_return(std::move(m_container));
m_container.clear();
return to_return;
Which can't be better than
auto to_return;
m_container.swap(to_return);
return to_return;
because the latter guarantees it won't copy buffers.
So I always prefer swap() as long as it fits.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "104"
} |
Q: Vowel datatype in Haskell, is it possible? I have written the following code to remove vowels from a sentence:
main = print $ unixname "The House"
vowel x = elem x "aeiouAEIOU"
unixname :: [Char] -> [Char]
unixname [] = []
unixname (x:xs) | vowel x = unixname xs
| otherwise = x : unixname xs
Just wondering if it is possible to create a data type for vowel? The compiler won't let me use characters in a data type.
A: You could use phantom types to tag characters with extra information, in order to make the type system guarantee during compile time that your strings only contain, for example, vowels or non-vowels.
Here's a toy example:
{-# LANGUAGE EmptyDataDecls #-}
import Data.Maybe
newtype TaggedChar a = TaggedChar { fromTaggedChar :: Char }
data Vowel
data NonVowel
isVowel x = x `elem` "aeiouyAEIOUY"
toVowel :: Char -> Maybe (TaggedChar Vowel)
toVowel x
| isVowel x = Just $ TaggedChar x
| otherwise = Nothing
toNonVowel :: Char -> Maybe (TaggedChar NonVowel)
toNonVowel x
| isVowel x = Nothing
| otherwise = Just $ TaggedChar x
unixname :: [Char] -> [TaggedChar NonVowel]
unixname = mapMaybe toNonVowel
The benefit of this approach is that you can still also write functions that work on all TaggedChars regardless of the tag. For example:
toString :: [TaggedChar a] -> String
toString = map fromTaggedChar
A: Not directly. The problem is that characters are a built-in type with no facility for polymorphism. This is different from numeric literals, which are designed to be polymorphic via the Num type class.
That said, there are two basic approaches you can take: a newtype wrapper with a smart constructor, or a totally new type.
The newtype wrapper is easier to use:
module Vowel (Vowel, vowel, fromVowel) where
newtype Vowel = Vowel Char
vowel :: Char -> Maybe (Vowel)
vowel x | x `elem` "aeiouAEIOU" = Just (Vowel x)
| otherwise = Nothing
fromVowel :: Vowel -> Char
fromVowel (Vowel x) = x
Since the Vowel constructor isn't exported, new Vowels can only be created by the vowel function, which only admits the characters you want.
You could also make a new type like this:
data Vowel = A | E | I | O | U | Aa | Ee | Ii | Oo | Uu
fromChar :: Char -> Maybe Vowel
fromChar 'a' = Just Aa
fromChar 'A' = Just A
-- etc.
toChar :: Vowel -> Char
toChar Aa = 'a'
toChar A = 'A'
This second way is pretty heavyweight, and therefore is much more awkward to use.
So that's how to do it. I'm not quite certain that you want to though. The usual idiom is to make types that represent your data, and you specifically don't represent vowels. A common pattern would be something like this:
newtype CleanString = Cleaned { raw :: String }
-- user input needs to be sanitized
cleanString :: String -> CleanString
Here the newtype differentiates between unsanitized and sanitized input. If the only way to make a CleanString is by cleanString, then you know statically that every CleanString is properly sanitized (provided that cleanString is correct). In your case, it seems you actually need a type for consonants, not vowels.
Newtypes in Haskell are very lightweight*, but the programmer does have to write and use code to do the wrapping and unwrapping. In many instances the benefits outweigh the extra work. However, I really can't think of any application where it's important to know that your String is vowel-free, so I'd probably just work with a plain String.
*newtypes only exist at compile-time, so in theory there's no runtime performance cost to using them. However, their existence can change the produced code (e.g. inhibiting RULEs), so sometimes there is a measurable performance impact.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Prohibit the posting of HTML in textarea form field I have a text area where a user can define a post. This field should allow BBCODE but not HTML.
Currently HTML is allowed but it should not be.
How can I disallow HTML tags to be posted by the user?
A: There are two main choices here. You can either escape the HTML, so it's treated as plain text, or you can remove it. Either way is safe, but escaping is usually what users expect.
To escape, use htmlspecialchars() [docs] on the input, before you process the bbcode.
echo htmlspecialchars("<b>Hello [i]world![/i]</b>")
<b>Hello [i]world![/i]</b>
To remove the HTML tags entirely, use strip_tags() [docs] instead:
echo strip_tags("<b>Hello [i]world![/i]</b>")
Hello [i]world![/i]
A: I think you should use strip_tags() it will strip html tags & preserve the text but leave BBcode.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Having problems when returning a variable using jquery I dont know why this code doesnt work :S
function check(){
var haySaldo=false;
$.post("controlarSaldo.php", function(data)
{
if(data>0)
haySaldo=true;
});
return haySaldo;
}
Information:
data=1000
I put an alert of haySaldo inside jquery and I get "true" but outside jquery I get "false" :S
Many thx in advance!
A: It looks like your return statement is outside your function.
Try this
$.post("controlarSaldo.php", function(data){
var haySaldo=false;
if(data>0){
haySaldo=true;
}
return haySaldo;
});
A: Apologies if you already understand this, but this jQuery post method is a shorthand for an AJAX requests, which means that your code will not wait for the AJAX request to complete before returning the value of haySaldo (as you have it written).
It's a little unclear what you are intending to do by calling return from inside the success method. Perhaps if you provided a little more information people could offer better suggestions.
One thing you may want to check out are jQuery's deferred objects. It would allow you to do something like this.
function check(){
return $.post("controlarSaldo.php").success(function(data)
{
if(data>0)
return true;
else
return false;
});
}
Then later on in your code you can do (untested).
check().done(function(resp){
if(resp){
// Do true thing
}
else{
// Do false thing
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Security between rails and nodejs I have an app that is mostly in rails but also uses nodejs for some realtime features, for example, chat. Users log in via Rails and get assigned a session, etc as usual. However, what's the best way to authenticate with nodejs as that same user? For example I would like to prevent users from impersonating one another but login is done on rails right now and messaging is done on nodejs. Rails and nodejs both have access to the same database.
I am using devise and socketio if that matters.
A: There's a number of ways implementation wise that you could tackle this. The one that jumps to mind is to share the session cookie that devise uses with nodejs via the database.
IIRC devise creates an encrypted session cookie during authentication; save this value temporarily to your database, and let nodejs pop it off the database for its authentication. There's likely some difficulty in accomplishing this (porting some of the devise encryption to nodejs, and the like) but if you're doing a rails/nodejs app, I'm pretty sure you're capable of handling it. :D
The benefit here is that a user can't get between the hand-off to accomplish impersonation.
A: You could always generate a one-time token for any user passed between rails and node. Much, much easier than re-implementing (and maintaining) the crypto strategy used by devise and rails.
That said, sharing sessions between servers creates a lot of extra work for you and effectively doubles your bug surface area (schema, validations, etc.)
Faye is an awesome project which handles this exact use case, so it's probably worth a look :) http://faye.jcoglan.com/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623660",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Display content inside 'Blogger' to max-width correctly How can I enclose the content section of my blog to display any items(JPEGs/video) to a certain width??? I'd like to re-size only if the items are larger then "...px"
I currently use 'blogger', I can either manipulate the html for my entire blog or make up tags to use when needed inside individual posts...I've been attempting things with the div tag unsuccessfully for hours so I though it best to ask after so many failed attempts.
Thanks regardless
A: I'm new on this but I think you can do it using CSS
In your template (HTML View) search for </style> inside <header> and put some like this above.
In CSS
.content {
[your content css]
}
.max900 {
max-width:900px
}
You can customize the "...px" above.
In HTML
Then in your blog content, in HTML View, define classes "content" and "max900":
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
<div class="content max900">
Maecenas ut tellus lorem, in mattis ante.
<img class="max900" src="image.jpg" />
</div>
Nulla aliquam, sed venenatis erat lorem sit amet dolor.
PS. Sorry for my English.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623664",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: using php variables in a html email using swiftmailer Im using swiftmailer to send my emails from my site. I'm trying to get a html email to send but i want to pass a php variable in to the email.
Is this possible and if so where am i going wrong?
->setBody(
'<html>' .
' <head></head>' .
' <body>' .
' Welcome to my site. To complete registration, please click activate below' .
' <a href="http://www.mysite.com/activate.php?=c' rawurlencode ($code)' ">activate ' .
' </body>' .
'</html>',
'text/html'
);
A: I don't understand why you are using this
<?php rawurlencode ($code);?>
unless than
rawurlencode ($code)
A: <pre>
->setBody(
'<html>' .
' <head></head>' .
' <body>' .
' Welcome to my site. To complete registration, please click activate below' .
' <a href="http://www.mysite.com/activate.php?=c'. rawurlencode ($code) .' ">activate ' .
' </body>' .
'</html>',
'text/html'
);
</pre>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623667",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android: make rounded layout with two background colors I wanted to make a rounded shape and apply it as a background on a layout. This i have under control, but i wanted to make the background like a progressbar.
that is i want it to look something like this image:
I want to be able to control where the bg change so i guess it should be done in code.
It must be done in a way so i can place text over it
at the moment i have this code for creating a rounded corner shape:
int w = this.getWidth() - this.getPaddingLeft() - this.getPaddingRight();
int h = this.getHeight() - this.getPaddingTop() - this.getPaddingBottom();
int progressWidth = Math.round((w * percent) / 100);
ShapeDrawable shapeDrawable = new ShapeDrawable();
float[] outerR = new float[]{5, 5, 5, 5, 5, 5, 5, 5};
RectF inset = new RectF(0, 0, 0, 0);
float[] innerR = new float[]{0, 0, 0, 0, 0, 0, 0, 0};
RoundRectShape roundRectShape = new RoundRectShape(outerR, inset, innerR);
shapeDrawable.setShape(roundRectShape);
shapeDrawable.getPaint().setColor(progressColor);
shapeDrawable.setBounds(0,0,w,h);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Access XML from 3rd-party SOAP service? I'm using a vendor-created SOAP client to access their SOAP service in my Jersey 1.3 REST application.
In certain cases, I would like like to access the response's XML, instead of the client's proxy class. Is there a way to do this?
I also have access to their WSDL if that would make this easier to do.
A: You can use JAX-WS Dispatch client to put your hands on XML:
import java.io.FileInputStream;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.Dispatch;
import javax.xml.ws.Service;
import javax.xml.ws.soap.SOAPBinding;
import org.w3c.dom.Node;
public class DispatchClient {
public static void main(String[] args) throws Exception {
String wsdlAddress = "http://127.0.0.1:8080/news/NewsWS?wsdl";
URL wsdl = new URL(wsdlAddress);
QName serviceName = new QName("http://news/", "NewsWebService");
QName portName = new QName("http://news/", "NewsPort");
//nie ma WSDL-a
Service service = Service.create(serviceName);
service.addPort(portName, SOAPBinding.SOAP12HTTP_BINDING, "http://127.0.0.1:8080/news/NewsWS");
Dispatch<SOAPMessage> dispatch = service.createDispatch(portName,
SOAPMessage.class, Service.Mode.MESSAGE);
MessageFactory mf = MessageFactory.newInstance();
SOAPMessage req = mf.createMessage(null, new FileInputStream("NewsCountSoapRequest.xml"));
SOAPMessage res = dispatch.invoke(req);
SOAPBody body = res.getSOAPBody(); //SOAP body XML
}
}
You can work with SOAP body XML using DOM interface (all these Node madness) or use XPath.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623675",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Adding controls and their events dynamically I have a problem in asp.net
I'm developing a website in visual studio 2008 using (asp.net/vb)
I have to allow registered users to build pages and add controls that are already defined by the same user.
My problem is how to build this page dynamically?
In other words, I'd like to make like any CMS (e.g. Joomla). CMSs allow us to make new pages and add our controls then save them...
I think alot and I find a solution by making a code-generator (from A->Z) that generates the page and its code-behind (apsx file & aspx.vb file)
Is there any tool or solution can help me better than my solution??
Any help is appreciated.
A: If you look at the designer cs file for an aspx page you will notice that the designer is adding objects to the controls for the page at runtime. If you want, you could the compiler services at run time to generate a class for the page, or you could create a function that creates an instance of the control by it's type name and then add that object to the page.
Type.GetType("myControl").GetConstructor(new Type[] { typeof(string) }).Invoke(new object[] { "myString" });
Which will should return the created control, that you can then hookup in the same way that the designer does it.
EDIT: Or you could look-up compiler services. I once made a program that took it's xml based config file, and turned it into a compilable .cs file using string builder. Then I used compiler services to compile that text into a class which I executed. It started life like this:
using System;
public class MyConfigClass
{
{0}
{1}
{2}
public MyConfigClass()
{
}
}
and ended up like this
using System;
public class MyConfigClass
{
public string FirstName{
get;
set;
}
public string LastName{
get;
set;
}
public string Age {
get;
set;
}
public MyConfigClass()
{
}
}
based on this information
<?xml version="1.0" encoding="utf-8"?>
<ConfigProperties>
<Property>
<Name>FirstName</Name>
<Value>John</Value>
</Property>
<Property>
<Name>LastName</Name>
<Value>Smith</Value>
</Property>
<Property>
<Name>Age</Name>
<Value>12</Value>
</Property>
</ConfigProperties>
Basically the string builder took: "public {0} {1}{get;set;}" for each property then built the final string based on the values of the xml. Compiler services then turned it into a class. Once the class was made it could be stored for future use. Another attempt I did was to run the code file out disk in a web site project, then called the site to restart (which effectively recompiled all the that IIS finds in the directory, including your new code files).
The possibilities :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: CMFCPropertyGridProperty list of values? Is there a standard way to hold a user editable list of values in a CMFCPropertyGridProperty? I'm thinking a string with semi-colon delimiter (that seems to be the windows standard). If I want an edit interface for this how would I build that?
A: One option:
You can inherit CMFCPropertyGridProperty and override HasButton, returning TRUE. This will cause an ellipsis ("...") button to appear in the right-hand side of the value field. Override OnClickButton to provide your user interface for editing the list of values. You can pop up a dialog with a list control and a way to add/remove/edit items in the list. Override FormatProperty to display the list of values in the value field, and override ResetOriginalValue and implement code to restore the value you are constructed with.
Another option:
Inherit CMFCPropertyGridProperty and override OnKillFocus. If the user-entered value violates the formatting that you allow (semicolon-separated list of integers, for example), pop up a warning and return FALSE to prevent the edit from being committed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: checkbox inside an update panel does not get its state I have 2 checkboxes inside an Updatepanel:
<asp:UpdatePanel>
<asp:CheckBox CssClass="checkboxDivE"/>
<asp:CheckBox CssClass="checkboxDivE"/>
<asp:UpdatePanel>
in js, jquery:
$('.checkboxDivE').live('click', function (e) {
alert($(this).is(':checked')); // always giving false result
});
markup:
<span class="checkboxDivE" title="Export a trip"><input id="ctl00_ContentPlaceHolder1_GridView_Trips_ctl02_checkboxDivE" type="checkbox" name="ctl00$ContentPlaceHolder1$GridView_Trips$ctl02$checkboxDivE"></span>
<span class="checkboxDivE" title="Export a trip"><input id="ctl00_ContentPlaceHolder1_GridView_Trips_ctl03_checkboxDivE" type="checkbox" name="ctl00$ContentPlaceHolder1$GridView_Trips$ctl03$checkboxDivE"></span>
Whenever I check or uncheck the checkbox, the result is always false?
I have spent hours for finding a solution but I could not! is it a problem with jquery inside an updatePanel?
A: It should be used like this: http://jsfiddle.net/fvVAy/
Maybe you're using a class selector where you should be using a name selector. If the jsfiddle doesn't help, try uploading checkbox markup.
A: If you look at your markup, you'll notice that the ID of your checkbox is actually ctl00_ContentPlaceHolder1_GridView_Trips_ctl03_CheckBoxExportTour and the class you are trying to grab - checkboxDivE - belongs to the span.
You just need to change your selector.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MS Access: An error in vba of my form I have a simple MS Access form that has 3 objects: a text box, a list box, and a button. The intended use of the form is as follows: the user enters a name in the text box, selects an item from the list box, then clicks the button to add the data to a table.
However, when I click on the button, I keep getting the error message, "You can't reference property or a method for a control unless the control has the focus."
Below is my code. Thanks!
Private Sub addRecord_button_Click()
Dim CustomerName As String
Dim CustomerType As String
On Error GoTo Errhandler
CustomerName = "[name not selected]"
CustomerType = "[type not selected]"
CustomerName = Customer_TextBox.Text
Select Case Type_ListBox.ListIndex
Case 0
CustomerType = "Type 1"
Case 1
CustomerType = "Type 2"
Case 2
CustomerType = "Type 3"
End Select
'MsgBox ("Name: " & CustomerName & " and Type: " & CustomerType)
DoCmd.RunSQL "INSERT INTO Customer VALUES (CustomerName, CustomerType);"
Errhandler:
MsgBox ("The following error has occured: " & Err & " - " & Error(Err))
End Sub
A: The .Text property can only be used when the TextBox has focus. Try using the .Value property instead.
Try replacing the below line
CustomerName = Customer_TextBox.Text
with
CustomerName = Customer_TextBox.Value
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Accessing program messages output to error stream I've created a class which processes files and if it encounters certain specific errors, it outputs relevant error messages to the error stream.
I am working on another class that needs to access these error messages. I'm not sure how to do this. I am a beginner in Java programming. Based on my limited knowledge, I thought that my two options would be to either call the main method of the first class (but I don't know how I would get the error messages in this case) or to execute the compiled class and access the messages through the getErrorStream() method of the Process class. But, I am having trouble with the system deadlocking or possibly not even executing the exec command, so I'm not sure how implement the second case either.
A: I'm not quite sure what you're asking here, but a potential problem with your code is that you're not reading from the process' stdout. Per the Process API, "failure to promptly ... read the output stream of the subprocess may cause the subprocess to block, and even deadlock." Is this the "trouble" you mentioned?
Edit: So yeah, you can either do what you're doing, but be sure to read both the error stream and the output stream (see my comment), or you could just call the main method directly from your code, in which case the error output will be written to System.err. You could use System.setErr() to install your own stream that would let you get what's written to it, but keep in mind that any error output from your own app--the one that's running the other app--will also show up here. It sounds like spawning a separate process, like you're already doing, is what you want.
A: You can't build modularity based on many little programs with a main method. You have to make blocks of function as classes that are designed to be called from elsewhere -- and that means returning status information in some programmatic fashion, not just blatting it onto System.err. If it really is an error, throw an exception. If you have to return status, design a data structure to hold the status and return it. But don't go launching new processes all over the place and reading their error streams.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I use variables in less with the Rails 3.1 Asset Pipeline I am converting a number of less files into a rails app, and running into problems with the processing of variables and other less features.
I require my assets in application.css, but when viewing the page see the following error:
Less::ParseError: variable @light-border is undefined
(in tokens.css.less
Served asset /tokens.css - 500 Internal Server Error
I have a less file that defines all my variables and several other files that define various mixins.
The problem also seems to affect the mixins - looks like the less files are being processed individually, but not as a single context ... hence the variable and mixin errors. Individual files will render, but not include the various components and variables.
Is there a trick to getting this working in Rails?
A: I added the less-rails gem and it seems to work now. I think the asset pipeline doesn't actually support more than rudimentary less use.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Random data loss on iOS after restarting app Clearly I must not be doing something right but this happens on random occasions. I can't make the issue appear by following certain steps so it has become extremely hard to debug. I have an app in which every time an object is added, or deleted it writes the file to a plist. I can verify the plist in the simulator and I also have an NSLog each time my save function is called. The data is loaded when applicationWillEnterForeground is called, which is also working correctly. On certain occasions after starting up the app it will revert to the previous save before the most recent changes. Does iOS cache data files? If it tries to load a file from disk to an array, could it possible already have the previous load in a cache and create the array with that data instead?
Save method:
- (void)saveFile {
// saves data to file
NSLog(@"save file reached");
#ifdef LITE_VERSION
[self.aquariums writeToFile:[self dataFilePathLite] atomically:YES];
#else
[self.aquariums writeToFile:[self dataFilePath] atomically:YES];
#endif
}
Load method; I just added the if (self.aquariums == null) check and it might have solved the issue but it's hard for me to confirm since I can't recreate the problem:
- (void)applicationDidBecomeActive:(UIApplication *)application
{
/*
Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
*/
NSLog(@"applicationDidBecomeActive called");
if (self.aquariums == NULL) {
NSLog(@"aquariums null, loading file");
#ifdef LITE_VERSION
NSString *filePath = [self dataFilePathLite];
#else
NSString *filePath = [self dataFilePath];
#endif
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
self.aquariums = array;
[array release];
[self update21];
} else {
#ifdef LITE_VERSION
[self convertFileName];
#else
[self update20];
#endif
}
application.applicationIconBadgeNumber = 0;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
aquaPlannerAppDelegate_iPad *appDelegate = [[UIApplication sharedApplication] delegate];
[appDelegate.rootView viewDidAppear:YES];
}
}
}
A: After releasing and not getting any reports of loss of data the issue must definitely have been
if (self.aquariums == NULL) {
so people remember if you are going to reload data when an app returns from being in the background set it to null first and release
aquariums = NULL;
[aquariums release];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is this always the address for GDB debug program? I will narrow down my questions:
The entry address in GDB stays the same for the same program (even after reboot, and after rewriting the source code).
Why is that?
For example 0x80483f4 is the starting address.
**0x80483f4** <main()> push %ebp │
│0x80483f5 <main()+1> mov %esp,%ebp │
│0x80483f7 <main()+3> sub $0x10,%esp │
│0x80483fa <main()+6> movl $0x3,-0x4(%ebp) │
│0x8048401 <main()+13> movl $0x3,-0x8(%ebp) │
│0x8048408 <main()+20> mov $0x0,%eax │
│0x804840d <main()+25> leave │
│0x804840e <main()+26> ret
Beside that, the value we get from, let say, 0x80483fa, is always the same.
$2 = 0x80483fa <main()+6>
(gdb) x $2
0x80483fa <main()+6>: 0x3fc45c7
(gdb) p 0x3fc45c7
$3 = 66864583 <-- even after reboot.
What does this suggest me?
I am interested in the values before and after each assignment (say c = a+b later), without using breakpoints to step through one line at a time.
The source code:
int main()
{
int b = 3;
int a = 3;
return 0;
}
Can someone please explain this to me? Thanks.
(I would also mark this as homework, although it really isn't.)
A:
For example 0x80483f4 is the starting address.
This is likely. Unless you have PIE (position independent executables), it will stay the same (for one binary) forever.
$2 = 0x80483fa <main()+6>
(gdb) x $2
0x80483fa <main()+6>: 0x3fc45c7
That is the binary representation of the instructions at main()+6. Will never change in one binary.
(gdb) p 0x3fc45c7
$3 = 66864583 <-- even after reboot.
That means 0x3fc45c7 is 66864583 in decimal...
Note that none of this has anything to do with a or b.
BTW the best way to get values of variables "before assignment" is to printf them before the assignment.
A: Your program is (at least partially) statically linked, and main() almost certainly is. Rebooting your computer isn't going to change that statically linked part of the executable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHPmailer failing if trying to send two emails in same script I'm using PHPmailer to send emails and I've created a function that prepares the email and sends it. If I try to use this function more than once in a script it stops the script execution when it trys to send a second email using the same function.
my function:
public static function sendEmail($from, $fromName, $to, $subject, $body){
require("includes/class.phpmailer.php");
$mailer = new PHPMailer();
$mailer->IsSMTP(true);
$mailer->Host = 'ssl://smtp.gmail.com:465';
$mailer->SMTPAuth = true;
$mailer->Username = 'removed';
$mailer->Password = 'removed';
$mailer->From = $from;
$mailer->FromName = $fromName;
$mailer->AddAddress($to);
$mailer->Subject = $subject;
$mailer->Body = $body;
$mailer->WordWrap = 100;
if ($mailer->Send()) {
return true;
} else {
return false;
}
}
Why is this happening? Is it anything to do with creating a new phpmailer object each time?
A: I think you should use require_once() instead of require
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: wget can't download - 404 error I tried to download an image using wget but got an error like the following.
--2011-10-01 16:45:42-- http://www.icerts.com/images/logo.jpg
Resolving www.icerts.com... 97.74.86.3
Connecting to www.icerts.com|97.74.86.3|:80... connected.
HTTP request sent, awaiting response... 404 Not Found
2011-10-01 16:45:43 ERROR 404: Not Found.
My browser has no problem loading the image.
What's the problem?
curl can't download either.
Thanks.
Sam
A: I had same problem.
Solved using single quotes like this:
$ wget 'http://www.icerts.com/images/logo.jpg'
wget version in use:
$ wget --version
GNU Wget 1.11.4 Red Hat modified
A: You need to add the referer field in the headers of the HTTP request. With wget, you just need the --header arg :
wget http://www.icerts.com/images/logo.jpg --header "Referer: www.icerts.com"
And the result :
--2011-10-02 02:00:18-- http://www.icerts.com/images/logo.jpg
Résolution de www.icerts.com (www.icerts.com)... 97.74.86.3
Connexion vers www.icerts.com (www.icerts.com)|97.74.86.3|:80...connecté.
requête HTTP transmise, en attente de la réponse...200 OK
Longueur: 6102 (6,0K) [image/jpeg]
Sauvegarde en : «logo.jpg»
A: I had the same problem with a Google Docs URL. Enclosing the URL in quotes did the trick for me:
wget "https://docs.google.com/spreadsheets/export?format=tsv&id=1sSi9f6m-zKteoXA4r4Yq-zfdmL4rjlZRt38mejpdhC23" -O sheet.tsv
A: You will also get a 404 error if you are using ipv6 and the server only accepts ipv4.
To use ipv4, make a request adding -4:
wget -4 http://www.php.net/get/php-5.4.13.tar.gz/from/this/mirror
A: Wget 404 error also always happens if you want to download the pages from Wordpress-website by typing
wget -r http://somewebsite.com
If this website is built using Wordpress you'll get such an error:
ERROR 404: Not Found.
There's no way to mirror Wordpress-website because the website content is stored in the database and wget is not able to grab .php files. That's why you get Wget 404 error.
I know it's not this question's case, because Sam only wants to download a single picture, but it can be helpful for others.
A: Actually I don't know what is the reason exactly, I have faced this like of problem.
if you have the domain's IP address (ex 208.113.139.4), please use the IP address instead of domain (in this case www.icerts.com)
wget 192.243.111.11/images/logo.jpg
Go to find the IP from URL https://ipinfo.info/html/ip_checker.php
A: I want to add something to @blotus's answer,
In case adding the referrer header does not solve the issue, May be you are using the wrong referrer (Sometimes the referrer is different from the URL's domain name).
Paste the URL on a web browser and find the referrer from developer tools (Network -> Request Headers).
A: I met exactly the same problem while setting up GitHub actions with Cygwin. Only after I used wget --debug <url>, I realized that URL is appended with 0xd symbol which is \r (carriage return).
For this kind of problem there is the solution described in docs:
you can also use igncr in the SHELLOPTS environment variable
So I added the following lines to my YAML script to make wget work properly, as well as other shell commands in my GHA workflow:
env:
SHELLOPTS: igncr
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "35"
} |
Q: CMake Header Generator Updates In CMake I currently have a simple Python script to generate a header, but if I update the script itself CMake won't re-run the script. Is there a way I can get CMake to do this?
A: It seems you are directly invoking your code generation script when cmake is run. While it is possible solution but it is definitely not a right way to use code generators with cmake.
I recommend you to use add_custom_command for your case:
add_custom_command(
OUTPUT generated.h
COMMAND ${PYTHON_EXECUTABLE} generator.py
DEPENDS generator.py
)
And next you can simple put your header to the list of source files passed to add_library/add_executable commands. cmake will automatically track all the dependencies and invoke your script.
Term DEPENDS generator.py informs cmake that it should regenerate header if script is changed.
With this approach file generated.h will be generated only at build time (when you run make or execute a build command in IDE). In contrast if you are running your script at cmake time (with execute_process command) then you have to rerun cmake to regenerate your file. Which is possible but you need to use some tricks to introduce a non-standard dependency.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623699",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Java - find position of a string in a List of storage object I guess the title of this questions says it all, or says nothing...
After couple of hours of googling, trying things and reinventing Java I decided to ask you.
I have this storage class:
class AppInfo implements Comparable<AppInfo > {
private String appname = "";
private String pname = "";
private String versionName = "";
//private int versionCode = 0;
private Drawable icon;
private String appdir = "";
private String appSize = "";
@Override
public int compareTo(AppInfo other) {
int compareAppsName = appname.compareToIgnoreCase(other.appname);
return compareAppsName;
}
}
I do what I do and eventually I get a List filled with objects.
Everything works great, ListView is populated with the right data...
Now I want to search a string (a certain pname) and see if it exists in the List and if it does, what's its position in the list (its index).
Tried creating another list with only the data I need.. tried Lists, HashMaps, LinkedHashMap, 2 dimensional arrays/arrayList... nothing did the trick...
Also tried iterating the list but couldn't figure out how to handle the elements I got.
Hopefully I make some sense and that's even possible.
Disclosure: Please bear with me, I am kinda new in Java.
A: I'm not entirely sure that I understand your question, but if you want to find the indices of the list elements with the given pname value, you can do something like this:
List<Integer> indices = new ArrayList<Integer>();
for (int i = 0; i < list.size(); i++) {
String panme = list.get(i).getPname();
if (pname != null && pname.equals(expectedPname));
indices.add(i);
}
}
I just reread your question, and it sounds like you're only expecting the index to show up once. Sorry for the confusion. For that, you can use the same idea without the additional list:
int matchingIndex = -1;
for (int i = 0; i < list.size(); i++) {
String pname = list.get(i).getPname();
if (pname != null && pname.equals(expectedPname));
matchingIndex = i;
break;
}
}
A: If you just wanting to check the pname string you could add a getter method to your AppInfo class e.g.
public String getPname(){
return pname ;
}
then as you iterate through your list you can call .getPname to extract the string at the given position in the list.
m
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Pointer arithmetic for structs Given a struct definition that contains one double and three int variables (4 variables in all), if p is a pointer to this struct with a value 0x1000, what value does p++ have?
This is not a homework problem, so don't worry. I'm just trying to prepare for a test and I can't figure out this practice problem. Thanks
This is in C. Yes I want the value of p after it is incremented. This is a 32-bit machine
A: The answer is that it is at least
sizeof(double) + (3*sizeof(int))
Thew reason it's "at least" is that the compiler is more or less free to add padding as needed by the underlying architecture to make it suit alignment constraints.
Let's say, for example, that you have a machine with a 64-bit word, like an old CDC machine. (Hell, some of them had 60-bit words, so it would get weirder yet.) Further assume that on that machine, sizeof(double) is 64 bits, while sizeof(int) is 16 bits. The compiler might then lay out your struct as
| double | int | int | int | 16 bits padding |
so that the whole struct could be passed through the machine in 2 memory references, with no shifting or messing about needed. In that case, sizeof(yourstruct_s) would be 16, where
sizeof(double)+ (3*sizeof(int)) is only 48 14.
Update
Observe this could be true on a 32-bit machine as well: then you might need padding to fit it into three words. I don't know of a modern machine that doesn't address down to the byte, so it may be hard to find an example now, but a bunch of older architectures ould need this.
A: Pointer arithmetic is done in units of the size of the pointer type.
So if you do p++ on a pointer to your struct, p will advance by sizeof *p bytes. i.e. just ask your compiler for how big your struct is with the sizeof operator.
A: p = p + sizeof(YourStruct)
The compiler is free to decide what sizeof will return if you don't turn padding off.
A: struct foobar *p;
p = 0x1000;
p++;
is the same as
struct foobar *p;
p = 0x1000 + sizeof(struct foobar);
A: A Increment in base address of a data type is equal to base address + sizeof(data type)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7623704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.