qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
24,520,243 | I'm looking right at the file I want to download in my current directory. wget wants a FULL url, I don't know what the full url is. im in directory /usr/local/lib/ and want to download php.ini.
I am using putty to log into my web server, and when i say donwload i want to download it from the web server to my pc | 2014/07/01 | [
"https://Stackoverflow.com/questions/24520243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1397417/"
] | The best way to get started with Android Wear is to use the latest Android Studio 0.8.1 or later, and it makes adding the support libraries to your code a lot easier. But it is possible to still use Eclipse, and I'll explain how to do it ...
Since the SDK was just released for Android Wear, you need to firstly make sure you follow these instructions to get everything up to date: <http://developer.android.com/preview/google-play-services-wear.html>
Here are the steps you need to do to fix your problem:
1. Start SDK Manager.
2. Update the Android SDK Tools and Platform-tools to versions 23 and 20 respectively.
3. Click Tools > Manage Add-on Sites > User Defined Sites.
4. Click New, enter <https://dl-ssl.google.com/android/repository/addon-play-services-5.xml> into the text field, and click OK.
5. Click Close. You should now see lots of packages that need to be downloaded. You need to download "SDK Platform" under "Android 4.4W (API 20)
6. The most important part is to download the "Google Repository" package under "Extras".
7. Step 6 will produce a directory called $SDK/extras/google/m2repository/com/google/android/support/wearable/1.0.0 and in there will be a wearable-1.0.0.aar file
8. Unzip the wearable-1.0.0.aar file, and it will produce a classes.jar file
9. If you unzip -v classes.jar you will see that it contains android/support/wearable/view/WatchViewStuff.class, which is what you were looking for!
10. Copy this classes.jar file to your project's libs directory, rename it to something like wearable-classes.jar
11. Right click on the libs directory in Eclipse, which will refresh your project and you should see wearable-classes.jar
12. Clean and rebuild your project.
These steps might seem complicated in having to deal with the .aar file ... It is a lot easier when working with Android Studio, since you can just add a gradle rule that does all these steps for you automatically:
```
dependencies {
compile "com.google.android.support:wearable:1.0.+"
}
``` | The instructions detailed at the link below were very helpful for my Eclipse setup.
<https://medium.com/@tangtungai/how-to-develop-and-package-android-wear-app-using-eclipse-ef1b34126a5d> |
24,520,243 | I'm looking right at the file I want to download in my current directory. wget wants a FULL url, I don't know what the full url is. im in directory /usr/local/lib/ and want to download php.ini.
I am using putty to log into my web server, and when i say donwload i want to download it from the web server to my pc | 2014/07/01 | [
"https://Stackoverflow.com/questions/24520243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1397417/"
] | The best way to get started with Android Wear is to use the latest Android Studio 0.8.1 or later, and it makes adding the support libraries to your code a lot easier. But it is possible to still use Eclipse, and I'll explain how to do it ...
Since the SDK was just released for Android Wear, you need to firstly make sure you follow these instructions to get everything up to date: <http://developer.android.com/preview/google-play-services-wear.html>
Here are the steps you need to do to fix your problem:
1. Start SDK Manager.
2. Update the Android SDK Tools and Platform-tools to versions 23 and 20 respectively.
3. Click Tools > Manage Add-on Sites > User Defined Sites.
4. Click New, enter <https://dl-ssl.google.com/android/repository/addon-play-services-5.xml> into the text field, and click OK.
5. Click Close. You should now see lots of packages that need to be downloaded. You need to download "SDK Platform" under "Android 4.4W (API 20)
6. The most important part is to download the "Google Repository" package under "Extras".
7. Step 6 will produce a directory called $SDK/extras/google/m2repository/com/google/android/support/wearable/1.0.0 and in there will be a wearable-1.0.0.aar file
8. Unzip the wearable-1.0.0.aar file, and it will produce a classes.jar file
9. If you unzip -v classes.jar you will see that it contains android/support/wearable/view/WatchViewStuff.class, which is what you were looking for!
10. Copy this classes.jar file to your project's libs directory, rename it to something like wearable-classes.jar
11. Right click on the libs directory in Eclipse, which will refresh your project and you should see wearable-classes.jar
12. Clean and rebuild your project.
These steps might seem complicated in having to deal with the .aar file ... It is a lot easier when working with Android Studio, since you can just add a gradle rule that does all these steps for you automatically:
```
dependencies {
compile "com.google.android.support:wearable:1.0.+"
}
``` | For gradle try
```
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.google.android.support:wearable:+'
compile 'com.google.android.gms:play-services-wearable:+'
```
} |
24,520,243 | I'm looking right at the file I want to download in my current directory. wget wants a FULL url, I don't know what the full url is. im in directory /usr/local/lib/ and want to download php.ini.
I am using putty to log into my web server, and when i say donwload i want to download it from the web server to my pc | 2014/07/01 | [
"https://Stackoverflow.com/questions/24520243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1397417/"
] | Create a wearable module with Android Studio 4.0 and ended-up with the exact same issue! And it's 2020, 6 years later LOL.
Followed this guide to add the missing bits and pieces:
<https://developer.android.com/training/wearables/apps/creating>
Basically my project builde.gradle didn't have those:
```
maven { url "https://maven.google.com" }
```
And this is module's gradle:
```
implementation 'com.google.android.support:wearable:2.8.0'
```
Once added, every checked properly.
PS: the maven is not even needed. Only missing implementation which clearly shows the wizard fails to create a valid module. | For gradle try
```
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.google.android.support:wearable:+'
compile 'com.google.android.gms:play-services-wearable:+'
```
} |
59,278,639 | How to change in nox app player default geo in google map ? Because after create new emulator need every time change pin on google map. | 2019/12/11 | [
"https://Stackoverflow.com/questions/59278639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6613393/"
] | c:\Users\YOURUSERNAME\AppData\Local\Nox\conf.ini
```
[Location]
Lat=10.8378886
Lng=106.638701
Map=google
``` | For **Nox** emulator you can setup location and status GPS in files placed on android:
```
> adb shell ls /data/property/persist.nox.gps.*
/data/property/persist.nox.gps.latitude
/data/property/persist.nox.gps.longitude
/data/property/persist.nox.gps.status
``` |
12,184,068 | Long time lurker, first time poster. I'm relatively new to objective-C so my apologies if I'm asking something fairly simple. My google & stack overflow-fu has let me down here, so I figured somebody could maybe help.
I have a synchronous process executing, say, three functions in a row - call it A -> B-> C , where task A executes, followed by B, followed by C.
Now, B involves an asynchronous process with a delegate callback for completion. But B must complete before C is executed, so I need some mechanism such that C is not triggered before B has finished. I imagine there must be a common design pattern for this problem?
Initially naive solution would be -
execute A
execute B
while (!B finished) {}
execute C
...but this seems really lame.
I suspect I can do this with some kind of block, but for the life of me I just can't figure it out. Could anyone help?
appreciate any assistance!
Guillaume | 2012/08/29 | [
"https://Stackoverflow.com/questions/12184068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1634015/"
] | Another approach to this problem might be the following: create an helper object for the async task and copy a completion block when the task is called. Call the completion block using the delegate methods once the async task is finished. As a result we might execute the tasks in order like the following:
```
FSTask *taskA = [FSTask taskWithName:@"Task A"];
FSAsyncTask *taskB = [FSAsyncTask asyncTaskWithName:@"Task B"];
FSTask *taskC = [FSTask taskWithName:@"Task C"];
[taskA performTaskWithCompletionBlock:^ (NSString *result) {
NSLog(@"%@", result);
[taskB performTaskWithCompletionBlock:^ (NSString *result) {
NSLog(@"%@", result);
[taskC performTaskWithCompletionBlock:^ (NSString *result) {
NSLog(@"%@", result);
}];
}];
}];
```
So how is this achieved? Well, look at the task objects below ...
---
**FSTask.m** - *synchronous work on main thread ...*
```
@interface FSTask ()
@property (nonatomic, copy) NSString *name;
@end
@implementation FSTask
@synthesize name = _name;
+ (FSTask *)taskWithName:(NSString *)name
{
FSTask *task = [[FSTask alloc] init];
if (task)
{
task.name = name;
}
return task;
}
- (void)performTaskWithCompletionBlock:(void (^)(NSString *taskResult))block
{
NSString *message = [NSString stringWithFormat:@"%@: doing work on main thread ...", _name];
NSLog(@"%@", message);
if (block)
{
NSString *result = [NSString stringWithFormat:@"%@: result", _name];
block(result);
}
}
@end
```
---
**FSAsyncTask.m** - *asynchronous work on background thread ...*
```
@interface FSAsyncTask ()
@property (nonatomic, copy) void (^block)(NSString *taskResult);
@property (nonatomic, copy) NSString *name;
- (void)performAsyncTask;
@end
@implementation FSAsyncTask
@synthesize block = _block;
@synthesize name = _name;
+ (FSAsyncTask *)asyncTaskWithName:(NSString *)name
{
FSAsyncTask *task = [[FSAsyncTask alloc] init];
if (task)
{
task.name = name;
}
return task;
}
- (void)performTaskWithCompletionBlock:(void (^)(NSString *taskResult))block
{
self.block = block;
// the call below could be e.g. a NSURLConnection that's being opened,
// in this case a NSURLConnectionDelegate method will return the result
// in this delegate method the completion block could be called ...
dispatch_queue_t queue = dispatch_queue_create("com.example.asynctask", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^ {
[self performAsyncTask];
});
}
#pragma mark - Private
- (void)performAsyncTask
{
for (int i = 0; i < 5; i++)
{
NSString *message = [NSString stringWithFormat:@"%d - %@: doing work on background thread ...", i, _name];
NSLog(@"%@", message);
[NSThread sleepForTimeInterval:1];
}
// this completion block might be called from your delegate methods ...
if (_block)
{
dispatch_async(dispatch_get_main_queue(), ^ {
NSString *result = [NSString stringWithFormat:@"%@: result", _name];
_block(result);
});
}
}
@end
``` | You can also pass C in a block like so...
define a custom block
`typedef void(^myCompletion)(BOOL complete);`
Create your B method
```
-(void)performBWithCompletionBlock:(myCompletion)complete;
{
// do your things
[self.delegate delegateCallback];
complete(YES);
}
```
then create BG / async ABC
```
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // now we're on a BG queue to perform our async tasks
[self performA];
[self performBWithCompletionBlock:^(BOOL complete) {
if (complete == YES)
[self performC];
}];
});
```
If you want C to be on the main thread
```
dispatch_async(dispatch_get_main_queue(), ^{
[self performC];
});
``` |
12,184,068 | Long time lurker, first time poster. I'm relatively new to objective-C so my apologies if I'm asking something fairly simple. My google & stack overflow-fu has let me down here, so I figured somebody could maybe help.
I have a synchronous process executing, say, three functions in a row - call it A -> B-> C , where task A executes, followed by B, followed by C.
Now, B involves an asynchronous process with a delegate callback for completion. But B must complete before C is executed, so I need some mechanism such that C is not triggered before B has finished. I imagine there must be a common design pattern for this problem?
Initially naive solution would be -
execute A
execute B
while (!B finished) {}
execute C
...but this seems really lame.
I suspect I can do this with some kind of block, but for the life of me I just can't figure it out. Could anyone help?
appreciate any assistance!
Guillaume | 2012/08/29 | [
"https://Stackoverflow.com/questions/12184068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1634015/"
] | Thanks for all the feeback - apologies for not responding sooner. I've now resolved this in a slightly different way to the suggestions:
Firstly, I extended NSObject to have the following method -
```
#import "NSObject+LTExtensions.h"
@implementation NSObject (Testing)
- (void) performSelectorWithBlock: (SEL) selector withSemaphore:(dispatch_semaphore_t)semaphore
{
[self performSelector:selector]; // This selector should complete the semaphore
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_release(semaphore);
}
@end
```
This allows me to execute a block via a selector. When the block executes, the thread on which it is executed will wait until signaled to proceed by a specific dispatch semaphore.
What we can then do is as follows:
* Call A
* Create a dispatch semaphore and define a selector which executes B
* Call the method defined above to execute B and wait for the selector to complete
* When B is completed (via a delegate callback), it signals the dispatch semaphore to suspend the wait
* I then execute C
So we have
```
A
B -> Asynchronous with delegate callback
C
```
Here's a simple example of how the above is implemented
```
-(void) methodA {
// ... do something
// Assign your semaphore (this is a dispatch_semaphore_t)
self.semaphore = dispatch_semaphore_create(0);
[self performSelectorWithBlock:@selector(methodB) withSemaphore:semaphore];
[self methodC];
}
-(void) methodB {
// ... do whatever needs to be done asynchronously
CFRunLoopRun();
}
-(void) methodBDelegateCallBack {
// This is called when B completes
// Signal completion
dispatch_semaphore_signal(self.semaphore);
CFRunLoopStop(CFRunLoopGetCurrent());
}
-(void) methodC {
...
}
```
Works very well without any issues (but I am new to Obj C, so there may be glaring issues with my approach). | Another approach to this problem might be the following: create an helper object for the async task and copy a completion block when the task is called. Call the completion block using the delegate methods once the async task is finished. As a result we might execute the tasks in order like the following:
```
FSTask *taskA = [FSTask taskWithName:@"Task A"];
FSAsyncTask *taskB = [FSAsyncTask asyncTaskWithName:@"Task B"];
FSTask *taskC = [FSTask taskWithName:@"Task C"];
[taskA performTaskWithCompletionBlock:^ (NSString *result) {
NSLog(@"%@", result);
[taskB performTaskWithCompletionBlock:^ (NSString *result) {
NSLog(@"%@", result);
[taskC performTaskWithCompletionBlock:^ (NSString *result) {
NSLog(@"%@", result);
}];
}];
}];
```
So how is this achieved? Well, look at the task objects below ...
---
**FSTask.m** - *synchronous work on main thread ...*
```
@interface FSTask ()
@property (nonatomic, copy) NSString *name;
@end
@implementation FSTask
@synthesize name = _name;
+ (FSTask *)taskWithName:(NSString *)name
{
FSTask *task = [[FSTask alloc] init];
if (task)
{
task.name = name;
}
return task;
}
- (void)performTaskWithCompletionBlock:(void (^)(NSString *taskResult))block
{
NSString *message = [NSString stringWithFormat:@"%@: doing work on main thread ...", _name];
NSLog(@"%@", message);
if (block)
{
NSString *result = [NSString stringWithFormat:@"%@: result", _name];
block(result);
}
}
@end
```
---
**FSAsyncTask.m** - *asynchronous work on background thread ...*
```
@interface FSAsyncTask ()
@property (nonatomic, copy) void (^block)(NSString *taskResult);
@property (nonatomic, copy) NSString *name;
- (void)performAsyncTask;
@end
@implementation FSAsyncTask
@synthesize block = _block;
@synthesize name = _name;
+ (FSAsyncTask *)asyncTaskWithName:(NSString *)name
{
FSAsyncTask *task = [[FSAsyncTask alloc] init];
if (task)
{
task.name = name;
}
return task;
}
- (void)performTaskWithCompletionBlock:(void (^)(NSString *taskResult))block
{
self.block = block;
// the call below could be e.g. a NSURLConnection that's being opened,
// in this case a NSURLConnectionDelegate method will return the result
// in this delegate method the completion block could be called ...
dispatch_queue_t queue = dispatch_queue_create("com.example.asynctask", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^ {
[self performAsyncTask];
});
}
#pragma mark - Private
- (void)performAsyncTask
{
for (int i = 0; i < 5; i++)
{
NSString *message = [NSString stringWithFormat:@"%d - %@: doing work on background thread ...", i, _name];
NSLog(@"%@", message);
[NSThread sleepForTimeInterval:1];
}
// this completion block might be called from your delegate methods ...
if (_block)
{
dispatch_async(dispatch_get_main_queue(), ^ {
NSString *result = [NSString stringWithFormat:@"%@: result", _name];
_block(result);
});
}
}
@end
``` |
12,184,068 | Long time lurker, first time poster. I'm relatively new to objective-C so my apologies if I'm asking something fairly simple. My google & stack overflow-fu has let me down here, so I figured somebody could maybe help.
I have a synchronous process executing, say, three functions in a row - call it A -> B-> C , where task A executes, followed by B, followed by C.
Now, B involves an asynchronous process with a delegate callback for completion. But B must complete before C is executed, so I need some mechanism such that C is not triggered before B has finished. I imagine there must be a common design pattern for this problem?
Initially naive solution would be -
execute A
execute B
while (!B finished) {}
execute C
...but this seems really lame.
I suspect I can do this with some kind of block, but for the life of me I just can't figure it out. Could anyone help?
appreciate any assistance!
Guillaume | 2012/08/29 | [
"https://Stackoverflow.com/questions/12184068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1634015/"
] | Another approach to this problem might be the following: create an helper object for the async task and copy a completion block when the task is called. Call the completion block using the delegate methods once the async task is finished. As a result we might execute the tasks in order like the following:
```
FSTask *taskA = [FSTask taskWithName:@"Task A"];
FSAsyncTask *taskB = [FSAsyncTask asyncTaskWithName:@"Task B"];
FSTask *taskC = [FSTask taskWithName:@"Task C"];
[taskA performTaskWithCompletionBlock:^ (NSString *result) {
NSLog(@"%@", result);
[taskB performTaskWithCompletionBlock:^ (NSString *result) {
NSLog(@"%@", result);
[taskC performTaskWithCompletionBlock:^ (NSString *result) {
NSLog(@"%@", result);
}];
}];
}];
```
So how is this achieved? Well, look at the task objects below ...
---
**FSTask.m** - *synchronous work on main thread ...*
```
@interface FSTask ()
@property (nonatomic, copy) NSString *name;
@end
@implementation FSTask
@synthesize name = _name;
+ (FSTask *)taskWithName:(NSString *)name
{
FSTask *task = [[FSTask alloc] init];
if (task)
{
task.name = name;
}
return task;
}
- (void)performTaskWithCompletionBlock:(void (^)(NSString *taskResult))block
{
NSString *message = [NSString stringWithFormat:@"%@: doing work on main thread ...", _name];
NSLog(@"%@", message);
if (block)
{
NSString *result = [NSString stringWithFormat:@"%@: result", _name];
block(result);
}
}
@end
```
---
**FSAsyncTask.m** - *asynchronous work on background thread ...*
```
@interface FSAsyncTask ()
@property (nonatomic, copy) void (^block)(NSString *taskResult);
@property (nonatomic, copy) NSString *name;
- (void)performAsyncTask;
@end
@implementation FSAsyncTask
@synthesize block = _block;
@synthesize name = _name;
+ (FSAsyncTask *)asyncTaskWithName:(NSString *)name
{
FSAsyncTask *task = [[FSAsyncTask alloc] init];
if (task)
{
task.name = name;
}
return task;
}
- (void)performTaskWithCompletionBlock:(void (^)(NSString *taskResult))block
{
self.block = block;
// the call below could be e.g. a NSURLConnection that's being opened,
// in this case a NSURLConnectionDelegate method will return the result
// in this delegate method the completion block could be called ...
dispatch_queue_t queue = dispatch_queue_create("com.example.asynctask", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^ {
[self performAsyncTask];
});
}
#pragma mark - Private
- (void)performAsyncTask
{
for (int i = 0; i < 5; i++)
{
NSString *message = [NSString stringWithFormat:@"%d - %@: doing work on background thread ...", i, _name];
NSLog(@"%@", message);
[NSThread sleepForTimeInterval:1];
}
// this completion block might be called from your delegate methods ...
if (_block)
{
dispatch_async(dispatch_get_main_queue(), ^ {
NSString *result = [NSString stringWithFormat:@"%@: result", _name];
_block(result);
});
}
}
@end
``` | You can assign a block property to B where it would be used to execute a block of code before calling the delegate method. something like:
@property (nonatomic, copy)void(^yourBlock)(id blockParameter);
So, after calling B's delegate, you could call upon this block and execute it. Inside this block, you can call C's method. |
12,184,068 | Long time lurker, first time poster. I'm relatively new to objective-C so my apologies if I'm asking something fairly simple. My google & stack overflow-fu has let me down here, so I figured somebody could maybe help.
I have a synchronous process executing, say, three functions in a row - call it A -> B-> C , where task A executes, followed by B, followed by C.
Now, B involves an asynchronous process with a delegate callback for completion. But B must complete before C is executed, so I need some mechanism such that C is not triggered before B has finished. I imagine there must be a common design pattern for this problem?
Initially naive solution would be -
execute A
execute B
while (!B finished) {}
execute C
...but this seems really lame.
I suspect I can do this with some kind of block, but for the life of me I just can't figure it out. Could anyone help?
appreciate any assistance!
Guillaume | 2012/08/29 | [
"https://Stackoverflow.com/questions/12184068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1634015/"
] | the way I handled this is.
I created a NSMutableDictionary before the async call.
Then i make the async call. and do a check for the value I am waiting for
```
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[AsyncCallClass asyncCall:^{
@synchronized(dictionary) {
[dictionary setValue:myValue forKey:@"result"];
}
}];
while (true){
@synchronized(dictionary){
if ([dictionary valueForKey:@"resultValue"] != nil){
break;
}
}
[NSThread sleepForTimeInterval:.25];
}
MyResultClass *result = [dictionary valueForKey:@"resultValue"];
```
you can add time out for this too to stop it from being an infinite loop. but this is my solution. and it seems to work pretty well. | You can also pass C in a block like so...
define a custom block
`typedef void(^myCompletion)(BOOL complete);`
Create your B method
```
-(void)performBWithCompletionBlock:(myCompletion)complete;
{
// do your things
[self.delegate delegateCallback];
complete(YES);
}
```
then create BG / async ABC
```
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // now we're on a BG queue to perform our async tasks
[self performA];
[self performBWithCompletionBlock:^(BOOL complete) {
if (complete == YES)
[self performC];
}];
});
```
If you want C to be on the main thread
```
dispatch_async(dispatch_get_main_queue(), ^{
[self performC];
});
``` |
12,184,068 | Long time lurker, first time poster. I'm relatively new to objective-C so my apologies if I'm asking something fairly simple. My google & stack overflow-fu has let me down here, so I figured somebody could maybe help.
I have a synchronous process executing, say, three functions in a row - call it A -> B-> C , where task A executes, followed by B, followed by C.
Now, B involves an asynchronous process with a delegate callback for completion. But B must complete before C is executed, so I need some mechanism such that C is not triggered before B has finished. I imagine there must be a common design pattern for this problem?
Initially naive solution would be -
execute A
execute B
while (!B finished) {}
execute C
...but this seems really lame.
I suspect I can do this with some kind of block, but for the life of me I just can't figure it out. Could anyone help?
appreciate any assistance!
Guillaume | 2012/08/29 | [
"https://Stackoverflow.com/questions/12184068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1634015/"
] | Here is the typical code I use to do such things (adapt the completionBlock signature and method names to your needs of course)
```
typedef void (^BCompletionBlock)(void);
@interface B : NSObject <BDelegate>
@property(nonatomic, copy) BCompletionBlock completionBlock;
-(void)doAsynchronousActionWithCompletion:(BCompletionBlock)aCompletionBlock;
@end
@implementation B
-(void)doAsynchronousActionWithCompletion:(BCompletionBlock)aCompletionBlock
{
// Store the completion block for later use
self.completionBlock = aCompletionBlock;
// Then execute your asynchronous action, that will call some delegate method when done
[self doYourAsynchronousActionWithDelegate:self];
}
-(void)yourBDelegateMethodCalledWhenDone
{
// Upon your async task completion, call your completion block then
if (self.completionBlock) self.completionBlock();
}
@end
```
Then here is an example usage:
```
-(void)doActions
{
[a doSynchronousAction];
[b doAsynchronousActionWithCompletion:^{
[c doSynchronousAction];
// A,B,C are now done
}];
}
```
I do this quite all the time to "convert" actions that uses delegate methods (to tell me when they are done) to actions that uses completionBlocks (have some classes to do this for UIAlertViews, UIActionsSheets, and many more cases for example) and it works like a charm.
I find it much more easier to use completionBlocks than the delegate mechanism in such cases. | You can also pass C in a block like so...
define a custom block
`typedef void(^myCompletion)(BOOL complete);`
Create your B method
```
-(void)performBWithCompletionBlock:(myCompletion)complete;
{
// do your things
[self.delegate delegateCallback];
complete(YES);
}
```
then create BG / async ABC
```
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // now we're on a BG queue to perform our async tasks
[self performA];
[self performBWithCompletionBlock:^(BOOL complete) {
if (complete == YES)
[self performC];
}];
});
```
If you want C to be on the main thread
```
dispatch_async(dispatch_get_main_queue(), ^{
[self performC];
});
``` |
12,184,068 | Long time lurker, first time poster. I'm relatively new to objective-C so my apologies if I'm asking something fairly simple. My google & stack overflow-fu has let me down here, so I figured somebody could maybe help.
I have a synchronous process executing, say, three functions in a row - call it A -> B-> C , where task A executes, followed by B, followed by C.
Now, B involves an asynchronous process with a delegate callback for completion. But B must complete before C is executed, so I need some mechanism such that C is not triggered before B has finished. I imagine there must be a common design pattern for this problem?
Initially naive solution would be -
execute A
execute B
while (!B finished) {}
execute C
...but this seems really lame.
I suspect I can do this with some kind of block, but for the life of me I just can't figure it out. Could anyone help?
appreciate any assistance!
Guillaume | 2012/08/29 | [
"https://Stackoverflow.com/questions/12184068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1634015/"
] | Thanks for all the feeback - apologies for not responding sooner. I've now resolved this in a slightly different way to the suggestions:
Firstly, I extended NSObject to have the following method -
```
#import "NSObject+LTExtensions.h"
@implementation NSObject (Testing)
- (void) performSelectorWithBlock: (SEL) selector withSemaphore:(dispatch_semaphore_t)semaphore
{
[self performSelector:selector]; // This selector should complete the semaphore
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_release(semaphore);
}
@end
```
This allows me to execute a block via a selector. When the block executes, the thread on which it is executed will wait until signaled to proceed by a specific dispatch semaphore.
What we can then do is as follows:
* Call A
* Create a dispatch semaphore and define a selector which executes B
* Call the method defined above to execute B and wait for the selector to complete
* When B is completed (via a delegate callback), it signals the dispatch semaphore to suspend the wait
* I then execute C
So we have
```
A
B -> Asynchronous with delegate callback
C
```
Here's a simple example of how the above is implemented
```
-(void) methodA {
// ... do something
// Assign your semaphore (this is a dispatch_semaphore_t)
self.semaphore = dispatch_semaphore_create(0);
[self performSelectorWithBlock:@selector(methodB) withSemaphore:semaphore];
[self methodC];
}
-(void) methodB {
// ... do whatever needs to be done asynchronously
CFRunLoopRun();
}
-(void) methodBDelegateCallBack {
// This is called when B completes
// Signal completion
dispatch_semaphore_signal(self.semaphore);
CFRunLoopStop(CFRunLoopGetCurrent());
}
-(void) methodC {
...
}
```
Works very well without any issues (but I am new to Obj C, so there may be glaring issues with my approach). | You can assign a block property to B where it would be used to execute a block of code before calling the delegate method. something like:
@property (nonatomic, copy)void(^yourBlock)(id blockParameter);
So, after calling B's delegate, you could call upon this block and execute it. Inside this block, you can call C's method. |
12,184,068 | Long time lurker, first time poster. I'm relatively new to objective-C so my apologies if I'm asking something fairly simple. My google & stack overflow-fu has let me down here, so I figured somebody could maybe help.
I have a synchronous process executing, say, three functions in a row - call it A -> B-> C , where task A executes, followed by B, followed by C.
Now, B involves an asynchronous process with a delegate callback for completion. But B must complete before C is executed, so I need some mechanism such that C is not triggered before B has finished. I imagine there must be a common design pattern for this problem?
Initially naive solution would be -
execute A
execute B
while (!B finished) {}
execute C
...but this seems really lame.
I suspect I can do this with some kind of block, but for the life of me I just can't figure it out. Could anyone help?
appreciate any assistance!
Guillaume | 2012/08/29 | [
"https://Stackoverflow.com/questions/12184068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1634015/"
] | You can assign a block property to B where it would be used to execute a block of code before calling the delegate method. something like:
@property (nonatomic, copy)void(^yourBlock)(id blockParameter);
So, after calling B's delegate, you could call upon this block and execute it. Inside this block, you can call C's method. | You can also pass C in a block like so...
define a custom block
`typedef void(^myCompletion)(BOOL complete);`
Create your B method
```
-(void)performBWithCompletionBlock:(myCompletion)complete;
{
// do your things
[self.delegate delegateCallback];
complete(YES);
}
```
then create BG / async ABC
```
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // now we're on a BG queue to perform our async tasks
[self performA];
[self performBWithCompletionBlock:^(BOOL complete) {
if (complete == YES)
[self performC];
}];
});
```
If you want C to be on the main thread
```
dispatch_async(dispatch_get_main_queue(), ^{
[self performC];
});
``` |
12,184,068 | Long time lurker, first time poster. I'm relatively new to objective-C so my apologies if I'm asking something fairly simple. My google & stack overflow-fu has let me down here, so I figured somebody could maybe help.
I have a synchronous process executing, say, three functions in a row - call it A -> B-> C , where task A executes, followed by B, followed by C.
Now, B involves an asynchronous process with a delegate callback for completion. But B must complete before C is executed, so I need some mechanism such that C is not triggered before B has finished. I imagine there must be a common design pattern for this problem?
Initially naive solution would be -
execute A
execute B
while (!B finished) {}
execute C
...but this seems really lame.
I suspect I can do this with some kind of block, but for the life of me I just can't figure it out. Could anyone help?
appreciate any assistance!
Guillaume | 2012/08/29 | [
"https://Stackoverflow.com/questions/12184068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1634015/"
] | Thanks for all the feeback - apologies for not responding sooner. I've now resolved this in a slightly different way to the suggestions:
Firstly, I extended NSObject to have the following method -
```
#import "NSObject+LTExtensions.h"
@implementation NSObject (Testing)
- (void) performSelectorWithBlock: (SEL) selector withSemaphore:(dispatch_semaphore_t)semaphore
{
[self performSelector:selector]; // This selector should complete the semaphore
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_release(semaphore);
}
@end
```
This allows me to execute a block via a selector. When the block executes, the thread on which it is executed will wait until signaled to proceed by a specific dispatch semaphore.
What we can then do is as follows:
* Call A
* Create a dispatch semaphore and define a selector which executes B
* Call the method defined above to execute B and wait for the selector to complete
* When B is completed (via a delegate callback), it signals the dispatch semaphore to suspend the wait
* I then execute C
So we have
```
A
B -> Asynchronous with delegate callback
C
```
Here's a simple example of how the above is implemented
```
-(void) methodA {
// ... do something
// Assign your semaphore (this is a dispatch_semaphore_t)
self.semaphore = dispatch_semaphore_create(0);
[self performSelectorWithBlock:@selector(methodB) withSemaphore:semaphore];
[self methodC];
}
-(void) methodB {
// ... do whatever needs to be done asynchronously
CFRunLoopRun();
}
-(void) methodBDelegateCallBack {
// This is called when B completes
// Signal completion
dispatch_semaphore_signal(self.semaphore);
CFRunLoopStop(CFRunLoopGetCurrent());
}
-(void) methodC {
...
}
```
Works very well without any issues (but I am new to Obj C, so there may be glaring issues with my approach). | the way I handled this is.
I created a NSMutableDictionary before the async call.
Then i make the async call. and do a check for the value I am waiting for
```
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[AsyncCallClass asyncCall:^{
@synchronized(dictionary) {
[dictionary setValue:myValue forKey:@"result"];
}
}];
while (true){
@synchronized(dictionary){
if ([dictionary valueForKey:@"resultValue"] != nil){
break;
}
}
[NSThread sleepForTimeInterval:.25];
}
MyResultClass *result = [dictionary valueForKey:@"resultValue"];
```
you can add time out for this too to stop it from being an infinite loop. but this is my solution. and it seems to work pretty well. |
12,184,068 | Long time lurker, first time poster. I'm relatively new to objective-C so my apologies if I'm asking something fairly simple. My google & stack overflow-fu has let me down here, so I figured somebody could maybe help.
I have a synchronous process executing, say, three functions in a row - call it A -> B-> C , where task A executes, followed by B, followed by C.
Now, B involves an asynchronous process with a delegate callback for completion. But B must complete before C is executed, so I need some mechanism such that C is not triggered before B has finished. I imagine there must be a common design pattern for this problem?
Initially naive solution would be -
execute A
execute B
while (!B finished) {}
execute C
...but this seems really lame.
I suspect I can do this with some kind of block, but for the life of me I just can't figure it out. Could anyone help?
appreciate any assistance!
Guillaume | 2012/08/29 | [
"https://Stackoverflow.com/questions/12184068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1634015/"
] | Another approach to this problem might be the following: create an helper object for the async task and copy a completion block when the task is called. Call the completion block using the delegate methods once the async task is finished. As a result we might execute the tasks in order like the following:
```
FSTask *taskA = [FSTask taskWithName:@"Task A"];
FSAsyncTask *taskB = [FSAsyncTask asyncTaskWithName:@"Task B"];
FSTask *taskC = [FSTask taskWithName:@"Task C"];
[taskA performTaskWithCompletionBlock:^ (NSString *result) {
NSLog(@"%@", result);
[taskB performTaskWithCompletionBlock:^ (NSString *result) {
NSLog(@"%@", result);
[taskC performTaskWithCompletionBlock:^ (NSString *result) {
NSLog(@"%@", result);
}];
}];
}];
```
So how is this achieved? Well, look at the task objects below ...
---
**FSTask.m** - *synchronous work on main thread ...*
```
@interface FSTask ()
@property (nonatomic, copy) NSString *name;
@end
@implementation FSTask
@synthesize name = _name;
+ (FSTask *)taskWithName:(NSString *)name
{
FSTask *task = [[FSTask alloc] init];
if (task)
{
task.name = name;
}
return task;
}
- (void)performTaskWithCompletionBlock:(void (^)(NSString *taskResult))block
{
NSString *message = [NSString stringWithFormat:@"%@: doing work on main thread ...", _name];
NSLog(@"%@", message);
if (block)
{
NSString *result = [NSString stringWithFormat:@"%@: result", _name];
block(result);
}
}
@end
```
---
**FSAsyncTask.m** - *asynchronous work on background thread ...*
```
@interface FSAsyncTask ()
@property (nonatomic, copy) void (^block)(NSString *taskResult);
@property (nonatomic, copy) NSString *name;
- (void)performAsyncTask;
@end
@implementation FSAsyncTask
@synthesize block = _block;
@synthesize name = _name;
+ (FSAsyncTask *)asyncTaskWithName:(NSString *)name
{
FSAsyncTask *task = [[FSAsyncTask alloc] init];
if (task)
{
task.name = name;
}
return task;
}
- (void)performTaskWithCompletionBlock:(void (^)(NSString *taskResult))block
{
self.block = block;
// the call below could be e.g. a NSURLConnection that's being opened,
// in this case a NSURLConnectionDelegate method will return the result
// in this delegate method the completion block could be called ...
dispatch_queue_t queue = dispatch_queue_create("com.example.asynctask", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^ {
[self performAsyncTask];
});
}
#pragma mark - Private
- (void)performAsyncTask
{
for (int i = 0; i < 5; i++)
{
NSString *message = [NSString stringWithFormat:@"%d - %@: doing work on background thread ...", i, _name];
NSLog(@"%@", message);
[NSThread sleepForTimeInterval:1];
}
// this completion block might be called from your delegate methods ...
if (_block)
{
dispatch_async(dispatch_get_main_queue(), ^ {
NSString *result = [NSString stringWithFormat:@"%@: result", _name];
_block(result);
});
}
}
@end
``` | the way I handled this is.
I created a NSMutableDictionary before the async call.
Then i make the async call. and do a check for the value I am waiting for
```
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[AsyncCallClass asyncCall:^{
@synchronized(dictionary) {
[dictionary setValue:myValue forKey:@"result"];
}
}];
while (true){
@synchronized(dictionary){
if ([dictionary valueForKey:@"resultValue"] != nil){
break;
}
}
[NSThread sleepForTimeInterval:.25];
}
MyResultClass *result = [dictionary valueForKey:@"resultValue"];
```
you can add time out for this too to stop it from being an infinite loop. but this is my solution. and it seems to work pretty well. |
12,184,068 | Long time lurker, first time poster. I'm relatively new to objective-C so my apologies if I'm asking something fairly simple. My google & stack overflow-fu has let me down here, so I figured somebody could maybe help.
I have a synchronous process executing, say, three functions in a row - call it A -> B-> C , where task A executes, followed by B, followed by C.
Now, B involves an asynchronous process with a delegate callback for completion. But B must complete before C is executed, so I need some mechanism such that C is not triggered before B has finished. I imagine there must be a common design pattern for this problem?
Initially naive solution would be -
execute A
execute B
while (!B finished) {}
execute C
...but this seems really lame.
I suspect I can do this with some kind of block, but for the life of me I just can't figure it out. Could anyone help?
appreciate any assistance!
Guillaume | 2012/08/29 | [
"https://Stackoverflow.com/questions/12184068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1634015/"
] | Thanks for all the feeback - apologies for not responding sooner. I've now resolved this in a slightly different way to the suggestions:
Firstly, I extended NSObject to have the following method -
```
#import "NSObject+LTExtensions.h"
@implementation NSObject (Testing)
- (void) performSelectorWithBlock: (SEL) selector withSemaphore:(dispatch_semaphore_t)semaphore
{
[self performSelector:selector]; // This selector should complete the semaphore
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_release(semaphore);
}
@end
```
This allows me to execute a block via a selector. When the block executes, the thread on which it is executed will wait until signaled to proceed by a specific dispatch semaphore.
What we can then do is as follows:
* Call A
* Create a dispatch semaphore and define a selector which executes B
* Call the method defined above to execute B and wait for the selector to complete
* When B is completed (via a delegate callback), it signals the dispatch semaphore to suspend the wait
* I then execute C
So we have
```
A
B -> Asynchronous with delegate callback
C
```
Here's a simple example of how the above is implemented
```
-(void) methodA {
// ... do something
// Assign your semaphore (this is a dispatch_semaphore_t)
self.semaphore = dispatch_semaphore_create(0);
[self performSelectorWithBlock:@selector(methodB) withSemaphore:semaphore];
[self methodC];
}
-(void) methodB {
// ... do whatever needs to be done asynchronously
CFRunLoopRun();
}
-(void) methodBDelegateCallBack {
// This is called when B completes
// Signal completion
dispatch_semaphore_signal(self.semaphore);
CFRunLoopStop(CFRunLoopGetCurrent());
}
-(void) methodC {
...
}
```
Works very well without any issues (but I am new to Obj C, so there may be glaring issues with my approach). | Here is the typical code I use to do such things (adapt the completionBlock signature and method names to your needs of course)
```
typedef void (^BCompletionBlock)(void);
@interface B : NSObject <BDelegate>
@property(nonatomic, copy) BCompletionBlock completionBlock;
-(void)doAsynchronousActionWithCompletion:(BCompletionBlock)aCompletionBlock;
@end
@implementation B
-(void)doAsynchronousActionWithCompletion:(BCompletionBlock)aCompletionBlock
{
// Store the completion block for later use
self.completionBlock = aCompletionBlock;
// Then execute your asynchronous action, that will call some delegate method when done
[self doYourAsynchronousActionWithDelegate:self];
}
-(void)yourBDelegateMethodCalledWhenDone
{
// Upon your async task completion, call your completion block then
if (self.completionBlock) self.completionBlock();
}
@end
```
Then here is an example usage:
```
-(void)doActions
{
[a doSynchronousAction];
[b doAsynchronousActionWithCompletion:^{
[c doSynchronousAction];
// A,B,C are now done
}];
}
```
I do this quite all the time to "convert" actions that uses delegate methods (to tell me when they are done) to actions that uses completionBlocks (have some classes to do this for UIAlertViews, UIActionsSheets, and many more cases for example) and it works like a charm.
I find it much more easier to use completionBlocks than the delegate mechanism in such cases. |
8,948,906 | I have created a login for an application. I got it that if you type in the username and password then click on the checkbox it remembers the username and password. However, if you make any changes after you click the checkbox the they are not saved. I am wondering if there is a way to fix this and how would I got about doing this. What I am thinking is when click on the edittext it continually saves what is in the editext. Basically, something that would dynamically saves while the user changes the password or username while the checkbox is clicked.
```
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_log_in);
SharedPreferences.Editor editor;
name = (EditText) findViewById(R.id.userName);
password = (EditText) findViewById(R.id.password);
button = (Button) findViewById(R.id.Button01);
error = (TextView) findViewById(R.id.invalid);
error.setVisibility(View.INVISIBLE);
checkbox = (CheckBox) findViewById(R.id.remember);
LoadPreferences();
LoadPreferences1();
}
public void rememberInfo(View view) {
SavePrefernces("MEM1", name.getText().toString());
SavePrefernces("MEM2", password.getText().toString());
}
private void LoadPreferences1() {
SharedPreferences shardPreferences = getPreferences(MODE_PRIVATE);
String strSavedMem2 = shardPreferences.getString("MEM2", "");
password.setText(strSavedMem2);
}
private void LoadPreferences() {
SharedPreferences shardPreferences = getPreferences(MODE_PRIVATE);
String strSavedMem1 = shardPreferences.getString("MEM1", "");
name.setText(strSavedMem1);
}
private void SavePrefernces(String key, String value) {
SharedPreferences shardPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = shardPreferences.edit();
editor.putString(key, value);
editor.commit();
}
``` | 2012/01/20 | [
"https://Stackoverflow.com/questions/8948906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708678/"
] | I finally got it:
I previously added CSS customisations to Blogger for the `<code>` HTML tag like this:
```
code {
border: 1px solid #ccc;
background-color: #f6f6f6;
font: 0.8em 'Courier New', Courier, Fixed;
border-spacing: 0;
padding: 0.3em;
display: block;
}
```
and the culprit is `display : block;`, which perturbates SyntaxHighlighter.
Replacing `code {...}` with `pre code {...}` does the trick for me. | I've tried it on my blog and it works. You should just add all those tags, right before `</head>` tag. This is what I've for my blog:
```
<!--SYNTAX HIGHLIGHTER BEGINS-->
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shCore.css' rel='stylesheet' type='text/css'/>
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shThemeDefault.css' rel='stylesheet' type='text/css'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCpp.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCSharp.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCss.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJava.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJScript.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPhp.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPython.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushRuby.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushSql.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushVb.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPerl.js' type='text/javascript'/>
<script language='javascript'>
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/current/scripts/clipboard.swf';
SyntaxHighlighter.all();
</script>
<!--SYNTAX HIGHLIGHTER ENDS-->
```
**`</head>`** |
1,572,796 | I want to learn how the computer represents the `double` type in bit, but the `&` and `|` bit operators can't use `double`. And `memcpy(&d, &src, 8)` also doesn't seem to work. Any suggestions? | 2009/10/15 | [
"https://Stackoverflow.com/questions/1572796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/121051/"
] | Here:
```
#include <stdio.h>
int main ()
{
double decker = 1.0;
unsigned char * desmond = (unsigned char *) & decker;
int i;
for (i = 0; i < sizeof (double); i++) {
printf ("%02X ", desmond[i]);
}
printf ("\n");
return 0;
}
```
You can try it: <http://codepad.org/onHnAcnC> | That isn't going to be very enlightening unless you also know a bit about typical IEEE FP representations.
Most likely the way your machine represents doubles is spelled out [here](http://www.psc.edu/general/software/packages/ieee/ieee.php). |
1,572,796 | I want to learn how the computer represents the `double` type in bit, but the `&` and `|` bit operators can't use `double`. And `memcpy(&d, &src, 8)` also doesn't seem to work. Any suggestions? | 2009/10/15 | [
"https://Stackoverflow.com/questions/1572796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/121051/"
] | A particular bit layout by itself is meaningless. Suppose I have the following: `1101`
Maybe I say that is unsigned and it represents the value 13.
Maybe it is signed and that high bit signifies that the value is a negative which means it is now -5.
Consider further that I consider the high two bits to be a base and the low two bits to be an exponent, then I get the value 3.
You see, it isnt the storage, its the interpretation. Read up on how floating point values are represented and interpreted; it will serve you much better than seeing how the bits are packed. | The key is to convert the `double` to a `long long` (assuming `sizeof(double) == sizeof(long long)`) without changing binary representation. This can be achieved by one of the following methods:
* cast: `double a; long long b = *((long long *)&a);`
* union: `union { double a ; long long b };` |
1,572,796 | I want to learn how the computer represents the `double` type in bit, but the `&` and `|` bit operators can't use `double`. And `memcpy(&d, &src, 8)` also doesn't seem to work. Any suggestions? | 2009/10/15 | [
"https://Stackoverflow.com/questions/1572796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/121051/"
] | Here:
```
#include <stdio.h>
int main ()
{
double decker = 1.0;
unsigned char * desmond = (unsigned char *) & decker;
int i;
for (i = 0; i < sizeof (double); i++) {
printf ("%02X ", desmond[i]);
}
printf ("\n");
return 0;
}
```
You can try it: <http://codepad.org/onHnAcnC> | The key is to convert the `double` to a `long long` (assuming `sizeof(double) == sizeof(long long)`) without changing binary representation. This can be achieved by one of the following methods:
* cast: `double a; long long b = *((long long *)&a);`
* union: `union { double a ; long long b };` |
1,572,796 | I want to learn how the computer represents the `double` type in bit, but the `&` and `|` bit operators can't use `double`. And `memcpy(&d, &src, 8)` also doesn't seem to work. Any suggestions? | 2009/10/15 | [
"https://Stackoverflow.com/questions/1572796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/121051/"
] | A particular bit layout by itself is meaningless. Suppose I have the following: `1101`
Maybe I say that is unsigned and it represents the value 13.
Maybe it is signed and that high bit signifies that the value is a negative which means it is now -5.
Consider further that I consider the high two bits to be a base and the low two bits to be an exponent, then I get the value 3.
You see, it isnt the storage, its the interpretation. Read up on how floating point values are represented and interpreted; it will serve you much better than seeing how the bits are packed. | That isn't going to be very enlightening unless you also know a bit about typical IEEE FP representations.
Most likely the way your machine represents doubles is spelled out [here](http://www.psc.edu/general/software/packages/ieee/ieee.php). |
1,572,796 | I want to learn how the computer represents the `double` type in bit, but the `&` and `|` bit operators can't use `double`. And `memcpy(&d, &src, 8)` also doesn't seem to work. Any suggestions? | 2009/10/15 | [
"https://Stackoverflow.com/questions/1572796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/121051/"
] | A particular bit layout by itself is meaningless. Suppose I have the following: `1101`
Maybe I say that is unsigned and it represents the value 13.
Maybe it is signed and that high bit signifies that the value is a negative which means it is now -5.
Consider further that I consider the high two bits to be a base and the low two bits to be an exponent, then I get the value 3.
You see, it isnt the storage, its the interpretation. Read up on how floating point values are represented and interpreted; it will serve you much better than seeing how the bits are packed. | Another option is to use [bitfields](http://publications.gbdirect.co.uk/c_book/chapter6/bitfields.html). Armed with such a structure and knowledge of how a double is supposed to be stored on your computer you can very easily print out the different parts of the internal representation of the double. A bit like they do [here](http://www.cs.cf.ac.uk/Dave/C/node13.html#SECTION001321000000000000000). |
1,572,796 | I want to learn how the computer represents the `double` type in bit, but the `&` and `|` bit operators can't use `double`. And `memcpy(&d, &src, 8)` also doesn't seem to work. Any suggestions? | 2009/10/15 | [
"https://Stackoverflow.com/questions/1572796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/121051/"
] | ```
union {
double d;
unsigned char c[sizeof(double)];
} d;
int main(int ac, char **av) {
int i;
char s1[80], s2[80];
d.d = 1.0;
for(i = 0; i < sizeof d; ++i) {
sprintf(s1 + i * 3, " %02x", d.c[i]);
sprintf(s2 + i * 3, " %02x", d.c[sizeof d - 1 - i]);
}
printf("%s\n%s\n", s1, s2);
return 0;
}
$ ./a.out
00 00 00 00 00 00 f0 3f
3f f0 00 00 00 00 00 00
```
Or you could just [read about the IEEE 754 standard](http://en.wikipedia.org/wiki/IEEE_754-1985), which specifies representation.
<http://en.wikipedia.org/wiki/IEEE_754-1985> | A particular bit layout by itself is meaningless. Suppose I have the following: `1101`
Maybe I say that is unsigned and it represents the value 13.
Maybe it is signed and that high bit signifies that the value is a negative which means it is now -5.
Consider further that I consider the high two bits to be a base and the low two bits to be an exponent, then I get the value 3.
You see, it isnt the storage, its the interpretation. Read up on how floating point values are represented and interpreted; it will serve you much better than seeing how the bits are packed. |
1,572,796 | I want to learn how the computer represents the `double` type in bit, but the `&` and `|` bit operators can't use `double`. And `memcpy(&d, &src, 8)` also doesn't seem to work. Any suggestions? | 2009/10/15 | [
"https://Stackoverflow.com/questions/1572796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/121051/"
] | ```
union {
double d;
unsigned char c[sizeof(double)];
} d;
int main(int ac, char **av) {
int i;
char s1[80], s2[80];
d.d = 1.0;
for(i = 0; i < sizeof d; ++i) {
sprintf(s1 + i * 3, " %02x", d.c[i]);
sprintf(s2 + i * 3, " %02x", d.c[sizeof d - 1 - i]);
}
printf("%s\n%s\n", s1, s2);
return 0;
}
$ ./a.out
00 00 00 00 00 00 f0 3f
3f f0 00 00 00 00 00 00
```
Or you could just [read about the IEEE 754 standard](http://en.wikipedia.org/wiki/IEEE_754-1985), which specifies representation.
<http://en.wikipedia.org/wiki/IEEE_754-1985> | Another option is to use [bitfields](http://publications.gbdirect.co.uk/c_book/chapter6/bitfields.html). Armed with such a structure and knowledge of how a double is supposed to be stored on your computer you can very easily print out the different parts of the internal representation of the double. A bit like they do [here](http://www.cs.cf.ac.uk/Dave/C/node13.html#SECTION001321000000000000000). |
1,572,796 | I want to learn how the computer represents the `double` type in bit, but the `&` and `|` bit operators can't use `double`. And `memcpy(&d, &src, 8)` also doesn't seem to work. Any suggestions? | 2009/10/15 | [
"https://Stackoverflow.com/questions/1572796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/121051/"
] | Here:
```
#include <stdio.h>
int main ()
{
double decker = 1.0;
unsigned char * desmond = (unsigned char *) & decker;
int i;
for (i = 0; i < sizeof (double); i++) {
printf ("%02X ", desmond[i]);
}
printf ("\n");
return 0;
}
```
You can try it: <http://codepad.org/onHnAcnC> | This works for me
```
#include <stdio.h>
#include <string.h> /* memmove */
int main(void) {
unsigned char dontdothis[sizeof (double)];
double x = 62.42;
printf("%f\n", x);
memmove(&dontdothis, &x, sizeof dontdothis);
/* examine/change the array dontdothis */
dontdothis[sizeof x - 1] ^= 0x80;
/* examine/change the array dontdothis */
memmove(&x, &dontdothis, sizeof dontdothis);
printf("%f\n", x);
return 0;
}
```
The result is
```
62.420000
-62.420000
``` |
1,572,796 | I want to learn how the computer represents the `double` type in bit, but the `&` and `|` bit operators can't use `double`. And `memcpy(&d, &src, 8)` also doesn't seem to work. Any suggestions? | 2009/10/15 | [
"https://Stackoverflow.com/questions/1572796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/121051/"
] | Here:
```
#include <stdio.h>
int main ()
{
double decker = 1.0;
unsigned char * desmond = (unsigned char *) & decker;
int i;
for (i = 0; i < sizeof (double); i++) {
printf ("%02X ", desmond[i]);
}
printf ("\n");
return 0;
}
```
You can try it: <http://codepad.org/onHnAcnC> | A particular bit layout by itself is meaningless. Suppose I have the following: `1101`
Maybe I say that is unsigned and it represents the value 13.
Maybe it is signed and that high bit signifies that the value is a negative which means it is now -5.
Consider further that I consider the high two bits to be a base and the low two bits to be an exponent, then I get the value 3.
You see, it isnt the storage, its the interpretation. Read up on how floating point values are represented and interpreted; it will serve you much better than seeing how the bits are packed. |
1,572,796 | I want to learn how the computer represents the `double` type in bit, but the `&` and `|` bit operators can't use `double`. And `memcpy(&d, &src, 8)` also doesn't seem to work. Any suggestions? | 2009/10/15 | [
"https://Stackoverflow.com/questions/1572796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/121051/"
] | ```
union {
double d;
unsigned char c[sizeof(double)];
} d;
int main(int ac, char **av) {
int i;
char s1[80], s2[80];
d.d = 1.0;
for(i = 0; i < sizeof d; ++i) {
sprintf(s1 + i * 3, " %02x", d.c[i]);
sprintf(s2 + i * 3, " %02x", d.c[sizeof d - 1 - i]);
}
printf("%s\n%s\n", s1, s2);
return 0;
}
$ ./a.out
00 00 00 00 00 00 f0 3f
3f f0 00 00 00 00 00 00
```
Or you could just [read about the IEEE 754 standard](http://en.wikipedia.org/wiki/IEEE_754-1985), which specifies representation.
<http://en.wikipedia.org/wiki/IEEE_754-1985> | This works for me
```
#include <stdio.h>
#include <string.h> /* memmove */
int main(void) {
unsigned char dontdothis[sizeof (double)];
double x = 62.42;
printf("%f\n", x);
memmove(&dontdothis, &x, sizeof dontdothis);
/* examine/change the array dontdothis */
dontdothis[sizeof x - 1] ^= 0x80;
/* examine/change the array dontdothis */
memmove(&x, &dontdothis, sizeof dontdothis);
printf("%f\n", x);
return 0;
}
```
The result is
```
62.420000
-62.420000
``` |
5,333,295 | I need to approx (1-x)^0.25 with given accuracy (0.0001 e.g.). I'm using [expansion found on Wikipedia](http://en.wikipedia.org/wiki/Taylor_series#List_of_Maclaurin_series_of_some_common_functions) for (1+x)^0.25. I need to stop approximating when current expression is less than the accuracy.
```
long double s(long double x, long double d) {
long double w = 1;
long double n = 1; // nth expression in series
long double tmp = 1;
// sum while last expression is greater than accuracy
while (fabsl(tmp) >= d) {
tmp *= (1.25 / n - 1) * (-x); // the next expression
w += tmp; // is added to approximation
n++;
}
return w;
}
```
Don't mind long double n. :P This works well when I'm not checking value of current expression but when I'm computing 1000 or more expressions. Domain of the function is <-1;1> and s() calculates approximation well for x in <-1;~0.6>. The bigger the argument is the bigger is the error of calculation. From 0.6 it exceeds the accuracy.
I'm not sure if the problem is clear enough because I don't know English math language well. The thing is what's the matter with while condition and why the function s() doesn't approximate correctly.
**EDIT:**
Problem mostly solved. When x>0 I have to substract absolute value of consecutive expressions from 1.
```
if (x<0)
w += tmp;
else
w -= fabsl(tmp);
```
After that accuracy increases a lot (fox x>0 of course). Redundant error stems from long double inaccuracy. That's all. Thanks anyway to you guys. | 2011/03/17 | [
"https://Stackoverflow.com/questions/5333295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/575657/"
] | See <http://bowlerframework.org/>
Sounds like exactly what you need. | You can just use Scala + Wicket. This is nice combination. |
16,991,728 | I want to subtract the smallest value in each subset of a data frame from each value in that subset i.e.
```
A <- c(1,3,5,6,4,5,6,7,10)
B <- rep(1:4, length.out=length(A))
df <- data.frame(A, B)
df <- df[order(B),]
```
Subtracting would give me:
```
A B
1 0 1
2 3 1
3 9 1
4 0 2
5 2 2
6 0 3
7 1 3
8 0 4
9 1 4
``` | 2013/06/07 | [
"https://Stackoverflow.com/questions/16991728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2464725/"
] | I think the output you show is not correct. In any case, from what you explain, I think this is what you want. This uses `ave` base function:
```
within(df, { A <- ave(A, B, FUN=function(x) x-min(x))})
A B
1 0 1
5 3 1
9 9 1
2 0 2
6 2 2
3 0 3
7 1 3
4 0 4
8 1 4
```
Of course there are other alternatives such as `plyr` and `data.table`. | Echoing Arun's comment above, I think your expected output might be off. In any event, you should be able to use can use `tapply` to calculate subsets and then use `match` to line those subsets up with the original values:
```
subs <- tapply(df$A, df$B, min)
df$A <- df$A - subs[match(df$B, names(subs))]
df
A B
1 0 1
5 3 1
9 9 1
2 0 2
6 2 2
3 0 3
7 1 3
4 0 4
8 1 4
``` |
1,195,206 | If root is very near to the max/min, what happens with Newton Raphson method? Does it diverge? Or converges slowly? I know if some iteration involves a stationery point then we can not go further. But is there a possiblity that even in such a case we can avoid the stationery point? | 2015/03/18 | [
"https://math.stackexchange.com/questions/1195206",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/33247/"
] | $$\frac{\sin a - \cos a + 1}{\sin a + \cos a - 1}$$
$$= \frac{(\sin a - \cos a + 1)(\sin a + \cos a + 1)}{(\sin a + \cos a - 1)(\sin a + \cos a + 1)}$$
$$= \frac{\sin^2 a + 2 \sin a + 1 - \cos^2 a}{\sin^2 a + 2 \sin a \cos a + \cos^2 a - 1}$$
$$= \frac{2\sin^2 a + 2\sin a}{2 \sin a \cos a}$$
$$= \frac{\sin a + 1}{\cos a}$$ | Hint : Multiply and divide by $\sin{a}-(\cos{a}-1)$ . |
1,195,206 | If root is very near to the max/min, what happens with Newton Raphson method? Does it diverge? Or converges slowly? I know if some iteration involves a stationery point then we can not go further. But is there a possiblity that even in such a case we can avoid the stationery point? | 2015/03/18 | [
"https://math.stackexchange.com/questions/1195206",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/33247/"
] | $$\frac{\sin a - \cos a + 1}{\sin a + \cos a - 1}$$
$$= \frac{(\sin a - \cos a + 1)(\sin a + \cos a + 1)}{(\sin a + \cos a - 1)(\sin a + \cos a + 1)}$$
$$= \frac{\sin^2 a + 2 \sin a + 1 - \cos^2 a}{\sin^2 a + 2 \sin a \cos a + \cos^2 a - 1}$$
$$= \frac{2\sin^2 a + 2\sin a}{2 \sin a \cos a}$$
$$= \frac{\sin a + 1}{\cos a}$$ | Assume that $\cos(a)\ne0$ and $\sin(a)+\cos(a)-1\ne0$, then cross-multiply:
$$
\begin{align}
&(\sin(a)-\cos(a)+1)\cos(a)-(\sin(a)+\cos(a)-1)(\sin(a)+1)\\
&=\small\overbrace{\color{#C00000}{\sin(a)\cos(a)}\color{#0000F0}{-\cos^2(a)}\color{#00A000}{+\cos(a)}}^{\large(\sin(a)-\cos(a)+1)\cos(a)}\overbrace{\color{#0000F0}{-\sin^2(a)}\color{#C00000}{-\sin(a)\cos(a)}\color{#C0A000}{+\sin(a)}}^{\large-(\sin(a)+\cos(a)-1)\sin(a)}\overbrace{\color{#C0A000}{-\sin(a)}\color{#00A000}{-\cos(a)}\color{#0000F0}{+1}\vphantom{1^2}}^{\large-(\sin(a)+\cos(a)-1)}\\[12pt]
&=0
\end{align}
$$
Terms of the same color cancel. The only identity we need to use is $\sin^2(a)+\cos^2(a)=1$. |
13,303 | Is there a way to use Twig's `{% spaceless %}` tag only under certain conditions?
For example, say you wanted the HTML to be spaceless in the live environment but wanted it uncompressed in the dev environment. I tried something like:
```
{% if isDev %}
{% spaceless %}
{% endif %}
{# Some code... #}
{% if isDev %}
{% endspaceless %}
{% endif %}
```
But this just throws a Twig error. | 2016/01/19 | [
"https://craftcms.stackexchange.com/questions/13303",
"https://craftcms.stackexchange.com",
"https://craftcms.stackexchange.com/users/467/"
] | Yes, Twig (sometimes) complains if you're splitting tags which belong together into different conditionals, I ran into that issue in a similar situation.
But as already noted in the comments, I'm also curious why you want to split the `spaceless` tag. If it's about minifying HTML, the tag isn't very efficient anyways and I'd recommend to use something like Andrew Welch's [Minify plugin](https://github.com/nystudio107/minify) instead. | You could do it by buffering your output, i.e.
```
{% set output %}
{# Your code here #}
{% endset %}
{% if isDev %}
{{ output }}
{% else %}
{% spaceless %}
{{ output }}
{% endspaceless %}
{% endif %}
``` |
62,412,163 | Here is the Apache Reverse proxy and load balancer, the website/reports url is not coming up
```
<IfModule mod_proxy.c>
ProxyPreserveHost On
<Proxy balancer://app0102>
BalancerMember https://serverapp01.com
BalancerMember https://serverapp02.com
</Proxy>
ProxyPass / "balancer://app0102/"
ProxyPassReverse "/" "balancer://app0102/"
</IfModule>
```
if I point to single server, the website/reports url work
```
<VirtualHost *:443>
<IfModule mod_proxy.c>
ProxyPass / https://serverapp01.com
```
/ retry=1 acquire=3000 timeout=1200 Keepalive=On
ProxyPassReverse / <https://serverapp01.com>
Website works in both cases, Any ideas on what I am missing
Thanks
Nate | 2020/06/16 | [
"https://Stackoverflow.com/questions/62412163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1291353/"
] | If your backend server is using SessionCookie then you can use the same cookie for sticky session.
```
<Proxy balancer://app0102>
BalancerMember https://serverapp01.com route=node1
BalancerMember https://serverapp02.com route=node2
</Proxy>
ProxyTimeout 60
ProxyStatus On
ProxyPass / balancer://app0102/ stickysession=JSESSIONID|jsessionid
ProxyPassReverse / bbalancer://app0102
```
If your backend server is not using Session Cookie then you can use route for sticky session.
```
Header add Set-Cookie "ROUTEID=.%{BALANCER_WORKER_ROUTE}e; path=/" env=BALANCER_ROUTE_CHANGED
<Proxy "balancer://app0102">
BalancerMember https://serverapp01.com route=node1
BalancerMember https://serverapp02.com route=node2
ProxySet stickysession=ROUTEID
</Proxy>
ProxyPass / balancer://app0102/
ProxyPassReverse / balancer://app0102/
```
Make sure that your both backend server is running. | I suggest using quotes on both source and destionation,
such as:
>
> ProxyPass "/" "balancer://app0102/"
>
>
> |
18,888,297 | In my application i'm using edit text view in exapandable listview.
When i'm trying to add text in edit text the focus of editext automatically changing.
i'm not able to put text in edit text properly.
what should i do?
edit text xml-
```
<EditText
android:id="@+id/editDetails"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="false"
android:lines="3"
android:focusable="true"
android:focusableInTouchMode="true" />
``` | 2013/09/19 | [
"https://Stackoverflow.com/questions/18888297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1501644/"
] | See this might help you '
Read from here [LINK TO UNDERSTAND](http://developer.android.com/guide/topics/data/data-storage.html#filesInternal)
```
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
``` | The correct way to access Android storage is
```
Environment.getExternalStorageDirectory()
```
In your case, this would return `/storage/sdcard1`, and you could code
```
Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"Android/New_Data.xml";
```
to get the pathname.
See [the Environment reference](http://developer.android.com/reference/android/os/Environment.html#getExternalStorageState%28%29). |
18,888,297 | In my application i'm using edit text view in exapandable listview.
When i'm trying to add text in edit text the focus of editext automatically changing.
i'm not able to put text in edit text properly.
what should i do?
edit text xml-
```
<EditText
android:id="@+id/editDetails"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="false"
android:lines="3"
android:focusable="true"
android:focusableInTouchMode="true" />
``` | 2013/09/19 | [
"https://Stackoverflow.com/questions/18888297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1501644/"
] | See this might help you '
Read from here [LINK TO UNDERSTAND](http://developer.android.com/guide/topics/data/data-storage.html#filesInternal)
```
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
``` | Try getDir().
Refer [Android getting external storage Absolute Path](https://stackoverflow.com/questions/17546718/android-getting-internal-storage-absolute-path)
```
File getdirectory = context.getDir("Samplefolder", Context.MODE_PRIVATE);
if(!getdirectory .exists)
{
getdirectory .mkdirs();
}
``` |
139,015 | I have a bunch of PDF files and my Perl program needs to do a full-text search of them to return which ones contain a specific string.
To date I have been using this:
```
my @search_results = `grep -i -l \"$string\" *.pdf`;
```
where $string is the text to look for.
However this fails for most pdf's because the file format is obviously not ASCII.
What can I do that's easiest?
Clarification:
There are about 300 pdf's whose name I do not know in advance. PDF::Core is probably overkill. I am trying to get pdftotext and grep to play nice with each other given I don't know the names of the pdf's, I can't find the right syntax yet.
Final solution using Adam Bellaire's suggestion below:
```
@search_results = `for i in \$( ls ); do pdftotext \$i - | grep --label="\$i" -i -l "$search_string"; done`;
``` | 2008/09/26 | [
"https://Stackoverflow.com/questions/139015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22654/"
] | The PerlMonks thread [here](http://www.perlmonks.org/?node_id=582868) talks about this problem.
It seems that for your situation, it might be simplest to get **pdftotext** (the command line tool), then you can do something like:
```
my @search_results = `pdftotext myfile.pdf - | grep -i -l \"$string\"`;
``` | You may want to look at [PDF::Core](http://search.cpan.org/perldoc?PDF::Core). |
139,015 | I have a bunch of PDF files and my Perl program needs to do a full-text search of them to return which ones contain a specific string.
To date I have been using this:
```
my @search_results = `grep -i -l \"$string\" *.pdf`;
```
where $string is the text to look for.
However this fails for most pdf's because the file format is obviously not ASCII.
What can I do that's easiest?
Clarification:
There are about 300 pdf's whose name I do not know in advance. PDF::Core is probably overkill. I am trying to get pdftotext and grep to play nice with each other given I don't know the names of the pdf's, I can't find the right syntax yet.
Final solution using Adam Bellaire's suggestion below:
```
@search_results = `for i in \$( ls ); do pdftotext \$i - | grep --label="\$i" -i -l "$search_string"; done`;
``` | 2008/09/26 | [
"https://Stackoverflow.com/questions/139015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22654/"
] | The easiest fulltext index/seach I've used is mysql. You just insert into the table with the appropriate index on it. You need to spend some time working out the relative weightings for fields (a match in the title might score higher than a match in the body), but this is all possible, albeit with some hairy sql.
Plucene is deprecated (there hasn't been any active work on it in the last two years afaik) in favour of KinoSearch. KinoSearch grew, in part, out of understanding the architectural limitations of Plucene.
If you have ~300 pdfs, then once you've extracted the text from the PDF (assuming the PDF has text and not just images of text ;) and depending on your query volumes you may find grep is sufficient.
However, I'd strongly suggest the mysql/kinosearch route as they have covered a lot of ground (stemming, stopwords, term weighting, token parsing) that you don't benefit from getting bogged down with.
KinoSearch is probably faster than the mysql route, but the mysql route gives you more widely used standard software/tools/developer-experience. And you get the ability to use the power of sql to augement your freetext search queries.
So unless you're talking HUGE data-sets and insane query volumes, my money would be on mysql. | You could try Lucene (the Perl port is called Plucene). The searches are incredibly fast and I know that PDFBox already knows how to index PDF files with Lucene. PDFBox is Java, but chances are there is something very similar somewhere in CPAN. Even if you can't find something that already adds PDF files to a Lucene index it shouldn't be more than a few lines of code to do it yourself. Lucene will give you quite a few more searching options than simply looking for a string in a file.
There's also a very quick and dirty way. Text in a PDF file is actually stored as plain text. If you open a PDF in a text editor or use 'strings' you can see the text in there. The binary junk is usually embedded fonts, images, etc. |
139,015 | I have a bunch of PDF files and my Perl program needs to do a full-text search of them to return which ones contain a specific string.
To date I have been using this:
```
my @search_results = `grep -i -l \"$string\" *.pdf`;
```
where $string is the text to look for.
However this fails for most pdf's because the file format is obviously not ASCII.
What can I do that's easiest?
Clarification:
There are about 300 pdf's whose name I do not know in advance. PDF::Core is probably overkill. I am trying to get pdftotext and grep to play nice with each other given I don't know the names of the pdf's, I can't find the right syntax yet.
Final solution using Adam Bellaire's suggestion below:
```
@search_results = `for i in \$( ls ); do pdftotext \$i - | grep --label="\$i" -i -l "$search_string"; done`;
``` | 2008/09/26 | [
"https://Stackoverflow.com/questions/139015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22654/"
] | My library, [CAM::PDF](http://search.cpan.org/dist/CAM-PDF/), has support for extracting text, but it's an inherently hard problem given the graphical orientation of PDF syntax. So, the output is sometimes gibberish. CAM::PDF bundles a [getpdftext.pl](http://search.cpan.org/dist/CAM-PDF/bin/getpdftext.pl) program, or you can invoke the functionality like so:
```
my $doc = CAM::PDF->new($filename) || die "$CAM::PDF::errstr\n";
for my $pagenum (1 .. $doc->numPages()) {
my $text = $doc->getPageText($pagenum);
print $text;
}
``` | You could try Lucene (the Perl port is called Plucene). The searches are incredibly fast and I know that PDFBox already knows how to index PDF files with Lucene. PDFBox is Java, but chances are there is something very similar somewhere in CPAN. Even if you can't find something that already adds PDF files to a Lucene index it shouldn't be more than a few lines of code to do it yourself. Lucene will give you quite a few more searching options than simply looking for a string in a file.
There's also a very quick and dirty way. Text in a PDF file is actually stored as plain text. If you open a PDF in a text editor or use 'strings' you can see the text in there. The binary junk is usually embedded fonts, images, etc. |
139,015 | I have a bunch of PDF files and my Perl program needs to do a full-text search of them to return which ones contain a specific string.
To date I have been using this:
```
my @search_results = `grep -i -l \"$string\" *.pdf`;
```
where $string is the text to look for.
However this fails for most pdf's because the file format is obviously not ASCII.
What can I do that's easiest?
Clarification:
There are about 300 pdf's whose name I do not know in advance. PDF::Core is probably overkill. I am trying to get pdftotext and grep to play nice with each other given I don't know the names of the pdf's, I can't find the right syntax yet.
Final solution using Adam Bellaire's suggestion below:
```
@search_results = `for i in \$( ls ); do pdftotext \$i - | grep --label="\$i" -i -l "$search_string"; done`;
``` | 2008/09/26 | [
"https://Stackoverflow.com/questions/139015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22654/"
] | The PerlMonks thread [here](http://www.perlmonks.org/?node_id=582868) talks about this problem.
It seems that for your situation, it might be simplest to get **pdftotext** (the command line tool), then you can do something like:
```
my @search_results = `pdftotext myfile.pdf - | grep -i -l \"$string\"`;
``` | I second Adam Bellaire solution. I used pdftotext utility to create full-text index of my ebook library. It's somewhat slow but does its job. As for full-text, try PLucene or KinoSearch to store full-text index. |
139,015 | I have a bunch of PDF files and my Perl program needs to do a full-text search of them to return which ones contain a specific string.
To date I have been using this:
```
my @search_results = `grep -i -l \"$string\" *.pdf`;
```
where $string is the text to look for.
However this fails for most pdf's because the file format is obviously not ASCII.
What can I do that's easiest?
Clarification:
There are about 300 pdf's whose name I do not know in advance. PDF::Core is probably overkill. I am trying to get pdftotext and grep to play nice with each other given I don't know the names of the pdf's, I can't find the right syntax yet.
Final solution using Adam Bellaire's suggestion below:
```
@search_results = `for i in \$( ls ); do pdftotext \$i - | grep --label="\$i" -i -l "$search_string"; done`;
``` | 2008/09/26 | [
"https://Stackoverflow.com/questions/139015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22654/"
] | The PerlMonks thread [here](http://www.perlmonks.org/?node_id=582868) talks about this problem.
It seems that for your situation, it might be simplest to get **pdftotext** (the command line tool), then you can do something like:
```
my @search_results = `pdftotext myfile.pdf - | grep -i -l \"$string\"`;
``` | The easiest fulltext index/seach I've used is mysql. You just insert into the table with the appropriate index on it. You need to spend some time working out the relative weightings for fields (a match in the title might score higher than a match in the body), but this is all possible, albeit with some hairy sql.
Plucene is deprecated (there hasn't been any active work on it in the last two years afaik) in favour of KinoSearch. KinoSearch grew, in part, out of understanding the architectural limitations of Plucene.
If you have ~300 pdfs, then once you've extracted the text from the PDF (assuming the PDF has text and not just images of text ;) and depending on your query volumes you may find grep is sufficient.
However, I'd strongly suggest the mysql/kinosearch route as they have covered a lot of ground (stemming, stopwords, term weighting, token parsing) that you don't benefit from getting bogged down with.
KinoSearch is probably faster than the mysql route, but the mysql route gives you more widely used standard software/tools/developer-experience. And you get the ability to use the power of sql to augement your freetext search queries.
So unless you're talking HUGE data-sets and insane query volumes, my money would be on mysql. |
139,015 | I have a bunch of PDF files and my Perl program needs to do a full-text search of them to return which ones contain a specific string.
To date I have been using this:
```
my @search_results = `grep -i -l \"$string\" *.pdf`;
```
where $string is the text to look for.
However this fails for most pdf's because the file format is obviously not ASCII.
What can I do that's easiest?
Clarification:
There are about 300 pdf's whose name I do not know in advance. PDF::Core is probably overkill. I am trying to get pdftotext and grep to play nice with each other given I don't know the names of the pdf's, I can't find the right syntax yet.
Final solution using Adam Bellaire's suggestion below:
```
@search_results = `for i in \$( ls ); do pdftotext \$i - | grep --label="\$i" -i -l "$search_string"; done`;
``` | 2008/09/26 | [
"https://Stackoverflow.com/questions/139015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22654/"
] | You may want to look at [PDF::Core](http://search.cpan.org/perldoc?PDF::Core). | You could try Lucene (the Perl port is called Plucene). The searches are incredibly fast and I know that PDFBox already knows how to index PDF files with Lucene. PDFBox is Java, but chances are there is something very similar somewhere in CPAN. Even if you can't find something that already adds PDF files to a Lucene index it shouldn't be more than a few lines of code to do it yourself. Lucene will give you quite a few more searching options than simply looking for a string in a file.
There's also a very quick and dirty way. Text in a PDF file is actually stored as plain text. If you open a PDF in a text editor or use 'strings' you can see the text in there. The binary junk is usually embedded fonts, images, etc. |
139,015 | I have a bunch of PDF files and my Perl program needs to do a full-text search of them to return which ones contain a specific string.
To date I have been using this:
```
my @search_results = `grep -i -l \"$string\" *.pdf`;
```
where $string is the text to look for.
However this fails for most pdf's because the file format is obviously not ASCII.
What can I do that's easiest?
Clarification:
There are about 300 pdf's whose name I do not know in advance. PDF::Core is probably overkill. I am trying to get pdftotext and grep to play nice with each other given I don't know the names of the pdf's, I can't find the right syntax yet.
Final solution using Adam Bellaire's suggestion below:
```
@search_results = `for i in \$( ls ); do pdftotext \$i - | grep --label="\$i" -i -l "$search_string"; done`;
``` | 2008/09/26 | [
"https://Stackoverflow.com/questions/139015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22654/"
] | I second Adam Bellaire solution. I used pdftotext utility to create full-text index of my ebook library. It's somewhat slow but does its job. As for full-text, try PLucene or KinoSearch to store full-text index. | The easiest fulltext index/seach I've used is mysql. You just insert into the table with the appropriate index on it. You need to spend some time working out the relative weightings for fields (a match in the title might score higher than a match in the body), but this is all possible, albeit with some hairy sql.
Plucene is deprecated (there hasn't been any active work on it in the last two years afaik) in favour of KinoSearch. KinoSearch grew, in part, out of understanding the architectural limitations of Plucene.
If you have ~300 pdfs, then once you've extracted the text from the PDF (assuming the PDF has text and not just images of text ;) and depending on your query volumes you may find grep is sufficient.
However, I'd strongly suggest the mysql/kinosearch route as they have covered a lot of ground (stemming, stopwords, term weighting, token parsing) that you don't benefit from getting bogged down with.
KinoSearch is probably faster than the mysql route, but the mysql route gives you more widely used standard software/tools/developer-experience. And you get the ability to use the power of sql to augement your freetext search queries.
So unless you're talking HUGE data-sets and insane query volumes, my money would be on mysql. |
139,015 | I have a bunch of PDF files and my Perl program needs to do a full-text search of them to return which ones contain a specific string.
To date I have been using this:
```
my @search_results = `grep -i -l \"$string\" *.pdf`;
```
where $string is the text to look for.
However this fails for most pdf's because the file format is obviously not ASCII.
What can I do that's easiest?
Clarification:
There are about 300 pdf's whose name I do not know in advance. PDF::Core is probably overkill. I am trying to get pdftotext and grep to play nice with each other given I don't know the names of the pdf's, I can't find the right syntax yet.
Final solution using Adam Bellaire's suggestion below:
```
@search_results = `for i in \$( ls ); do pdftotext \$i - | grep --label="\$i" -i -l "$search_string"; done`;
``` | 2008/09/26 | [
"https://Stackoverflow.com/questions/139015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22654/"
] | My library, [CAM::PDF](http://search.cpan.org/dist/CAM-PDF/), has support for extracting text, but it's an inherently hard problem given the graphical orientation of PDF syntax. So, the output is sometimes gibberish. CAM::PDF bundles a [getpdftext.pl](http://search.cpan.org/dist/CAM-PDF/bin/getpdftext.pl) program, or you can invoke the functionality like so:
```
my $doc = CAM::PDF->new($filename) || die "$CAM::PDF::errstr\n";
for my $pagenum (1 .. $doc->numPages()) {
my $text = $doc->getPageText($pagenum);
print $text;
}
``` | The easiest fulltext index/seach I've used is mysql. You just insert into the table with the appropriate index on it. You need to spend some time working out the relative weightings for fields (a match in the title might score higher than a match in the body), but this is all possible, albeit with some hairy sql.
Plucene is deprecated (there hasn't been any active work on it in the last two years afaik) in favour of KinoSearch. KinoSearch grew, in part, out of understanding the architectural limitations of Plucene.
If you have ~300 pdfs, then once you've extracted the text from the PDF (assuming the PDF has text and not just images of text ;) and depending on your query volumes you may find grep is sufficient.
However, I'd strongly suggest the mysql/kinosearch route as they have covered a lot of ground (stemming, stopwords, term weighting, token parsing) that you don't benefit from getting bogged down with.
KinoSearch is probably faster than the mysql route, but the mysql route gives you more widely used standard software/tools/developer-experience. And you get the ability to use the power of sql to augement your freetext search queries.
So unless you're talking HUGE data-sets and insane query volumes, my money would be on mysql. |
139,015 | I have a bunch of PDF files and my Perl program needs to do a full-text search of them to return which ones contain a specific string.
To date I have been using this:
```
my @search_results = `grep -i -l \"$string\" *.pdf`;
```
where $string is the text to look for.
However this fails for most pdf's because the file format is obviously not ASCII.
What can I do that's easiest?
Clarification:
There are about 300 pdf's whose name I do not know in advance. PDF::Core is probably overkill. I am trying to get pdftotext and grep to play nice with each other given I don't know the names of the pdf's, I can't find the right syntax yet.
Final solution using Adam Bellaire's suggestion below:
```
@search_results = `for i in \$( ls ); do pdftotext \$i - | grep --label="\$i" -i -l "$search_string"; done`;
``` | 2008/09/26 | [
"https://Stackoverflow.com/questions/139015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22654/"
] | The PerlMonks thread [here](http://www.perlmonks.org/?node_id=582868) talks about this problem.
It seems that for your situation, it might be simplest to get **pdftotext** (the command line tool), then you can do something like:
```
my @search_results = `pdftotext myfile.pdf - | grep -i -l \"$string\"`;
``` | My library, [CAM::PDF](http://search.cpan.org/dist/CAM-PDF/), has support for extracting text, but it's an inherently hard problem given the graphical orientation of PDF syntax. So, the output is sometimes gibberish. CAM::PDF bundles a [getpdftext.pl](http://search.cpan.org/dist/CAM-PDF/bin/getpdftext.pl) program, or you can invoke the functionality like so:
```
my $doc = CAM::PDF->new($filename) || die "$CAM::PDF::errstr\n";
for my $pagenum (1 .. $doc->numPages()) {
my $text = $doc->getPageText($pagenum);
print $text;
}
``` |
139,015 | I have a bunch of PDF files and my Perl program needs to do a full-text search of them to return which ones contain a specific string.
To date I have been using this:
```
my @search_results = `grep -i -l \"$string\" *.pdf`;
```
where $string is the text to look for.
However this fails for most pdf's because the file format is obviously not ASCII.
What can I do that's easiest?
Clarification:
There are about 300 pdf's whose name I do not know in advance. PDF::Core is probably overkill. I am trying to get pdftotext and grep to play nice with each other given I don't know the names of the pdf's, I can't find the right syntax yet.
Final solution using Adam Bellaire's suggestion below:
```
@search_results = `for i in \$( ls ); do pdftotext \$i - | grep --label="\$i" -i -l "$search_string"; done`;
``` | 2008/09/26 | [
"https://Stackoverflow.com/questions/139015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22654/"
] | I second Adam Bellaire solution. I used pdftotext utility to create full-text index of my ebook library. It's somewhat slow but does its job. As for full-text, try PLucene or KinoSearch to store full-text index. | You could try Lucene (the Perl port is called Plucene). The searches are incredibly fast and I know that PDFBox already knows how to index PDF files with Lucene. PDFBox is Java, but chances are there is something very similar somewhere in CPAN. Even if you can't find something that already adds PDF files to a Lucene index it shouldn't be more than a few lines of code to do it yourself. Lucene will give you quite a few more searching options than simply looking for a string in a file.
There's also a very quick and dirty way. Text in a PDF file is actually stored as plain text. If you open a PDF in a text editor or use 'strings' you can see the text in there. The binary junk is usually embedded fonts, images, etc. |
73,886,487 | In Spring Boot 2.7.4, the `WebSecurityConfigurerAdapter`class which contains the `authenticationManagerBean` function is deprecated
What is the alternative? | 2022/09/28 | [
"https://Stackoverflow.com/questions/73886487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14076156/"
] | I found that the alternative is the `getAuthenticationManager` function in the `AuthenticationConfiguration` class
```java
@Bean
protected SecurityFilterChain configure(final HttpSecurity http,
final AuthenticationManagerBuilder auth,
final AuthenticationConfiguration authenticationConfiguration) throws Exception {
// set the authentication provider
auth.authenticationProvider(daoAuthenticationProvider());
// set the authorization and authentication rules
return http
.csrf().disable()
// Make sure that the session is stateless because we are using JWT
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
// Add the JWT filter (my custom filter)
.addFilter(new JwtFilter(authenticationConfiguration.getAuthenticationManager()))
.build();
}
``` | I have been facing the same problem as you these days, the only solution found is this
```
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
```
But this is causing me an exception in testing.
I posted a spring-boot issue on GitHub. Take a look to keep up to date.
<https://github.com/spring-projects/spring-framework/issues/29215>
It could be a bug |
24,756 | The title really asks it all: **When can a pilot disobey ATC commands?**.
Of course, the pilot has the final decision, but when would the pilot really disobey someone in ATC with much more knowledge of planes and other potential hazards near by? | 2016/01/29 | [
"https://aviation.stackexchange.com/questions/24756",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/11428/"
] | A pilot can break any rule in the book for the safety of the flight or those on the ground. Ultimately the safety of the flight rests with the pilot in command of the aircraft and therefore not just the right but the duty to diverge from ATC instructions if the situation warrants. Examples of this might be:
* A cabin depressurization or engine failure requiring an immediate descent
* A change in course or altitude to avoid a collision with an aircraft or terrain
* Passenger illness
* Unlawful interference
* When intercepted by law enforcement or the military
* If complying with an instruction is hazardous, for instance putting the aircraft outside its flight envelope, into a possible collision
* Fuel emergencies
* Mechanical problems
In cases such as these pilots will take immediate action and inform ATC afterwards if they can. | Others have talked about emergencies, which allows a pilot to take any action he sees fit. This is correct, and you could even argue that it's not really disobeying, as in the moment the emergency was declared, all clearances sort of went out the window.
There's one important part missing and that's the option for a pilot to *not* accept a clearance or an amendment. A clearance is not an instruction as much as it's a negotiation, and once established, is more or less valid until both pilot and controller can agree on something different. If they can't agree, by either the pilot saying "unable" for whatever reason, or in the case where radio communication is lost and the pilot didn't actually hear anything, he is expected to carry on as previously cleared. |
24,756 | The title really asks it all: **When can a pilot disobey ATC commands?**.
Of course, the pilot has the final decision, but when would the pilot really disobey someone in ATC with much more knowledge of planes and other potential hazards near by? | 2016/01/29 | [
"https://aviation.stackexchange.com/questions/24756",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/11428/"
] | In case of emergencies, yes. The pilot in command has the final authority and responsibility for safety of the flight and can disobey ATC commands in case of emergencies. The reasons for that and the results will decide the consequences.
From [14 CFR §91.123 Compliance with ATC clearances and instructions](https://www.law.cornell.edu/cfr/text/14/91.123):
>
> (a) When an ATC clearance has been obtained, no pilot in command may deviate from that clearance **unless an amended clearance is obtained, an emergency exists**, or the deviation is in response to a traffic alert and collision avoidance system resolution advisory.
>
>
> (b) **Except in an emergency**, no person may operate an aircraft contrary to an ATC instruction in an area in which air traffic control is exercised.
>
>
>
From [14 CFR §121.557 Emergencies: Domestic and flag operations](http://www.ecfr.gov/cgi-bin/retrieveECFR?gp=&SID=7b2be47d0f0b0f80a9b50b8f55ebb950&r=SECTION&n=14y3.0.1.1.7.20.3.20):
>
> (a) In an emergency situation that requires immediate decision and action the **pilot in command may take any action** that he considers necessary under the circumstances. In such a case he may deviate from prescribed operations procedures and methods, weather minimums, and this chapter, to the extent required in the interests of safety.
>
>
>
Emphasis mine. Obviously, it would be prudent for the the pilot (and required under FAR 91.123(c), as @Pondlife points out) to report the deviation to the ATC as soon as possible. | Others have talked about emergencies, which allows a pilot to take any action he sees fit. This is correct, and you could even argue that it's not really disobeying, as in the moment the emergency was declared, all clearances sort of went out the window.
There's one important part missing and that's the option for a pilot to *not* accept a clearance or an amendment. A clearance is not an instruction as much as it's a negotiation, and once established, is more or less valid until both pilot and controller can agree on something different. If they can't agree, by either the pilot saying "unable" for whatever reason, or in the case where radio communication is lost and the pilot didn't actually hear anything, he is expected to carry on as previously cleared. |
24,756 | The title really asks it all: **When can a pilot disobey ATC commands?**.
Of course, the pilot has the final decision, but when would the pilot really disobey someone in ATC with much more knowledge of planes and other potential hazards near by? | 2016/01/29 | [
"https://aviation.stackexchange.com/questions/24756",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/11428/"
] | To add one more case to what's been mentioned, if ATC tells you to climb to avoid a conflict and TCAS tells you to descend, pilots are required to follow the TCAS command rather than ATC's.
The reason behind this is that TCAS in the two aircraft can typically coordinate "behind the scenes" which aircraft will do what in order to avoid a collision, but there's no guarantee that both aircraft are hearing the same plan from ATC. Maybe separate controllers both issue a "climb" command, or one aircraft is on the wrong frequency, or whatever. But the TCAS-to-TCAS communication is sufficiently reliable that this is now a required (although extremely rare) case of disobeying ATC. | Others have talked about emergencies, which allows a pilot to take any action he sees fit. This is correct, and you could even argue that it's not really disobeying, as in the moment the emergency was declared, all clearances sort of went out the window.
There's one important part missing and that's the option for a pilot to *not* accept a clearance or an amendment. A clearance is not an instruction as much as it's a negotiation, and once established, is more or less valid until both pilot and controller can agree on something different. If they can't agree, by either the pilot saying "unable" for whatever reason, or in the case where radio communication is lost and the pilot didn't actually hear anything, he is expected to carry on as previously cleared. |
32,937,943 | I have a points table, where important columns are:
```
id userid orderid
1 10 150
2 10 150
3 15 151
4 12 152
5 11 152
```
I need to find all `orderid` which have multiple/various `userid`. The result would be:
```
id userid orderid
4 12 152
5 11 152
```
I can do it in PHP, but I hope someone have time to help me with mysql query. What I have tried so far is probably irrelevant. | 2015/10/04 | [
"https://Stackoverflow.com/questions/32937943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1386703/"
] | I had the same problem, I don't think that this is possible at the moment.
My solution was to generate a NuGet package with the target dll.
You will need to install NuGet command line and then:
```
nuget spec YourNameOrCompany.PackageName
```
This will generate a YourNameOrCompany.PackageName.nuspec, open the file and change as follow:
```
<?xml version="1.0"?>
<package >
<metadata>
<id>YourNameOrCompany.PackageName</id>
<version>1.0.0</version>
<authors>Your Name</authors>
<owners>Your Company</owners>
<licenseUrl>https://en.wikipedia.org/wiki/MIT_License</licenseUrl>
<projectUrl>http://www.yourporject.url</projectUrl>
<iconUrl>http://www.urltoyourimage.com</iconUrl>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>Package to expose DLL</description>
<copyright>Copyright 2016</copyright>
<tags>DLL</tags>
<dependencies>
</dependencies>
</metadata>
<files>
<file src="path/to/you/file.dll" target="lib"></file>
</files>
</package>
```
Save the file and run:
```
nuget pack YourNameOrCompany.PackageName.nuspec
```
You will probably get a warning message about the target of your file, but that fine.
Now you need to publish the generated .nupkg file on NuGet Gallery, just register and follow the instructions on the website.
Once you finish publishing, go to your project folder and type:
```
dnu install YourNameOrCompany.PackageName
```
This will add the reference to your pkg and you will be able to reference it on your project and get the Intellisense.
I hope that helps.
cheers | Try to use Nuget package as **@Mush** answered.
But thats not always work, because .NET Framework and .NET Core are incompatible.
In that case you will get error message:
`Package DLLNAME is not compatible with netcoreapp1.1`
Which means the package does not support netcoreapp1.1 instead it supports .NET Framework (such as .NET Framework 4.5) |
54,251,200 | Is it possible to use parallelism in Entity Framework's `DbContext`? Basically I have an application that adds thousands of records for each of the 4 tables that I have. And I am thinking that the best way to optimize it is to have the adding of records done in parallel.
```
public void Transact()
{
var context = new DbContext();
_fooList = new List<Foo>
{
//… Assume that this list contains thousands of objects
}
context.Set<Foo>().AddRange(_fooList);
var context1 = new DbContext();
_barList = new List<Bar>
{
//… Assume that this list contains thousands of objects
}
context1.Set<Bar>().AddRange(_barList);
context.SaveChanges();
context1.SaveChanges();
}
``` | 2019/01/18 | [
"https://Stackoverflow.com/questions/54251200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6435817/"
] | Verbatim content is tricky. You have to ask yourself what the intent is. If it's printing code, then king of the hill would be [`listings`](//ctan.org/pkg/listings). I'd suggest that and define your own environment for large chunks of code-specific output.
Here's an example:
[](https://i.stack.imgur.com/M1uer.png)
```
\documentclass{article}
\usepackage{listings}
\lstnewenvironment{code}[1][]
{\lstset{#1}}% Add/update settings locally
{}
\lstset{% Global options
frame = single,
basicstyle = \ttfamily\small,
language = PHP
}
\begin{document}
My first PHP ``Hello World'' page:
\begin{code}
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php echo '<p>Hello World</p>'; ?>
</body>
</html>
\end{code}
When you write \lstinline!<title>PHP Test</test>!, it sets the \textit{title} of the page.
\end{document}
``` | Found a workaround for `verbatim` with `\verb` command, and using tilde as delimiter (if I want to use tilde inside the script I have to use `\textasciitilde`):
```
\documentclass{article}
\newcommand{\scr}[1]{
\begin{minipage}{0.9\textwidth}
\fbox{
\parbox{\textwidth}{
\verb~#1~ % <-- HERE
}
}
\end{minipage}
}
\begin{document}
\scr{Some script code here...
here a tilde : \textasciitilde
}
\end{document}
```
But nothing for `listings`...
---
EDIT :
I've just noticed that this workaround doesn't keep the "automatic" character escaping, so it's not what I was looking for. I'd like to be able to paste code without escaping special chars. |
45,612,366 | I have an `EMP` table in SQL Server that looks something like this
```
ID T_Date Jid Emp_Cost Con_Cost IsActive
--------------------------------------------------------
13178 null 214 0 0 0
12797 null 214 0 55 1
11906 null 214 0 55 1
12916 null 214 0 58 1
```
I am executing the below query
```
SELECT
AVG(CASE WHEN IsActive = 1 THEN Con_Cost ELSE Emp_Cost END) cost
FROM
EMP
WHERE
Jid = 214
AND (T_Date IS NULL OR T_Date >= sysdate);
```
My expected cost value must be 56.
Can anybody help me with this?
Arun | 2017/08/10 | [
"https://Stackoverflow.com/questions/45612366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1341159/"
] | It's not getting pushed an infinite number of times. It's a matter of how Firefox Developer Console **presents** the element. Expanding the array and clicking on it again, under itself, will always show you how the array looks like. So you can expand it and click it an infinite number of times, but still, it's there **only once**. | Because the javascript gives the reference to the 'a' variable, and not the actual object, so if you push the a to itself, you push the memory address what hold the object, and it creates a circular reference.
[1, 2, *reference to this object*] |
45,612,366 | I have an `EMP` table in SQL Server that looks something like this
```
ID T_Date Jid Emp_Cost Con_Cost IsActive
--------------------------------------------------------
13178 null 214 0 0 0
12797 null 214 0 55 1
11906 null 214 0 55 1
12916 null 214 0 58 1
```
I am executing the below query
```
SELECT
AVG(CASE WHEN IsActive = 1 THEN Con_Cost ELSE Emp_Cost END) cost
FROM
EMP
WHERE
Jid = 214
AND (T_Date IS NULL OR T_Date >= sysdate);
```
My expected cost value must be 56.
Can anybody help me with this?
Arun | 2017/08/10 | [
"https://Stackoverflow.com/questions/45612366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1341159/"
] | It is just pushed once. While the array is referencing itself ([circular refernce](https://en.wikipedia.org/wiki/Circular_reference)), you see more than one inserted arrays. The display is dependent of the browser.
If you try to get a [JSON](http://json.org/) string, then [`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) breaks with an error
>
>
> ```
> Circular reference in value argument not supported
>
> ```
>
>
```js
var a = [1, 2]
console.log(a);
a.push(a);
console.log(a);
JSON.stringify(a);
```
```css
.as-console-wrapper { max-height: 100% !important; top: 0; }
``` | Because the javascript gives the reference to the 'a' variable, and not the actual object, so if you push the a to itself, you push the memory address what hold the object, and it creates a circular reference.
[1, 2, *reference to this object*] |
45,612,366 | I have an `EMP` table in SQL Server that looks something like this
```
ID T_Date Jid Emp_Cost Con_Cost IsActive
--------------------------------------------------------
13178 null 214 0 0 0
12797 null 214 0 55 1
11906 null 214 0 55 1
12916 null 214 0 58 1
```
I am executing the below query
```
SELECT
AVG(CASE WHEN IsActive = 1 THEN Con_Cost ELSE Emp_Cost END) cost
FROM
EMP
WHERE
Jid = 214
AND (T_Date IS NULL OR T_Date >= sysdate);
```
My expected cost value must be 56.
Can anybody help me with this?
Arun | 2017/08/10 | [
"https://Stackoverflow.com/questions/45612366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1341159/"
] | You've created a circular reference.
When you push the array onto itself, the last element in the array becomes a reference to the entire array -- including that last element. So the last element in that last element is also a reference to the entire array, and so on.
It's infinite in the same sense that a circle is infinite, and "appends more than once" only in the same sense that if you go around a circle more than once you'll hit the same spot more than once. | Because the javascript gives the reference to the 'a' variable, and not the actual object, so if you push the a to itself, you push the memory address what hold the object, and it creates a circular reference.
[1, 2, *reference to this object*] |
45,612,366 | I have an `EMP` table in SQL Server that looks something like this
```
ID T_Date Jid Emp_Cost Con_Cost IsActive
--------------------------------------------------------
13178 null 214 0 0 0
12797 null 214 0 55 1
11906 null 214 0 55 1
12916 null 214 0 58 1
```
I am executing the below query
```
SELECT
AVG(CASE WHEN IsActive = 1 THEN Con_Cost ELSE Emp_Cost END) cost
FROM
EMP
WHERE
Jid = 214
AND (T_Date IS NULL OR T_Date >= sysdate);
```
My expected cost value must be 56.
Can anybody help me with this?
Arun | 2017/08/10 | [
"https://Stackoverflow.com/questions/45612366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1341159/"
] | It's not getting pushed an infinite number of times. It's a matter of how Firefox Developer Console **presents** the element. Expanding the array and clicking on it again, under itself, will always show you how the array looks like. So you can expand it and click it an infinite number of times, but still, it's there **only once**. | It is actually pushing it only one time. It doesn't push the array elements, but the address of the array. Firefox console just tries to show what's in there, but ends up showing the same thing infinitely.
Not just Firefox, Chrome also does that. |
45,612,366 | I have an `EMP` table in SQL Server that looks something like this
```
ID T_Date Jid Emp_Cost Con_Cost IsActive
--------------------------------------------------------
13178 null 214 0 0 0
12797 null 214 0 55 1
11906 null 214 0 55 1
12916 null 214 0 58 1
```
I am executing the below query
```
SELECT
AVG(CASE WHEN IsActive = 1 THEN Con_Cost ELSE Emp_Cost END) cost
FROM
EMP
WHERE
Jid = 214
AND (T_Date IS NULL OR T_Date >= sysdate);
```
My expected cost value must be 56.
Can anybody help me with this?
Arun | 2017/08/10 | [
"https://Stackoverflow.com/questions/45612366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1341159/"
] | It is just pushed once. While the array is referencing itself ([circular refernce](https://en.wikipedia.org/wiki/Circular_reference)), you see more than one inserted arrays. The display is dependent of the browser.
If you try to get a [JSON](http://json.org/) string, then [`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) breaks with an error
>
>
> ```
> Circular reference in value argument not supported
>
> ```
>
>
```js
var a = [1, 2]
console.log(a);
a.push(a);
console.log(a);
JSON.stringify(a);
```
```css
.as-console-wrapper { max-height: 100% !important; top: 0; }
``` | It is actually pushing it only one time. It doesn't push the array elements, but the address of the array. Firefox console just tries to show what's in there, but ends up showing the same thing infinitely.
Not just Firefox, Chrome also does that. |
45,612,366 | I have an `EMP` table in SQL Server that looks something like this
```
ID T_Date Jid Emp_Cost Con_Cost IsActive
--------------------------------------------------------
13178 null 214 0 0 0
12797 null 214 0 55 1
11906 null 214 0 55 1
12916 null 214 0 58 1
```
I am executing the below query
```
SELECT
AVG(CASE WHEN IsActive = 1 THEN Con_Cost ELSE Emp_Cost END) cost
FROM
EMP
WHERE
Jid = 214
AND (T_Date IS NULL OR T_Date >= sysdate);
```
My expected cost value must be 56.
Can anybody help me with this?
Arun | 2017/08/10 | [
"https://Stackoverflow.com/questions/45612366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1341159/"
] | You've created a circular reference.
When you push the array onto itself, the last element in the array becomes a reference to the entire array -- including that last element. So the last element in that last element is also a reference to the entire array, and so on.
It's infinite in the same sense that a circle is infinite, and "appends more than once" only in the same sense that if you go around a circle more than once you'll hit the same spot more than once. | It is actually pushing it only one time. It doesn't push the array elements, but the address of the array. Firefox console just tries to show what's in there, but ends up showing the same thing infinitely.
Not just Firefox, Chrome also does that. |
45,612,366 | I have an `EMP` table in SQL Server that looks something like this
```
ID T_Date Jid Emp_Cost Con_Cost IsActive
--------------------------------------------------------
13178 null 214 0 0 0
12797 null 214 0 55 1
11906 null 214 0 55 1
12916 null 214 0 58 1
```
I am executing the below query
```
SELECT
AVG(CASE WHEN IsActive = 1 THEN Con_Cost ELSE Emp_Cost END) cost
FROM
EMP
WHERE
Jid = 214
AND (T_Date IS NULL OR T_Date >= sysdate);
```
My expected cost value must be 56.
Can anybody help me with this?
Arun | 2017/08/10 | [
"https://Stackoverflow.com/questions/45612366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1341159/"
] | It is just pushed once. While the array is referencing itself ([circular refernce](https://en.wikipedia.org/wiki/Circular_reference)), you see more than one inserted arrays. The display is dependent of the browser.
If you try to get a [JSON](http://json.org/) string, then [`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) breaks with an error
>
>
> ```
> Circular reference in value argument not supported
>
> ```
>
>
```js
var a = [1, 2]
console.log(a);
a.push(a);
console.log(a);
JSON.stringify(a);
```
```css
.as-console-wrapper { max-height: 100% !important; top: 0; }
``` | It's not getting pushed an infinite number of times. It's a matter of how Firefox Developer Console **presents** the element. Expanding the array and clicking on it again, under itself, will always show you how the array looks like. So you can expand it and click it an infinite number of times, but still, it's there **only once**. |
45,612,366 | I have an `EMP` table in SQL Server that looks something like this
```
ID T_Date Jid Emp_Cost Con_Cost IsActive
--------------------------------------------------------
13178 null 214 0 0 0
12797 null 214 0 55 1
11906 null 214 0 55 1
12916 null 214 0 58 1
```
I am executing the below query
```
SELECT
AVG(CASE WHEN IsActive = 1 THEN Con_Cost ELSE Emp_Cost END) cost
FROM
EMP
WHERE
Jid = 214
AND (T_Date IS NULL OR T_Date >= sysdate);
```
My expected cost value must be 56.
Can anybody help me with this?
Arun | 2017/08/10 | [
"https://Stackoverflow.com/questions/45612366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1341159/"
] | It is just pushed once. While the array is referencing itself ([circular refernce](https://en.wikipedia.org/wiki/Circular_reference)), you see more than one inserted arrays. The display is dependent of the browser.
If you try to get a [JSON](http://json.org/) string, then [`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) breaks with an error
>
>
> ```
> Circular reference in value argument not supported
>
> ```
>
>
```js
var a = [1, 2]
console.log(a);
a.push(a);
console.log(a);
JSON.stringify(a);
```
```css
.as-console-wrapper { max-height: 100% !important; top: 0; }
``` | You've created a circular reference.
When you push the array onto itself, the last element in the array becomes a reference to the entire array -- including that last element. So the last element in that last element is also a reference to the entire array, and so on.
It's infinite in the same sense that a circle is infinite, and "appends more than once" only in the same sense that if you go around a circle more than once you'll hit the same spot more than once. |
13,796,160 | I have a form with a table.
```
<form >
<div>
<table>
<tr>
<td > <input type="text" id="slno1" size="25" value="10" /> </td>
<td > <input type="text" id="data" size="10" value="this is a test" /> </td>
<td > <input type="radio" value="" id="edit1" name="sample" /> </td>
</tr>
<tr>
<td > <input type="text" id="slno2" size="25" value="10" /> </td>
<td > <input type="text" id="data1" size="10" value="this is a test1" /> </td>
<td > <input type="radio" value="" id="edit1" name="sample" /> </td>
</tr>
</table>
<input type="submit" id="mysu1" Value="submits" />
</div>
</form>
```
in that when a user selects a row with a radio button I want all the data on that row.
so, we do :
```
var theSelectedRadioButton = theForm.find('input[name="sample"]:checked');
```
how can I get all the corresponding values in td's. | 2012/12/10 | [
"https://Stackoverflow.com/questions/13796160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1530845/"
] | With JS you can get the position of the topmost window with `top.screenLeft` and `top.screenTop`. | Here's a cool way to do it. It's sorta animated
VBScript
Add this to global variables
```
Dim IntervalMovingWindow
```
then add this OnLoad routine
```
Sub Window_OnLoad
moveTo screen.availWidth/2-200 , screen.availHeight/2-100
IntervalMovingWindow= Setinterval ("MoveTheWindow",100)
End Sub
```
Then Add this Routine for moving windows (animated style)
```
Sub MoveTheWindow
Dim X,Y
X=top.screenleft
Y=top.screentop
If X<=60 Then
X=0
End If
If Y<=60 Then
Y=0
End If
If X<>0 Then
moveBy -20,0
End If
If Y<>0 Then
moveBy 0,-20
End If
If X=0 And Y=0 Then
moveto 0,0
clearInterval IntervalMovingWindow
End If
End Sub
```
This may not work if you have an excessively large border. in that case you may need to change `-20` in the `moveBy` to a larger negative number like `-30` and the `If {X or Y}=60` into a larger positive number like `If {X or Y}=80`
NOTE don't include the Braces '{}' they just mean that i am talking about both X and the Y conditionals. |
45,969,124 | I would like to convert windows .iso to .qcow2 format and use in openstack.
Tried using vbox:
<https://www.virtualbox.org/>
Not sure how to add cloud-init package to the OS, configure grub (steps 11&12)
Also tried using qemu-img commands in windows using ref <https://cloudbase.it/qemu-img-windows/>
able to convert image to .qcow2 format but when i upload image to openstack and launch instance. It got stuck at booting. | 2017/08/30 | [
"https://Stackoverflow.com/questions/45969124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8539472/"
] | ```
brew/apt install qemu
qemu-img convert xxx.iso xxx.qcow2
``` | I think you have to install it first before converting it, try to install it on virtualbox and then convert virtualbox image to qcow2.
Hope it will help |
45,969,124 | I would like to convert windows .iso to .qcow2 format and use in openstack.
Tried using vbox:
<https://www.virtualbox.org/>
Not sure how to add cloud-init package to the OS, configure grub (steps 11&12)
Also tried using qemu-img commands in windows using ref <https://cloudbase.it/qemu-img-windows/>
able to convert image to .qcow2 format but when i upload image to openstack and launch instance. It got stuck at booting. | 2017/08/30 | [
"https://Stackoverflow.com/questions/45969124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8539472/"
] | ```
brew/apt install qemu
qemu-img convert xxx.iso xxx.qcow2
``` | ```
qemu-img convert -O qcow2 virtio-win.iso virtio-win.qcow2
``` |
379,093 | Consider the case described below, from Peacock (1972). This passage seems to imply the young statistician is making a smart, correct statement.
But is he?
[](https://i.stack.imgur.com/53Ms6.jpg) | 2018/11/27 | [
"https://stats.stackexchange.com/questions/379093",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/-1/"
] | As the statistician did not make any statements, he cannot be wrong. He just asked two questions: 1) Did you have controls? and 2) Which half?
The surgeon is clearly wrong, unless a) Every patient he treated survived and b) No patient who was not treated would survive (or, of course, vice versa).
Both the surgeon and the statistician are making good points. | This sounds a lot like that story about one of the sons in the fourth generation of the Pearson family, the one that became a paramedic. He used to not help half of his patients with a cardiac arrest in order to test whether helping or not helping was significantly helpful in order to get the heart beating again.
A grand child of Joan Fisher and Joerge Box is currently doing a project for the final exam as air traffic controller. He is testing on half the pilot whether they will fly better and crash less often if he is not speaking to them.
Do you think they are right to do so? |
379,093 | Consider the case described below, from Peacock (1972). This passage seems to imply the young statistician is making a smart, correct statement.
But is he?
[](https://i.stack.imgur.com/53Ms6.jpg) | 2018/11/27 | [
"https://stats.stackexchange.com/questions/379093",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/-1/"
] | As the statistician did not make any statements, he cannot be wrong. He just asked two questions: 1) Did you have controls? and 2) Which half?
The surgeon is clearly wrong, unless a) Every patient he treated survived and b) No patient who was not treated would survive (or, of course, vice versa).
Both the surgeon and the statistician are making good points. | The statistician sounds like a frequentist, and he's correct if we view things in terms of measures of evidence. In particular, at this point we have no direct evidence in regards to the effectiveness of the surgeon's effectiveness.
Maybe surprising to most statisticians, the surgeon is taking more of a Bayesian perspective. That is, because of his advanced knowledge of medicine, he is very strongly convinced that his procedures are helping his patients. He's human, so he must realize that he does know *exactly* how effective his treatments are, but he also is so confident that it's positive that the long-term benefit is better for him to treat every patient than it is to collect controls, who will with very high probability be worse off than if they were treated only to collect data that confirms what he already knows. So while collecting data on controls may be informative, it is dangerous to the controls and not likely to make any differences in future decisions. Therefore, it is quite logical for him to not use controls.
Who's correct? Well, the statistician is certainly correct that we don't have any data that demonstrates that the surgeon's methods are effective.
But the lack of evidence doesn't mean the surgeon is wrong! **Assuming the surgeon is not over-confident**, the surgeon is also correct that collecting data on controls is not the ethical thing to do. What it all comes down to is: do you trust the surgeon's confidence? |
379,093 | Consider the case described below, from Peacock (1972). This passage seems to imply the young statistician is making a smart, correct statement.
But is he?
[](https://i.stack.imgur.com/53Ms6.jpg) | 2018/11/27 | [
"https://stats.stackexchange.com/questions/379093",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/-1/"
] | As the statistician did not make any statements, he cannot be wrong. He just asked two questions: 1) Did you have controls? and 2) Which half?
The surgeon is clearly wrong, unless a) Every patient he treated survived and b) No patient who was not treated would survive (or, of course, vice versa).
Both the surgeon and the statistician are making good points. | The surgeon is right.
The people who suffered or died because they did not get this operation serve as a control group. It would be better to formalize this and quantify the improved performance (e.g. 70% mortality rate vs 10%), but we do have a group to which we can compare.
Now...if the surgeon is claiming that his treatment saved lives, yet the patients tended to do just fine without the procedure, then the success of the treatment is not so remarkable. However, quite the opposite is implied.
The "which half" line is wrong. Nothing suggests that the surgeon's procedure causes death. Perhaps it doesn't help compared to a control group, but it certainly sounds like most patients survive. Operating on a patient certainly doesn't suggest that they are doomed to die in the OR. |
379,093 | Consider the case described below, from Peacock (1972). This passage seems to imply the young statistician is making a smart, correct statement.
But is he?
[](https://i.stack.imgur.com/53Ms6.jpg) | 2018/11/27 | [
"https://stats.stackexchange.com/questions/379093",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/-1/"
] | This sounds a lot like that story about one of the sons in the fourth generation of the Pearson family, the one that became a paramedic. He used to not help half of his patients with a cardiac arrest in order to test whether helping or not helping was significantly helpful in order to get the heart beating again.
A grand child of Joan Fisher and Joerge Box is currently doing a project for the final exam as air traffic controller. He is testing on half the pilot whether they will fly better and crash less often if he is not speaking to them.
Do you think they are right to do so? | The surgeon is right.
The people who suffered or died because they did not get this operation serve as a control group. It would be better to formalize this and quantify the improved performance (e.g. 70% mortality rate vs 10%), but we do have a group to which we can compare.
Now...if the surgeon is claiming that his treatment saved lives, yet the patients tended to do just fine without the procedure, then the success of the treatment is not so remarkable. However, quite the opposite is implied.
The "which half" line is wrong. Nothing suggests that the surgeon's procedure causes death. Perhaps it doesn't help compared to a control group, but it certainly sounds like most patients survive. Operating on a patient certainly doesn't suggest that they are doomed to die in the OR. |
379,093 | Consider the case described below, from Peacock (1972). This passage seems to imply the young statistician is making a smart, correct statement.
But is he?
[](https://i.stack.imgur.com/53Ms6.jpg) | 2018/11/27 | [
"https://stats.stackexchange.com/questions/379093",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/-1/"
] | The statistician sounds like a frequentist, and he's correct if we view things in terms of measures of evidence. In particular, at this point we have no direct evidence in regards to the effectiveness of the surgeon's effectiveness.
Maybe surprising to most statisticians, the surgeon is taking more of a Bayesian perspective. That is, because of his advanced knowledge of medicine, he is very strongly convinced that his procedures are helping his patients. He's human, so he must realize that he does know *exactly* how effective his treatments are, but he also is so confident that it's positive that the long-term benefit is better for him to treat every patient than it is to collect controls, who will with very high probability be worse off than if they were treated only to collect data that confirms what he already knows. So while collecting data on controls may be informative, it is dangerous to the controls and not likely to make any differences in future decisions. Therefore, it is quite logical for him to not use controls.
Who's correct? Well, the statistician is certainly correct that we don't have any data that demonstrates that the surgeon's methods are effective.
But the lack of evidence doesn't mean the surgeon is wrong! **Assuming the surgeon is not over-confident**, the surgeon is also correct that collecting data on controls is not the ethical thing to do. What it all comes down to is: do you trust the surgeon's confidence? | The surgeon is right.
The people who suffered or died because they did not get this operation serve as a control group. It would be better to formalize this and quantify the improved performance (e.g. 70% mortality rate vs 10%), but we do have a group to which we can compare.
Now...if the surgeon is claiming that his treatment saved lives, yet the patients tended to do just fine without the procedure, then the success of the treatment is not so remarkable. However, quite the opposite is implied.
The "which half" line is wrong. Nothing suggests that the surgeon's procedure causes death. Perhaps it doesn't help compared to a control group, but it certainly sounds like most patients survive. Operating on a patient certainly doesn't suggest that they are doomed to die in the OR. |
20,223,188 | I am working on creating a very simple content management system... Unfortunately I'm failing to retrieve posts from my database. My error is:
>
> Notice: Undefined index: title in C:\wamp\www\NightOwlSoftware\index.php
>
>
>
```
<?php
include 'scripts/db_connect.php';
include 'scripts/functions.php';
sec_session_start();
$sql = "SELECT * FROM blog";
$result = mysqli_query($mysqli, $sql);
while($row = mysqli_fetch_array($result)) {
echo'<div class="blog"><h3 class="blog">' . $row['title'] . "</h3>";
echo'<span class="blog"> Date: ' . $row['date'] . " Tag: " . $row['tag'] . "</span><hr>";
echo'<p class="blog">' . $row['body'] . "</p>";
}
?>
```
Here is the working script that stores data proving that my columns are all there...
```
<?php
include 'db_connect.php';
include 'functions.php';
sec_session_start();
$title = $_POST['title'];
$body = $_POST['body'];
$tag = $_POST['tag'];
$date = date_create()->format('Y-m-d H:i:s');
$sql = "INSERT INTO blog (date, title, body, tag)
VALUES ('$date', '$title', '$body', '$tag')";
mysqli_query($mysqli, $sql);
mysqli_close($mysqli);
header( 'Location: ../index.php' ) ;
?>
``` | 2013/11/26 | [
"https://Stackoverflow.com/questions/20223188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2610750/"
] | If that's the only error you're getting (ie. date, tag, body all work fine), then you probably mis-typed something in the database creation, and don't actually have a `title` column as a result. Or maybe the column has a different name, like `name`, `subject` or `im_so_bored_i_dont_know_what_im_typing`... (sorry, I'm bored!) | You are getting an undefined index for `title` because there is no `title` in the array `$row`.
I would recommend you look over your DB structure for the table `blog` but I would also recommend doing some basic data checks in your `while` to ensure you render only the content that exists. Look this over:
```
<?php
include 'scripts/db_connect.php';
include 'scripts/functions.php';
sec_session_start();
$sql = "SELECT * FROM blog";
$result = mysqli_query($mysqli, $sql);
while($row = mysqli_fetch_array($result)) {
if (array_key_exists('title', $row) && !empty($row['title'])) {
echo'<div class="blog"><h3 class="blog">' . $row['title'] . "</h3>";
}
if (array_key_exists('date', $row) && !empty($row['date'])) {
echo '<span class="blog"> Date: ' . $row['date'];
}
if (array_key_exists('tag', $row) && !empty($row['tag'])) {
echo " Tag: " . $row['tag'] . "</span><hr>";
}
if (array_key_exists('body', $row) && !empty($row['body'])) {
echo'<p class="blog">' . $row['body'] . "</p>";
}
}
?>
```
If this all runs & nothing renders, then your DB query is flawed, so data is not returned. A simple way to check this before the `while` loop is to dump the array to the screen to see what is there:
```
<?php
include 'scripts/db_connect.php';
include 'scripts/functions.php';
sec_session_start();
$sql = "SELECT * FROM blog";
$result = mysqli_query($mysqli, $sql);
while($row = mysqli_fetch_array($result)) {
echo '<pre>';
print_r($row);
echo '</pre>';
[ rest of your code goes here]
``` |
20,223,188 | I am working on creating a very simple content management system... Unfortunately I'm failing to retrieve posts from my database. My error is:
>
> Notice: Undefined index: title in C:\wamp\www\NightOwlSoftware\index.php
>
>
>
```
<?php
include 'scripts/db_connect.php';
include 'scripts/functions.php';
sec_session_start();
$sql = "SELECT * FROM blog";
$result = mysqli_query($mysqli, $sql);
while($row = mysqli_fetch_array($result)) {
echo'<div class="blog"><h3 class="blog">' . $row['title'] . "</h3>";
echo'<span class="blog"> Date: ' . $row['date'] . " Tag: " . $row['tag'] . "</span><hr>";
echo'<p class="blog">' . $row['body'] . "</p>";
}
?>
```
Here is the working script that stores data proving that my columns are all there...
```
<?php
include 'db_connect.php';
include 'functions.php';
sec_session_start();
$title = $_POST['title'];
$body = $_POST['body'];
$tag = $_POST['tag'];
$date = date_create()->format('Y-m-d H:i:s');
$sql = "INSERT INTO blog (date, title, body, tag)
VALUES ('$date', '$title', '$body', '$tag')";
mysqli_query($mysqli, $sql);
mysqli_close($mysqli);
header( 'Location: ../index.php' ) ;
?>
``` | 2013/11/26 | [
"https://Stackoverflow.com/questions/20223188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2610750/"
] | If that's the only error you're getting (ie. date, tag, body all work fine), then you probably mis-typed something in the database creation, and don't actually have a `title` column as a result. Or maybe the column has a different name, like `name`, `subject` or `im_so_bored_i_dont_know_what_im_typing`... (sorry, I'm bored!) | If I could, I would've added this as a comment because this is not really an answer. I agree with other, that most likely - the column name in DB does not match what you have in the code.
In any case, when I am in situations like this, you could use debugger or use print\_r.
In your while loop, add the print\_r statement -
```
while($row = mysqli_fetch_array($result)) {
print_r($row);
echo'<div class="blog"><h3 class="blog">' . $row['title'] . "</h3>";
echo'<span class="blog"> Date: ' . $row['date'] . " Tag: " . $row['tag'] . "</span><hr>";
echo'<p class="blog">' . $row['body'] . "</p>";
}
``` |
485,948 | Does it make sense that entropy goes to infinity as temperature goes to infinity?
For an ideal monoatomic 1D gas I have an expression for entropy
\begin{equation}
S=Nk\_{B}Ln(\frac{Ve^{\frac{5}{2}}\sqrt{2\pi m k\_{B}T}}{N h})
\end{equation}
Where $N$ is the number of particles, $h$ the Planck's constant. $V$ the volume of the box, $e$ Euler's number, $m$ the mass of each particle.
This expression tends to infinity when temperature goes to infinity... why does this have sense? I was used to finding asymptotic behaviours for entropy as a function of temperature, so this result is confusing me | 2019/06/13 | [
"https://physics.stackexchange.com/questions/485948",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/186136/"
] | You may get answers based on statistical mechanics that are more helpful in resolving your confusion (higher temperature means a steadily increasing number of accessible states), but let me just mention a couple of relations from classical thermodynamics.
Firstly, for the ideal gas, the heat capacity at constant volume $C\_V$ is just a constant ($3R/2$ for a monatomic gas in 3D, for instance). It follows, if you integrate with respect to temperature at constant volume, that the internal energy $U$ is proportional to temperature. So, if $T\rightarrow\infty$, then $U\rightarrow\infty$. Is this something to worry about? I don't see why.
But also, it is an identity that
$$
C\_V = T \left( \frac{\partial S}{\partial T}\right)\_V
$$
So to get the entropy difference of an ideal gas for two different temperatures, at the same volume, just integrate $C\_V/T$ with respect to $T$. Since $C\_V$ is constant, this just gives $C\_V(\ln T\_2 - \ln T\_1)$. This seems to be what you are concerned about. Some people worry about the limit $T\rightarrow 0$, and the answer (given elsewhere on Physics SE) is that the ideal gas model is simply inapplicable in this limit. At extremely high temperatures, one will start to see the model become inapplicable as well (e.g. relativistic effects). But over its range of applicability, which is quite wide for low density gases, there is nothing intrinsically unphysical about the logarithmic increase in entropy with temperature. | >
> Does it make sense that entropy goes to infinity as temperature goes to infinity?
>
>
>
At constant volume it makes sense for the entropy to increase with temperature since, at constant volume:
$$
dS = \frac{dU}{T}
$$
and $T$ is positive and we expect $U$ to increase with increasing $T$. However, this does *not* mean the entropy goes to infinity.
The exact details of how the entropy increases and whether it increases to infinity or just increases asymptotically to some limit will depends on the details of the system under study.
However, for many "normal" systems one might expect the entropy to increase to infinity. Roughly, one could argue that this is true because the Hamiltonian is bounded below but not above for "most" systems. That is, we expect there is some lowest energy "ground state" but no "highest energy state." Because there is no highest energy state, there is no limit to how many more states are readily accessible as the energy increases and no necessary limit to the entropy.
To put this into more concrete terms, what we really want to know is how the entropy changes with temperature at constant volume... but this can be written in terms of how the energy changes at constant volume $C\_V$ as:
$$
\left(\frac{\partial S}{\partial T}\right)\_V = \frac{1}{T}\left(\frac{\partial U}{\partial T}\right)\_V = \frac{C\_V}{T}\;.
$$
In general, $C\_V$ can depend on temperature, but for some systems (like the "ideal gas") $C\_V$ is independent of temperature. In the "ideal gas" case, the entropy increases as the log of the temperature (as shown in the other answer).
So, it does seem to make sense that the entropy can go to infinity as the temperature goes to infinity, but it is not *necessarily* the case for all systems.
In fact, we know of simple examples where the entropy *does not* go to infinity at infinite temperature. One example of this is the so-called "two-state" system (See: <http://home.thep.lu.se/~larsg/Site/SM2.pdf>).
For the "two-state" system the entropy continues to increase as the temperature approaches infinity, but it does not increase to inifinity. Rather, the entropy approaches approaches a maximum entropy of $S=Nk\ln(2)$ asymptotically. But, as indicated at in the above discussion, this is due to the single particle Hamiltonian being bounded both above and below for this example. |
485,948 | Does it make sense that entropy goes to infinity as temperature goes to infinity?
For an ideal monoatomic 1D gas I have an expression for entropy
\begin{equation}
S=Nk\_{B}Ln(\frac{Ve^{\frac{5}{2}}\sqrt{2\pi m k\_{B}T}}{N h})
\end{equation}
Where $N$ is the number of particles, $h$ the Planck's constant. $V$ the volume of the box, $e$ Euler's number, $m$ the mass of each particle.
This expression tends to infinity when temperature goes to infinity... why does this have sense? I was used to finding asymptotic behaviours for entropy as a function of temperature, so this result is confusing me | 2019/06/13 | [
"https://physics.stackexchange.com/questions/485948",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/186136/"
] | You may get answers based on statistical mechanics that are more helpful in resolving your confusion (higher temperature means a steadily increasing number of accessible states), but let me just mention a couple of relations from classical thermodynamics.
Firstly, for the ideal gas, the heat capacity at constant volume $C\_V$ is just a constant ($3R/2$ for a monatomic gas in 3D, for instance). It follows, if you integrate with respect to temperature at constant volume, that the internal energy $U$ is proportional to temperature. So, if $T\rightarrow\infty$, then $U\rightarrow\infty$. Is this something to worry about? I don't see why.
But also, it is an identity that
$$
C\_V = T \left( \frac{\partial S}{\partial T}\right)\_V
$$
So to get the entropy difference of an ideal gas for two different temperatures, at the same volume, just integrate $C\_V/T$ with respect to $T$. Since $C\_V$ is constant, this just gives $C\_V(\ln T\_2 - \ln T\_1)$. This seems to be what you are concerned about. Some people worry about the limit $T\rightarrow 0$, and the answer (given elsewhere on Physics SE) is that the ideal gas model is simply inapplicable in this limit. At extremely high temperatures, one will start to see the model become inapplicable as well (e.g. relativistic effects). But over its range of applicability, which is quite wide for low density gases, there is nothing intrinsically unphysical about the logarithmic increase in entropy with temperature. | It's because kinetic energy, unlike most other forms of energy, is unbounded from above. It can increase without limit. This implies that the heat capacity need not fall to zero as the temperature goes up, and this is confirmed when we look at phase space and the available momentum states. There are more and more states available at any given energy as the energy increases. |
21,000,888 | I want when mouse goes on `li` jquery add a class to the element:
```
<ul class="menu">
<li>Menu Item</li>
<li>Menu Item</li>
<li>Menu Item</li>
<li>Menu Item</li>
</ul>
<script type="text/javascript">
var myMenu = $('.menu').children('li');
myMenu.on({
mouseenter: function() { $( this ).addClass( "is_hovered" ); },
mouseleave: function() { $( this ).removeClass( "is_hovered" ); }
});
</script>
```
But I want to remove class only if mouse goes on another `li`, if not **keep** class on element.
Is this possible? | 2014/01/08 | [
"https://Stackoverflow.com/questions/21000888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3173809/"
] | Don't use the mouseleave handler in that case, on mouseenter remove the hovered class from other elements
```
var myMenu = $('.menu li');
myMenu.mouseenter(function () {
myMenu.filter('.is_hovered').removeClass("is_hovered");
$(this).addClass("is_hovered");
});
```
Demo: [Fiddle](http://jsfiddle.net/arunpjohny/HCWw7/) | This will work, when you mouse over li it will add `is_hovered` to li and remove from other li.
```
$(".menu li").mouseover(function(){
$(".menu li").removeClass("is_hovered");
$(this).addClass("is_hovered");
});
``` |
2,095,071 | I am having trouble forming the proof for the following:
Let m>0. We can define operation \* on the equivalence classes of m as follows:
[a]m\*[b]m=[a\*b]m (The m's are subscripts)
---
As an example, we are given the proof for the "+" operation:
[a]m+[b]m=[a+b]m
Proof: We have to show the fns we've claimed to define are well-defined. Suppose a1≡a2 (congruent mod m) and b1≡b2 (congruent mod m). We have to show a1+b1≡a2+b2 (congruent mod m).
By assumption m|a1−a2, and m|b1−b2. Therefore m|(a1−a2)+(b1−b2), which after reorganizing the right-hand side gives m|(a1+b1)−(a2+b2), i.e., a1+b1≡ma2+b2, as required.
---
I understand what "congruent mod m" means, but I'm unsure what an equivalence class and equivalence relation are. Based on the given example, what I thought so far was I need to find steps that will lead to m|(a1\*b1)-(a2\*b2). | 2017/01/12 | [
"https://math.stackexchange.com/questions/2095071",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/406400/"
] | HINT: If you're given a word and you change the last letter, what happens to the number of zeros?
---
EDIT: This hint can give the answer without induction. Let $E\_n$ be the number of words of length $n$ with an even number of $0$'s and $O\_n$ the number of words of length $n$ with an odd number of $0$'s. Define $\phi:\{0,1\}^n \to \{0,1\}^n$ to flip the last letter of the word. Then $\phi^2 = \text{id}$ with $\phi(E\_n) \subset O\_n$ and $\phi(O\_n) \subset E\_n$. This immediately implies that $|E\_n| = |O\_n|$ Since there are $2^n$ total words, this implies $|E\_n| = |O\_n| = 2^{n-1}$. | Two cases: If $n$ is odd, then any word of length $n$ containing an odd number of zeros is a word containing an even number of ones. So under the mapping that turns every one into a zero and every zero into a one, every word that contains an odd number of zeros corresponds to a word with an even number of zeros. That implies that half the words have an even number of zeros.
If $n$ is odd, then omit the last digit of the word. Note that half the words in that $n-1$ universe have an even number of zeros, and will pair with an last digit of zero to give an even number. And half the words in that $n-1$ universe have an odd number of zeros, and will pair with an last digit of oneto give an even number. So the fraction of words of length $n$ with an even number of zeros is $\frac12\cdot \frac12 + \frac12\cdot \frac12 = \frac12$. |
2,095,071 | I am having trouble forming the proof for the following:
Let m>0. We can define operation \* on the equivalence classes of m as follows:
[a]m\*[b]m=[a\*b]m (The m's are subscripts)
---
As an example, we are given the proof for the "+" operation:
[a]m+[b]m=[a+b]m
Proof: We have to show the fns we've claimed to define are well-defined. Suppose a1≡a2 (congruent mod m) and b1≡b2 (congruent mod m). We have to show a1+b1≡a2+b2 (congruent mod m).
By assumption m|a1−a2, and m|b1−b2. Therefore m|(a1−a2)+(b1−b2), which after reorganizing the right-hand side gives m|(a1+b1)−(a2+b2), i.e., a1+b1≡ma2+b2, as required.
---
I understand what "congruent mod m" means, but I'm unsure what an equivalence class and equivalence relation are. Based on the given example, what I thought so far was I need to find steps that will lead to m|(a1\*b1)-(a2\*b2). | 2017/01/12 | [
"https://math.stackexchange.com/questions/2095071",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/406400/"
] | What you are considering are numbers $0000\dots0$ to $1111\dots1$ in binary. Indeed in total there are $2^n$ numbers.
Now, notice it is true for $n=1$. Assume it might be true for the number before your favourite natural number $k-1$.
Now, consider the possibilities for $k$. The last digit is either $0$ or $1$. So the total amount with even number when last is $0$, is all the $k-1$ length strings with odd amount, i.e. $2^{k-1}$. When last is $1$, we seek all the $k-1$ length strings with even amount, i.e. $2^{k-1}$.
Now, the total number would be $2^{k-1} + 2^{k-1} = 2^k$.
So it's true for all the numbers you care about. | Two cases: If $n$ is odd, then any word of length $n$ containing an odd number of zeros is a word containing an even number of ones. So under the mapping that turns every one into a zero and every zero into a one, every word that contains an odd number of zeros corresponds to a word with an even number of zeros. That implies that half the words have an even number of zeros.
If $n$ is odd, then omit the last digit of the word. Note that half the words in that $n-1$ universe have an even number of zeros, and will pair with an last digit of zero to give an even number. And half the words in that $n-1$ universe have an odd number of zeros, and will pair with an last digit of oneto give an even number. So the fraction of words of length $n$ with an even number of zeros is $\frac12\cdot \frac12 + \frac12\cdot \frac12 = \frac12$. |
2,095,071 | I am having trouble forming the proof for the following:
Let m>0. We can define operation \* on the equivalence classes of m as follows:
[a]m\*[b]m=[a\*b]m (The m's are subscripts)
---
As an example, we are given the proof for the "+" operation:
[a]m+[b]m=[a+b]m
Proof: We have to show the fns we've claimed to define are well-defined. Suppose a1≡a2 (congruent mod m) and b1≡b2 (congruent mod m). We have to show a1+b1≡a2+b2 (congruent mod m).
By assumption m|a1−a2, and m|b1−b2. Therefore m|(a1−a2)+(b1−b2), which after reorganizing the right-hand side gives m|(a1+b1)−(a2+b2), i.e., a1+b1≡ma2+b2, as required.
---
I understand what "congruent mod m" means, but I'm unsure what an equivalence class and equivalence relation are. Based on the given example, what I thought so far was I need to find steps that will lead to m|(a1\*b1)-(a2\*b2). | 2017/01/12 | [
"https://math.stackexchange.com/questions/2095071",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/406400/"
] | A proof by induction could be done:
If $n=1, 2^n = 2^0 = 1$ and $1$ word of length $1$ has an even amount of $0$s, which is the word $1$.
Now imagine you have a sequence of length $k-1$. If it has an odd number of $0$s, then you can append a $0$ to the end of it. If it has an even number of $0$s, you can append a $1$ to it.
Assume then that it is true that, for words of length $k$, there are $2^{k-1}$ words with an even number of $0$s.
To those $2^{k-1}$ which have an even number of $0$s you add a $1$, making $2^{k-1}$ words of length $k+1$ that have an even amount of $0$s. To the other $2^{k-1}$ that have an odd number of $0$s, you add a $0$, making another $2^{k-1}$ words that have an even number of $0$s and length $k+1$. Therefore, you have a total of $2^{k-1} + 2^{k-1} = 2\cdot2^{k-1} = 2^k$ words, of length $k+1$, with an even number of $0$s, concluding your proof. | Two cases: If $n$ is odd, then any word of length $n$ containing an odd number of zeros is a word containing an even number of ones. So under the mapping that turns every one into a zero and every zero into a one, every word that contains an odd number of zeros corresponds to a word with an even number of zeros. That implies that half the words have an even number of zeros.
If $n$ is odd, then omit the last digit of the word. Note that half the words in that $n-1$ universe have an even number of zeros, and will pair with an last digit of zero to give an even number. And half the words in that $n-1$ universe have an odd number of zeros, and will pair with an last digit of oneto give an even number. So the fraction of words of length $n$ with an even number of zeros is $\frac12\cdot \frac12 + \frac12\cdot \frac12 = \frac12$. |
32,720,527 | I have a loop:
```
result = []
list = ['a', 'b', 'c', 'd', 'e', 'f']
start = 2
step = 5
end = start + step*len(list)
for i in range(start, end, step):
result.append(list[i%len(list)])
print result
```
in this case, the result would be:
```
['c', 'b', 'a', 'f', 'e', 'd']
```
But let's say, i wanted the result to be(change the starting index to 1):
```
['b', 'a', 'd', 'c', 'f', 'e']
```
How do i make the step change after each loop, so that in the first loop the step is 5 and in the next loop it's 3 then 5 again and so on and on? | 2015/09/22 | [
"https://Stackoverflow.com/questions/32720527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5363349/"
] | You could write your own generator for this sort of thing:
```
from itertools import cycle
def super_range(start, stop, steps):
csteps = cycle(steps)
val = start
while val < stop:
yield val
val += next(csteps)
```
And the usage would look something like:
```
for i in super_range(start, end, (5, 3)):
result.append(list[i%len(list)])
``` | A very simple solution would be to use a separate variable to indicate the index to get from your list , and increase that index manually according to your steps. Example -
```
lst = ['a', 'b', 'c', 'd', 'e', 'f']
i = 1
new_lst = []
for j in range(len(lst)):
new_lst.append(lst[i%len(lst)])
if j%2 == 0:
i += 5
else:
i += 3
```
Demo -
```
>>> lst = ['a', 'b', 'c', 'd', 'e', 'f']
>>> i = 1
>>> new_lst = []
>>> for j in range(len(lst)):
... new_lst.append(lst[i%len(lst)])
... if j%2 == 0:
... i += 5
... else:
... i += 3
...
>>> new_lst
['b', 'a', 'd', 'c', 'f', 'e']
```
Also, you should not use `list` as a variable name , it shadows the built-in function `list` , which means after defining your `list` variable, you would not be able to use the built-in function `list()` . |
32,720,527 | I have a loop:
```
result = []
list = ['a', 'b', 'c', 'd', 'e', 'f']
start = 2
step = 5
end = start + step*len(list)
for i in range(start, end, step):
result.append(list[i%len(list)])
print result
```
in this case, the result would be:
```
['c', 'b', 'a', 'f', 'e', 'd']
```
But let's say, i wanted the result to be(change the starting index to 1):
```
['b', 'a', 'd', 'c', 'f', 'e']
```
How do i make the step change after each loop, so that in the first loop the step is 5 and in the next loop it's 3 then 5 again and so on and on? | 2015/09/22 | [
"https://Stackoverflow.com/questions/32720527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5363349/"
] | A very simple solution would be to use a separate variable to indicate the index to get from your list , and increase that index manually according to your steps. Example -
```
lst = ['a', 'b', 'c', 'd', 'e', 'f']
i = 1
new_lst = []
for j in range(len(lst)):
new_lst.append(lst[i%len(lst)])
if j%2 == 0:
i += 5
else:
i += 3
```
Demo -
```
>>> lst = ['a', 'b', 'c', 'd', 'e', 'f']
>>> i = 1
>>> new_lst = []
>>> for j in range(len(lst)):
... new_lst.append(lst[i%len(lst)])
... if j%2 == 0:
... i += 5
... else:
... i += 3
...
>>> new_lst
['b', 'a', 'd', 'c', 'f', 'e']
```
Also, you should not use `list` as a variable name , it shadows the built-in function `list` , which means after defining your `list` variable, you would not be able to use the built-in function `list()` . | Is it a `while` loop rather than a `for` loop? I.e. one when you don't know how many trips around the loop it'll take, but have a good reason to believe that something will terminate the loop. Outline code:
```
i, inc, newlst = 1, 2, []
while i < len(lst) and i >= 0:
newlst.append( lst[i] )
# if some_condition: inc = some_new_value
i += inc
```
A similar structure uses `while True` with `if something: break` inside.
generators (above) are another approach. |
32,720,527 | I have a loop:
```
result = []
list = ['a', 'b', 'c', 'd', 'e', 'f']
start = 2
step = 5
end = start + step*len(list)
for i in range(start, end, step):
result.append(list[i%len(list)])
print result
```
in this case, the result would be:
```
['c', 'b', 'a', 'f', 'e', 'd']
```
But let's say, i wanted the result to be(change the starting index to 1):
```
['b', 'a', 'd', 'c', 'f', 'e']
```
How do i make the step change after each loop, so that in the first loop the step is 5 and in the next loop it's 3 then 5 again and so on and on? | 2015/09/22 | [
"https://Stackoverflow.com/questions/32720527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5363349/"
] | You could write your own generator for this sort of thing:
```
from itertools import cycle
def super_range(start, stop, steps):
csteps = cycle(steps)
val = start
while val < stop:
yield val
val += next(csteps)
```
And the usage would look something like:
```
for i in super_range(start, end, (5, 3)):
result.append(list[i%len(list)])
``` | Based on what you want to do instead of iterating and changing the step you can use and python built-in function or `itertools` module. In this case you can sue `zip` function and `iterools.chain`:
```
>>> list(chain.from_iterable((j,i) for i,j in zip(li[0::2],li[1::2])))
['b', 'a', 'd', 'c', 'f', 'e']
```
In other cases you might need to use some functions like `itertools.islice()` and `zip_longest` |
32,720,527 | I have a loop:
```
result = []
list = ['a', 'b', 'c', 'd', 'e', 'f']
start = 2
step = 5
end = start + step*len(list)
for i in range(start, end, step):
result.append(list[i%len(list)])
print result
```
in this case, the result would be:
```
['c', 'b', 'a', 'f', 'e', 'd']
```
But let's say, i wanted the result to be(change the starting index to 1):
```
['b', 'a', 'd', 'c', 'f', 'e']
```
How do i make the step change after each loop, so that in the first loop the step is 5 and in the next loop it's 3 then 5 again and so on and on? | 2015/09/22 | [
"https://Stackoverflow.com/questions/32720527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5363349/"
] | You could write your own generator for this sort of thing:
```
from itertools import cycle
def super_range(start, stop, steps):
csteps = cycle(steps)
val = start
while val < stop:
yield val
val += next(csteps)
```
And the usage would look something like:
```
for i in super_range(start, end, (5, 3)):
result.append(list[i%len(list)])
``` | Is it a `while` loop rather than a `for` loop? I.e. one when you don't know how many trips around the loop it'll take, but have a good reason to believe that something will terminate the loop. Outline code:
```
i, inc, newlst = 1, 2, []
while i < len(lst) and i >= 0:
newlst.append( lst[i] )
# if some_condition: inc = some_new_value
i += inc
```
A similar structure uses `while True` with `if something: break` inside.
generators (above) are another approach. |
32,720,527 | I have a loop:
```
result = []
list = ['a', 'b', 'c', 'd', 'e', 'f']
start = 2
step = 5
end = start + step*len(list)
for i in range(start, end, step):
result.append(list[i%len(list)])
print result
```
in this case, the result would be:
```
['c', 'b', 'a', 'f', 'e', 'd']
```
But let's say, i wanted the result to be(change the starting index to 1):
```
['b', 'a', 'd', 'c', 'f', 'e']
```
How do i make the step change after each loop, so that in the first loop the step is 5 and in the next loop it's 3 then 5 again and so on and on? | 2015/09/22 | [
"https://Stackoverflow.com/questions/32720527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5363349/"
] | Based on what you want to do instead of iterating and changing the step you can use and python built-in function or `itertools` module. In this case you can sue `zip` function and `iterools.chain`:
```
>>> list(chain.from_iterable((j,i) for i,j in zip(li[0::2],li[1::2])))
['b', 'a', 'd', 'c', 'f', 'e']
```
In other cases you might need to use some functions like `itertools.islice()` and `zip_longest` | Is it a `while` loop rather than a `for` loop? I.e. one when you don't know how many trips around the loop it'll take, but have a good reason to believe that something will terminate the loop. Outline code:
```
i, inc, newlst = 1, 2, []
while i < len(lst) and i >= 0:
newlst.append( lst[i] )
# if some_condition: inc = some_new_value
i += inc
```
A similar structure uses `while True` with `if something: break` inside.
generators (above) are another approach. |
10,786,623 | Okay.. I am completely new to this PDO stuff.. I have tried to recreate my mysql script (working) to a PDO script (not working).. I have tested that my DB login informations is correctly programmed for PDO..
This is my PDO script...
```
<?
session_start();
//connect to DB
require_once("connect.php");
//get the posted values
$email=htmlspecialchars($_POST['email'],ENT_QUOTES);
$pass=md5($_POST['psw']);
//now validating the email and password
$sql - $conn_business->prepare( "SELECT email, password FROM members WHERE email='".$email."'");
$sql -> execute();
$count = $sql->rowCount();
$result = $sql -> fetch();
// Now use $result['rowname'];
$stmt = $conn_business->prepare("SELECT * FROM members WHERE email='".$email."'");
$stmt ->execute();
$act = $stmt -> fetch();
//if email exists
if($count > 0)
{
//compare the password
if(strcmp($result["password"],$pass)==0)
{
// check if activated
if($act["activated"] == "0")
{
echo "act"; //account is not activated yet
}
else
{
echo "yes"; //Logging in
//now set the session from here if needed
$_SESSION['email'] = $email;
}
}
else
echo "no"; //Passwords don't match
}
else
echo "no"; //Invalid Login
?>
```
And this is my old mysql script...
```
session_start();
require_once("connect.php");
//get the posted values
$email=htmlspecialchars($_POST['email'],ENT_QUOTES);
$pass=md5($_POST['psw']);
//now validating the username and password
$sql="SELECT email, password members WHERE email='".$email."'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$sql2="SELECT * FROM members WHERE email='".$email."'";
$result2=mysql_query($sql2);
$row2=mysql_fetch_array($result2);
$act = $row2['activated'];
//if username exists
if(mysql_num_rows($result)>0)
{
//compare the password
if(strcmp($row['password'],$pass)==0)
{
// check if activated
if($act == "0")
{
echo "act";
}
else
{
echo "yes";
//now set the session from here if needed
$_SESSION['email'] = $email;
}
}
else
echo "no";
}
else
echo "no"; //Invalid Login
```
Does anybody know, what I have done wrong? It is an automatically script.. It is called through AJAX and return data based on 'no', 'yes' and 'act' that tells the AJAX/jQuery script what to do.. As I said - the mysql script is working, so please if anyone could tell me what I have done wrong with the PDO script..
EDIT:
when it returns the data to the jQuery script, this should happen:
if yes: start session, redirect to page2.php with session started.
else if act: write in a field that the account is not activated.
else: write that email and password didn't match.
The thing is, that when I try to write the correct e-mail and password - it continues to write : "email and password didn't match" instead of redirecting.. When I say that it is not working it is because the mysql script does as described but the PDO script doesn't..
And I have tried to change the 'echo "no";' to 'echo "yes";' to see if the login would start anyway, but somehow it continues to write that the email and password didn't match..
SOLUTION:
I ahven't told this because I thought it was unnecessary, but the reason for it not to work was because of that i have had my old mysql code in comment marks on top of the page, so that the session\_start command didn't work.. After deleting the old code it worked, but then I found something else to change, and that is in the PDO script when it is validating it says:
$sql - $conn\_business->prepare( "SELECT email, password FROM members WHERE email='".$email."'");
and then I just changed the '-' after $sql to '=' and now, everything works perfectly... Anyhow thank you everybody.. hope this code can help others.. | 2012/05/28 | [
"https://Stackoverflow.com/questions/10786623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1421945/"
] | The second `factorial` function always returns `1`. The code is built to use an accumulator variable (`acc`), and the first code block gets it right by returning this accumulator variable.
A `factorial` function can be written to return `1`, though, if an accumulator variable is not used. Since this method does not utilize `loop` / `recur`, it can cause a stack overflow easily: try `(fact 5000)`.
```
(defn factorial [x]
(if (<= x 1)
1
(* x (factorial (- x 1)))))
```
([source](https://stackoverflow.com/questions/1662336/clojure-simple-factorial-causes-stack-overflow)) | it's hard to work out what you think should be happening for the question to make sense.
i think maybe you think `loop` is doing more than it does? your code is almost equivalent to:
```
(defn factorial
([n] (factorial n 1)
([n acc]
(if (zero? n)
acc
(recur (dec n) (* n acc)))))
```
which is a stack-safe version of
```
(defn factorial
([n] (factorial n 1)
([n acc]
(if (zero? n)
acc
(factorial (dec n) (* n acc)))))
```
so the `acc` (or `1`) is the final value returned from the function.
all that `loop` does is give a different target for `recur`, which is useful if you have some code between the start of the function and the point where you want to repeat. it's basically a label for a goto. |
4,860,166 | I have two git repositories on different PCs. I have some local branches on every one of them. I don`t want to send this branches to remote server, just keep them local. How can I synchronize then without using a web? Can I just zip repository on one PC and move to another? Is that safe? Maybe I can export somehow newest changes from every branch? | 2011/02/01 | [
"https://Stackoverflow.com/questions/4860166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/205234/"
] | Rather than making a bare clone, I prefer making a **[bundle](http://schacon.github.com/git/git-bundle.html)** (see "[How can I email someone a git repository?](https://stackoverflow.com/questions/2545765/how-can-i-email-someone-a-git-repository/2545784#2545784)"), which generates *one* file, easier to copy around (on an USB stick for instance)
The bonus is that is does have some of the characteristics of a bare repo: you can pull from it or clone it, but you only have to worry about *one* file.
```
machineB$ git clone /home/me/tmp/file.bundle R2
```
>
> This will define a remote called "`origin`" in the resulting repository that lets you fetch and pull from the bundle. The `$GIT_DIR/config` file in `R2` will have an entry like this:
>
>
>
```
[remote "origin"]
url = /home/me/tmp/file.bundle
fetch = refs/heads/*:refs/remotes/origin/*
```
>
> To update the resulting mine.git repository, you can fetch or pull after replacing the bundle stored at `/home/me/tmp/file.bundle` with incremental updates.
>
>
>
>
> After working some more in the original repository, you can create an incremental bundle to update the other repository:
>
>
>
```
machineA$ cd R1
machineA$ git bundle create file.bundle lastR2bundle..master
machineA$ git tag -f lastR2bundle master
```
>
> You then transfer the bundle to the other machine to replace `/home/me/tmp/file.bundle`, and pull from it.
>
>
>
```
machineB$ cd R2
machineB$ git pull
``` | See [this blog post "Synchronizing Git repositories without a server "](http://blog.costan.us/2009/02/synchronizing-git-repositories-without.html) (by [Victor Costan](http://www.blogger.com/profile/13804381550088697006)).
>
> This post describes a method for pushing changes between two repositories without using a server with network connections to both hosts having repositories
>
>
>
Start up by creating a repository on the USB stick.
```
mkdir /path/to/usb/stick/repository.git
git clone --local --bare . /path/to/usb/stick/repository.git
```
Then register the repository on the USB stick as a remote repository, and push the desired branch to it (if you don't want to push master, substitute your desired branch).
```
git remote add usb file:///path/to/usb/stick/repository.git
git push usb master
```
In the future, you can treat the USB repository as any other remote repository. Just make sure it's mounted :) For instance, the following pushes new changes to the USB repository.
```
git push usb
```
On the receiving end, mount the USB stick, and use a file URL for the repository
```
file:///path/to/usb/stick/repository.git
```
A few handy commands:
```
# cloning the repository on the USB stick
git clone file:///path/to/usb/stick/repository.git
# updating a repository cloned from the USB stick using the above command
git pull origin
# adding the USB stick repository as a remote for an existing repository
git remote add usb file:///path/to/usb/stick/repository.git
# updating from a remote repository configured using the above command
git pull usb master
``` |
4,860,166 | I have two git repositories on different PCs. I have some local branches on every one of them. I don`t want to send this branches to remote server, just keep them local. How can I synchronize then without using a web? Can I just zip repository on one PC and move to another? Is that safe? Maybe I can export somehow newest changes from every branch? | 2011/02/01 | [
"https://Stackoverflow.com/questions/4860166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/205234/"
] | See [this blog post "Synchronizing Git repositories without a server "](http://blog.costan.us/2009/02/synchronizing-git-repositories-without.html) (by [Victor Costan](http://www.blogger.com/profile/13804381550088697006)).
>
> This post describes a method for pushing changes between two repositories without using a server with network connections to both hosts having repositories
>
>
>
Start up by creating a repository on the USB stick.
```
mkdir /path/to/usb/stick/repository.git
git clone --local --bare . /path/to/usb/stick/repository.git
```
Then register the repository on the USB stick as a remote repository, and push the desired branch to it (if you don't want to push master, substitute your desired branch).
```
git remote add usb file:///path/to/usb/stick/repository.git
git push usb master
```
In the future, you can treat the USB repository as any other remote repository. Just make sure it's mounted :) For instance, the following pushes new changes to the USB repository.
```
git push usb
```
On the receiving end, mount the USB stick, and use a file URL for the repository
```
file:///path/to/usb/stick/repository.git
```
A few handy commands:
```
# cloning the repository on the USB stick
git clone file:///path/to/usb/stick/repository.git
# updating a repository cloned from the USB stick using the above command
git pull origin
# adding the USB stick repository as a remote for an existing repository
git remote add usb file:///path/to/usb/stick/repository.git
# updating from a remote repository configured using the above command
git pull usb master
``` | Direct copy of a repository to the other file system is an alternative to bare clone or to bundle. After copying you can set the copied repo up directly as a local remote - unintuitive as local remote may seem - to fetch and merge into the first repository.
I.e. to merge repo2 from a second computer into ~/repo1, first copy repo2 to the repo1 file system at ~/repo2 (memory stick, network copy, etc.) and then you can use the answer to [Git pulling changes between two local repositories](https://stackoverflow.com/questions/5775580/git-pulling-changes-between-two-local-repositories):
```
~/repo1 $ git remote add repo2 ~/repo2
~/repo1 $ git fetch repo2
~/repo1 $ git merge repo2/foo
```
This works because as [the wikipedia article on git](http://en.wikipedia.org/wiki/Git_%28software%29) says: "A Git repository — data and metadata — is completely contained within its directory, so a normal system-level copy (or rename, or delete) of an entire Git repository is a safe operation. The resulting copy is both independent of and unaware of the original." |
4,860,166 | I have two git repositories on different PCs. I have some local branches on every one of them. I don`t want to send this branches to remote server, just keep them local. How can I synchronize then without using a web? Can I just zip repository on one PC and move to another? Is that safe? Maybe I can export somehow newest changes from every branch? | 2011/02/01 | [
"https://Stackoverflow.com/questions/4860166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/205234/"
] | See [this blog post "Synchronizing Git repositories without a server "](http://blog.costan.us/2009/02/synchronizing-git-repositories-without.html) (by [Victor Costan](http://www.blogger.com/profile/13804381550088697006)).
>
> This post describes a method for pushing changes between two repositories without using a server with network connections to both hosts having repositories
>
>
>
Start up by creating a repository on the USB stick.
```
mkdir /path/to/usb/stick/repository.git
git clone --local --bare . /path/to/usb/stick/repository.git
```
Then register the repository on the USB stick as a remote repository, and push the desired branch to it (if you don't want to push master, substitute your desired branch).
```
git remote add usb file:///path/to/usb/stick/repository.git
git push usb master
```
In the future, you can treat the USB repository as any other remote repository. Just make sure it's mounted :) For instance, the following pushes new changes to the USB repository.
```
git push usb
```
On the receiving end, mount the USB stick, and use a file URL for the repository
```
file:///path/to/usb/stick/repository.git
```
A few handy commands:
```
# cloning the repository on the USB stick
git clone file:///path/to/usb/stick/repository.git
# updating a repository cloned from the USB stick using the above command
git pull origin
# adding the USB stick repository as a remote for an existing repository
git remote add usb file:///path/to/usb/stick/repository.git
# updating from a remote repository configured using the above command
git pull usb master
``` | I'd just like to add a little twist to things. The information in other posts seems right, but I'd like to mention a few extra things I do in practice.
If I do
```
git remote -v
```
I get information like this
```
USB_F file:///f/Git_repositories/projectname.git (fetch)
USB_F file:///f/Git_repositories/projectname.git (push)
USB_G file:///g/Git_repositories/projectname.git (fetch)
USB_G file:///g/Git_repositories/projectname.git (push)
```
Basically I have defined several remotes with USB names rather than just one as suggested since the drive letter allocated to my USB device changes depending on the port I insert it into.
I then run a script with contents like this
```
cd /path/to/projectname
if [ -d /f/Git_repositories/projectname.git ]
then
git push USB_F --all
git push USB_F --tags
fi
if [ -d /g/Git_repositories/projectname.git ]
then
git push USB_G --all
git push USB_G --tags
fi
```
The intention is to push all branches and all tags to the USB repository if it exists and where ever it is. (The -d flag is checking for existence of the git repository directory and conditional code only executes if the directory exists.)
The original question said: **I have some local branches** on every one of them. I don`t want to send this branches to remote server, just keep them local. **How can I synchronize** ...
The **push -all** and **push --tags** command do this synchronizing, making sure that all the branches and tags are pushed to the USB repository, even new ones that the USB repository was unaware of. There is no defaulting to master or needing to know the names of branches and handling them one by one.
I run this for backup purposes so I've only shown the push side of things, and reduced the number of projects and repositories. In reality I backup multiple projects to multiple locations, but it's only the repeated USB items that are relevant here.
Another thing that is rather obvious but that I have not seen mentioned, is that in order to sync PC A and PC B, you'd need to
```
1. sync PC A and the USB device
2. sync PC B and the USB device
3. sync PC A and the USB device again!
```
Or viewed differently, go
```
PC A -> USB -> PC B
PC B -> USB -> PC A
```
so that ultimately the branches and tags are the same on the two machines. |
4,860,166 | I have two git repositories on different PCs. I have some local branches on every one of them. I don`t want to send this branches to remote server, just keep them local. How can I synchronize then without using a web? Can I just zip repository on one PC and move to another? Is that safe? Maybe I can export somehow newest changes from every branch? | 2011/02/01 | [
"https://Stackoverflow.com/questions/4860166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/205234/"
] | Rather than making a bare clone, I prefer making a **[bundle](http://schacon.github.com/git/git-bundle.html)** (see "[How can I email someone a git repository?](https://stackoverflow.com/questions/2545765/how-can-i-email-someone-a-git-repository/2545784#2545784)"), which generates *one* file, easier to copy around (on an USB stick for instance)
The bonus is that is does have some of the characteristics of a bare repo: you can pull from it or clone it, but you only have to worry about *one* file.
```
machineB$ git clone /home/me/tmp/file.bundle R2
```
>
> This will define a remote called "`origin`" in the resulting repository that lets you fetch and pull from the bundle. The `$GIT_DIR/config` file in `R2` will have an entry like this:
>
>
>
```
[remote "origin"]
url = /home/me/tmp/file.bundle
fetch = refs/heads/*:refs/remotes/origin/*
```
>
> To update the resulting mine.git repository, you can fetch or pull after replacing the bundle stored at `/home/me/tmp/file.bundle` with incremental updates.
>
>
>
>
> After working some more in the original repository, you can create an incremental bundle to update the other repository:
>
>
>
```
machineA$ cd R1
machineA$ git bundle create file.bundle lastR2bundle..master
machineA$ git tag -f lastR2bundle master
```
>
> You then transfer the bundle to the other machine to replace `/home/me/tmp/file.bundle`, and pull from it.
>
>
>
```
machineB$ cd R2
machineB$ git pull
``` | Direct copy of a repository to the other file system is an alternative to bare clone or to bundle. After copying you can set the copied repo up directly as a local remote - unintuitive as local remote may seem - to fetch and merge into the first repository.
I.e. to merge repo2 from a second computer into ~/repo1, first copy repo2 to the repo1 file system at ~/repo2 (memory stick, network copy, etc.) and then you can use the answer to [Git pulling changes between two local repositories](https://stackoverflow.com/questions/5775580/git-pulling-changes-between-two-local-repositories):
```
~/repo1 $ git remote add repo2 ~/repo2
~/repo1 $ git fetch repo2
~/repo1 $ git merge repo2/foo
```
This works because as [the wikipedia article on git](http://en.wikipedia.org/wiki/Git_%28software%29) says: "A Git repository — data and metadata — is completely contained within its directory, so a normal system-level copy (or rename, or delete) of an entire Git repository is a safe operation. The resulting copy is both independent of and unaware of the original." |
4,860,166 | I have two git repositories on different PCs. I have some local branches on every one of them. I don`t want to send this branches to remote server, just keep them local. How can I synchronize then without using a web? Can I just zip repository on one PC and move to another? Is that safe? Maybe I can export somehow newest changes from every branch? | 2011/02/01 | [
"https://Stackoverflow.com/questions/4860166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/205234/"
] | Rather than making a bare clone, I prefer making a **[bundle](http://schacon.github.com/git/git-bundle.html)** (see "[How can I email someone a git repository?](https://stackoverflow.com/questions/2545765/how-can-i-email-someone-a-git-repository/2545784#2545784)"), which generates *one* file, easier to copy around (on an USB stick for instance)
The bonus is that is does have some of the characteristics of a bare repo: you can pull from it or clone it, but you only have to worry about *one* file.
```
machineB$ git clone /home/me/tmp/file.bundle R2
```
>
> This will define a remote called "`origin`" in the resulting repository that lets you fetch and pull from the bundle. The `$GIT_DIR/config` file in `R2` will have an entry like this:
>
>
>
```
[remote "origin"]
url = /home/me/tmp/file.bundle
fetch = refs/heads/*:refs/remotes/origin/*
```
>
> To update the resulting mine.git repository, you can fetch or pull after replacing the bundle stored at `/home/me/tmp/file.bundle` with incremental updates.
>
>
>
>
> After working some more in the original repository, you can create an incremental bundle to update the other repository:
>
>
>
```
machineA$ cd R1
machineA$ git bundle create file.bundle lastR2bundle..master
machineA$ git tag -f lastR2bundle master
```
>
> You then transfer the bundle to the other machine to replace `/home/me/tmp/file.bundle`, and pull from it.
>
>
>
```
machineB$ cd R2
machineB$ git pull
``` | I'd just like to add a little twist to things. The information in other posts seems right, but I'd like to mention a few extra things I do in practice.
If I do
```
git remote -v
```
I get information like this
```
USB_F file:///f/Git_repositories/projectname.git (fetch)
USB_F file:///f/Git_repositories/projectname.git (push)
USB_G file:///g/Git_repositories/projectname.git (fetch)
USB_G file:///g/Git_repositories/projectname.git (push)
```
Basically I have defined several remotes with USB names rather than just one as suggested since the drive letter allocated to my USB device changes depending on the port I insert it into.
I then run a script with contents like this
```
cd /path/to/projectname
if [ -d /f/Git_repositories/projectname.git ]
then
git push USB_F --all
git push USB_F --tags
fi
if [ -d /g/Git_repositories/projectname.git ]
then
git push USB_G --all
git push USB_G --tags
fi
```
The intention is to push all branches and all tags to the USB repository if it exists and where ever it is. (The -d flag is checking for existence of the git repository directory and conditional code only executes if the directory exists.)
The original question said: **I have some local branches** on every one of them. I don`t want to send this branches to remote server, just keep them local. **How can I synchronize** ...
The **push -all** and **push --tags** command do this synchronizing, making sure that all the branches and tags are pushed to the USB repository, even new ones that the USB repository was unaware of. There is no defaulting to master or needing to know the names of branches and handling them one by one.
I run this for backup purposes so I've only shown the push side of things, and reduced the number of projects and repositories. In reality I backup multiple projects to multiple locations, but it's only the repeated USB items that are relevant here.
Another thing that is rather obvious but that I have not seen mentioned, is that in order to sync PC A and PC B, you'd need to
```
1. sync PC A and the USB device
2. sync PC B and the USB device
3. sync PC A and the USB device again!
```
Or viewed differently, go
```
PC A -> USB -> PC B
PC B -> USB -> PC A
```
so that ultimately the branches and tags are the same on the two machines. |
4,860,166 | I have two git repositories on different PCs. I have some local branches on every one of them. I don`t want to send this branches to remote server, just keep them local. How can I synchronize then without using a web? Can I just zip repository on one PC and move to another? Is that safe? Maybe I can export somehow newest changes from every branch? | 2011/02/01 | [
"https://Stackoverflow.com/questions/4860166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/205234/"
] | Direct copy of a repository to the other file system is an alternative to bare clone or to bundle. After copying you can set the copied repo up directly as a local remote - unintuitive as local remote may seem - to fetch and merge into the first repository.
I.e. to merge repo2 from a second computer into ~/repo1, first copy repo2 to the repo1 file system at ~/repo2 (memory stick, network copy, etc.) and then you can use the answer to [Git pulling changes between two local repositories](https://stackoverflow.com/questions/5775580/git-pulling-changes-between-two-local-repositories):
```
~/repo1 $ git remote add repo2 ~/repo2
~/repo1 $ git fetch repo2
~/repo1 $ git merge repo2/foo
```
This works because as [the wikipedia article on git](http://en.wikipedia.org/wiki/Git_%28software%29) says: "A Git repository — data and metadata — is completely contained within its directory, so a normal system-level copy (or rename, or delete) of an entire Git repository is a safe operation. The resulting copy is both independent of and unaware of the original." | I'd just like to add a little twist to things. The information in other posts seems right, but I'd like to mention a few extra things I do in practice.
If I do
```
git remote -v
```
I get information like this
```
USB_F file:///f/Git_repositories/projectname.git (fetch)
USB_F file:///f/Git_repositories/projectname.git (push)
USB_G file:///g/Git_repositories/projectname.git (fetch)
USB_G file:///g/Git_repositories/projectname.git (push)
```
Basically I have defined several remotes with USB names rather than just one as suggested since the drive letter allocated to my USB device changes depending on the port I insert it into.
I then run a script with contents like this
```
cd /path/to/projectname
if [ -d /f/Git_repositories/projectname.git ]
then
git push USB_F --all
git push USB_F --tags
fi
if [ -d /g/Git_repositories/projectname.git ]
then
git push USB_G --all
git push USB_G --tags
fi
```
The intention is to push all branches and all tags to the USB repository if it exists and where ever it is. (The -d flag is checking for existence of the git repository directory and conditional code only executes if the directory exists.)
The original question said: **I have some local branches** on every one of them. I don`t want to send this branches to remote server, just keep them local. **How can I synchronize** ...
The **push -all** and **push --tags** command do this synchronizing, making sure that all the branches and tags are pushed to the USB repository, even new ones that the USB repository was unaware of. There is no defaulting to master or needing to know the names of branches and handling them one by one.
I run this for backup purposes so I've only shown the push side of things, and reduced the number of projects and repositories. In reality I backup multiple projects to multiple locations, but it's only the repeated USB items that are relevant here.
Another thing that is rather obvious but that I have not seen mentioned, is that in order to sync PC A and PC B, you'd need to
```
1. sync PC A and the USB device
2. sync PC B and the USB device
3. sync PC A and the USB device again!
```
Or viewed differently, go
```
PC A -> USB -> PC B
PC B -> USB -> PC A
```
so that ultimately the branches and tags are the same on the two machines. |
19,852,385 | I am trying to write 2 functions for a single click action, based on the screen width:
```
$(".view_offer_wrapper").click(function(){
var current = $(".compare_wrapper div:last-child").index(this);
$(".product_desc_expand").hide();
});
if ($(window).width() < 480) {
// Different action for same click function
}
```
First click works fine, no issues with it.
But if the window size < 480, first click is initiated rather than the click function inside the if condition. | 2013/11/08 | [
"https://Stackoverflow.com/questions/19852385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2358234/"
] | The first solution is to check the condition within the click handler
```
$(".view_offer_wrapper").click(function () {
if ($(window).width() < 480) {
//action 1
} else {
//action2
var current = $(".compare_wrapper div:last-child").index(this);
$(".product_desc_expand").hide();
}
});
```
Second solution is to register different click handlers based on the condition
```
if ($(window).width() < 480) {
$(".view_offer_wrapper").click(function () {
//action 1
});
} else {
$(".view_offer_wrapper").click(function () {
//action2
var current = $(".compare_wrapper div:last-child").index(this);
$(".product_desc_expand").hide();
});
}
```
*Note: If you want to support resizing of window then you have to choose the first solution* | Try this
```
$(".view_offer_wrapper").click(function(){
if ($(window).width() < 480) {
alert('width less than 480');
}
else
{
alert('width grater than 480');
}
});
```
You can use **if else** inside click function. |
45,569,682 | I am new to Hadoop and Spark. I am using Spark-2.1.1-bin-hadoop2.7. Using SparkR I want to load (read) data from Hadoop 2.7.3 HDFS.
I know, I can point to my Hadoop file using "hdfs://somepath-to-my-file" but I could not find a function in SparkR to do the job. read.df() doesn't work.
I am using sparkR.session() to connect to my Spark session.
For launching R interface for Spark, I ran sparkR from spark's bin location.
In short, I want to load csv file from HDFS using sparkR.
Please help. If possible, provide example.
Thanks,
SG | 2017/08/08 | [
"https://Stackoverflow.com/questions/45569682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4816088/"
] | It seems that you have copied that line including typographic (?) quotes. Have a look at the output:
>
> resolving cookbooks for run list: ["“apache::server”"]
>
>
>
So fix those quotes in your shell command:
```
$ sudo chef-client -z --runlist "apache::server"
``` | Try with
```
chef-client -z -o apache
``` |
53,877,447 | I'm using `"laravel/lumen-framework": "5.7.*"`
I have two middlewares, first one `AuthTokenAuthenticate` that should be applied to all the routes, so its defined in `bootstrap/app.php` like
```
$app->middleware([
App\Http\Middleware\AuthTokenAuthenticate::class
]);
```
Another middleware is defined like
```
$app->routeMiddleware([
'auth.token' => Vendor\Utilities\Middleware\AuthToken::class
]);
```
and will only be applied to some specific routes.
I need `auth.token` to be executed first, then `AuthTokenAuthenticate` but I can't find the way to do it because Lumen executes `$app->middleware` routes first.
Laravel has `$middlewarePriority` which is exactly what I need, but how can I handle it in Lumen? | 2018/12/20 | [
"https://Stackoverflow.com/questions/53877447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5329658/"
] | I don't think this is possible in Lumen in the way you want to. What I suggest is using the middleware alongside the [router group middleware options](https://lumen.laravel.com/docs/5.7/routing#route-group-middleware).
---
Remove the global middleware registration
*/bootstrap/app.php*
```
$app->middleware([
//App\Http\Middleware\AuthTokenAuthenticate::class
]);
```
Add both middlewares to the route middleware
*/bootstrap/app.php*
```
$app->routeMiddleware([
'auth.token' => Vendor\Utilities\Middleware\AuthToken::class,
'auth.token.authenticate' => App\Http\Middleware\AuthTokenAuthenticate::class
]);
```
Create two route groups: one with just `auth.token.authenticate` and one group with both `auth.token` **and** `auth.token.authenticate`.
*/routes/web/php*
```
$router->get('/', ['middleware' => 'auth.token.authenticate', function () use ($router) {
// these routes will just have auth.token.authenticate applied
}]);
$router->get('/authenticate', ['middleware' => 'auth.token|auth.token.authenticate', function () use ($router) {
// these routes will have both auth.token and auth.token.authenticate applied, with auth.token being the first one
}]);
```
I think this is the cleanest way to get the desired effect. | As of now with Lumen v6 (and possibly earlier), you can specify the middleware as an array field when defining your route. In the routes file `web.php`, I have something like the following:
```
$router->get('/api/path/to/thing', [
'uses' => 'FooController@index',
'middleware' => ['etag', 'caching', 'bar']
]);
```
Note how the the `middleware` field is an array with three elements. When this route is called, the middleware `etag` will execute first, then `caching`, then `bar`, in that order. When you only have a single middleware class, you can either specify it as a plain string or an array with just one element. This can of course be extended to [route groups](https://lumen.laravel.com/docs/5.4/routing#route-groups) so that you have an entire class of routes that all use this middleware in this order. |
39,399,338 | I have an array of select boxes, with a unique id like this.
```
<select class="taskcompleted" id="c392018">
<option value="No">No</option>
<option value="Yes">Yes</option>
</select>
```
I have a JSON in the format
```
{"id":"c392018","value":"Yes"}
```
I am using the following Javascript to set the selected value
```
$.getJSON('getstatus.php') //place correct script URL
.done(function(response) {
$.each(response, function(key) {
var SelectObj = response[key];
console.log(SelectObj['value']);
jQuery('#' + SelectObj['id']).val(SelectObj['value']).attr('selected', true);
});
});
```
This is not selecting the value of "Yes". How can I do this? | 2016/09/08 | [
"https://Stackoverflow.com/questions/39399338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/813813/"
] | If you are just trying to trigger a repair of Smart Ink there are easier approaches. Msiexec allows you to [pass it the guid for the ProductId](https://technet.microsoft.com/en-us/library/bb490936.aspx) instead of a path to an msi. All you need to do is get the guid which should remain the same for all installations of the same version of the software. An easy way to get the GUID from the registry instead of invoking Win32\_Product is:
```
##Read in installed packages, check for a displayname, split the key to get the GUID
$prodId = Get-ChildItem HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall |
Where-Object {$_.GetValue('DisplayName') -match 'smart ink'} |
Foreach-Object { $_.Name -split '\\'} | Select-Object -last 1
```
In my case this returns {5ABC49B5-D0DC-428D-A082-4AEFF6490F04} as the Smart Ink Product ID. You can then pass this to msiexec.
```
msiexec /fa $prodId
``` | Try this...
```
$localPackageName = 'localPackageName'
$command = 'C:\windows\system32\MSIExec.exe /f'
get-wmiobject -class win32_product -filter "name = 'smart ink'" | select-object localpackage -outvariable localPackageName
$packageName = $localPackageName.localpackage
$string = '{0} {1}' -f $command, $packageName
Invoke-Expression $string
``` |
4,242,798 | We have an add in for VS that currently is launched from the tools menu, the add-in consists of a a UI offering the user a few option buttons, which I now want to convert to a top-level menu that would offer the same functionality.
I've read [this](http://msdn.microsoft.com/en-us/library/bb165473.aspx) tutorial, which helped me add a new top-level menu, but couldn't really understand the logic behind all the steps. The guide doesn't really clear what each of the steps create or how can your change the output.
What the steps create is a new top-level menu with a single item underneath it. I'm trying to create some hierarchy in my menu (i.e. Top Level -> Sub category -> Commands) but got abit lost with all the groups/menus/IDs structure.
Is there any clear explanation for the structure of these files? A documentation or a tutorial? If anyone had experience in the subject and could help clear things up I would much appreciate it... | 2010/11/22 | [
"https://Stackoverflow.com/questions/4242798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428489/"
] | I haven't tried doing hierarchical menu items, but I have had similar problems with the Visual SDK .vcst file. It is a pain. A couple of things you can do.
1. Install the VS Package Editor to Visual Studio Blog Entry for it: <http://blogs.msdn.com/b/visualstudio/archive/2010/09/08/introducing-the-vspackage-builder.aspx>
2. Download source code (open source so you can see how they do it) for an add-in that does similar things. Example is AnkhSVN which is a Subversion Repository Add-in to Visual Studio. Here is the source code: <http://ankhsvn.open.collab.net/source/browse/ankhsvn/> | **Code example**
```
<?xml version="1.0" encoding="utf-8"?>
<CommandTable xmlns="...">
<!-- Extern section unchanged -->
<Commands package="guidHowToPackagePkg">
<Menus>
<!-- New menu added -->
<Menu guid="guidBasicVSCTSampleCmdSet" id="SubMenu" priority="0x200"
type="Menu">
<Parent guid="guidBasicVSCTSampleCmdSet" id="TopLevelMenuGroup" />
<Strings>
<ButtonText>Other Commands</ButtonText>
<CommandName>Other Commands</CommandName>
</Strings>
</Menu>
</Menus>
<Groups>
<!-- Group changed to SubMenuGroup and attached to SubMenu -->
<Group guid="guidBasicVSCTSampleCmdSet" id="SubMenuGroup"
priority="0x0600">
<Parent guid="guidBasicVSCTSampleCmdSet" id="SubMenu"/>
</Group>
</Groups>
<Buttons>
<!-- We attached these two buttons to SubMenuGroup -->
<Button guid="guidBasicVSCTSampleCmdSet" id="ThirdCommand" priority="0x0100"
type="Button">
<Parent guid="guidBasicVSCTSampleCmdSet" id="SubMenuGroup" />
<Icon guid="guidImages" id="bmpPicX" />
<Strings>
<CommandName>ThirdCommand</CommandName>
<ButtonText>Third Command</ButtonText>
</Strings>
</Button>
<Button guid="guidBasicVSCTSampleCmdSet" id="FourthCommand"
priority="0x0101" type="Button">
<Parent guid="guidBasicVSCTSampleCmdSet" id="SubMenuGroup" />
<Icon guid="guidImages" id="bmpPicArrows" />
<Strings>
<CommandName>FourthCommand</CommandName>
<ButtonText>Fourth Command</ButtonText>
</Strings>
</Button>
</Buttons>
</Commands>
<Symbols>
<!-- We add a SubMenu and changed SubMenuGroup -->
<GuidSymbol name="guidBasicVSCTSampleCmdSet" value="...">
<IDSymbol name="SubMenu" value="0x0101" />
<IDSymbol name="SubMenuGroup" value="0x0201" />
</GuidSymbol>
</Symbols>
</CommandTable>
```
This provides you with the following top-level menu:
[](https://i.stack.imgur.com/jEryl.png)
Here's a full chapter on the topic. This pretty much explains everything there is to know on (hierarchical) menu's.
<http://dotneteers.net/blogs/divedeeper/archive/2010/05/23/vs-2010-package-development-chapter-2-commands-menus-and-toolbars.aspx> |
4,242,798 | We have an add in for VS that currently is launched from the tools menu, the add-in consists of a a UI offering the user a few option buttons, which I now want to convert to a top-level menu that would offer the same functionality.
I've read [this](http://msdn.microsoft.com/en-us/library/bb165473.aspx) tutorial, which helped me add a new top-level menu, but couldn't really understand the logic behind all the steps. The guide doesn't really clear what each of the steps create or how can your change the output.
What the steps create is a new top-level menu with a single item underneath it. I'm trying to create some hierarchy in my menu (i.e. Top Level -> Sub category -> Commands) but got abit lost with all the groups/menus/IDs structure.
Is there any clear explanation for the structure of these files? A documentation or a tutorial? If anyone had experience in the subject and could help clear things up I would much appreciate it... | 2010/11/22 | [
"https://Stackoverflow.com/questions/4242798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428489/"
] | I haven't tried doing hierarchical menu items, but I have had similar problems with the Visual SDK .vcst file. It is a pain. A couple of things you can do.
1. Install the VS Package Editor to Visual Studio Blog Entry for it: <http://blogs.msdn.com/b/visualstudio/archive/2010/09/08/introducing-the-vspackage-builder.aspx>
2. Download source code (open source so you can see how they do it) for an add-in that does similar things. Example is AnkhSVN which is a Subversion Repository Add-in to Visual Studio. Here is the source code: <http://ankhsvn.open.collab.net/source/browse/ankhsvn/> | I assume that nowadays by "add-in" you mean an extension that is a VS package (using the VS SDK) because an "add-in" was an older form of extension for VS 2013 and lower. (If you really mean an "add-in" then see my sample [HOWTO: Adding buttons, commandbars and toolbars to Visual Studio .NET from an add-in](https://www.mztools.com/articles/2005/MZ2005003.aspx))
Packages use .vsct files. To answer your question, see the .vsct files of my samples [here](https://github.com/carlos-quintero/VSX-Samples):
* CommandTopMenu
* CommandSubMenu
(and to learn see also the other ones for context menus, toolbars, etc.). In the .vcst file they use "CommandPlacements" to separate the definition of an item from its "placement", and comments to explain the relationship between the 3 kinds of items:
1. Menus (Main-menu/Top-menus/Sub-menus/Context menus) and Toolbars.
2. Groups: a group is a container for other groups and also for commands and sub-menus.
3. Commands
Remember the rules:
* The parent of a top-menu is always the Main menu of VS, never a group
* The parent of a sub-menu is always a group, never directly a toolbar or any kind of menu.
* The parent of a command is always a group, never directly a toolbar or any kind of menu (same rule that for sub-menus)
* The parent of a group can be a menu, a toolbar, a context menu, etc. and it can be also another group.
* A menu (any kind) or toolbar can be either created by your extension (except the main menu of VS) or an existing one of VS, identified by prefix "IDM\_". See [GUIDs and IDs of Visual Studio menus](https://learn.microsoft.com/en-us/visualstudio/extensibility/internals/guids-and-ids-of-visual-studio-menus?view=vs-2017) and [GUIDs and IDs of Visual Studio toolbars](https://learn.microsoft.com/en-us/visualstudio/extensibility/internals/guids-and-ids-of-visual-studio-toolbars?view=vs-2017).
* A group can be either new (created by your extension) or an existing group of Visual Studio, identified by prefix "IDG\_". You have some built-in Visual Studio groups in the links above, but for a more exhaustive list install the [ExtensionTools](https://marketplace.visualstudio.com/items?itemName=MadsKristensen.ExtensibilityTools) extension (Mads Kristensen) that provides intellisense in the .vsct file or check the source code of its [VsctBuiltInCache.cs file](https://github.com/madskristensen/ExtensibilityTools/blob/master/src/VSCT/Completion/VsctBuiltInCache.cs). |
4,242,798 | We have an add in for VS that currently is launched from the tools menu, the add-in consists of a a UI offering the user a few option buttons, which I now want to convert to a top-level menu that would offer the same functionality.
I've read [this](http://msdn.microsoft.com/en-us/library/bb165473.aspx) tutorial, which helped me add a new top-level menu, but couldn't really understand the logic behind all the steps. The guide doesn't really clear what each of the steps create or how can your change the output.
What the steps create is a new top-level menu with a single item underneath it. I'm trying to create some hierarchy in my menu (i.e. Top Level -> Sub category -> Commands) but got abit lost with all the groups/menus/IDs structure.
Is there any clear explanation for the structure of these files? A documentation or a tutorial? If anyone had experience in the subject and could help clear things up I would much appreciate it... | 2010/11/22 | [
"https://Stackoverflow.com/questions/4242798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428489/"
] | I assume that nowadays by "add-in" you mean an extension that is a VS package (using the VS SDK) because an "add-in" was an older form of extension for VS 2013 and lower. (If you really mean an "add-in" then see my sample [HOWTO: Adding buttons, commandbars and toolbars to Visual Studio .NET from an add-in](https://www.mztools.com/articles/2005/MZ2005003.aspx))
Packages use .vsct files. To answer your question, see the .vsct files of my samples [here](https://github.com/carlos-quintero/VSX-Samples):
* CommandTopMenu
* CommandSubMenu
(and to learn see also the other ones for context menus, toolbars, etc.). In the .vcst file they use "CommandPlacements" to separate the definition of an item from its "placement", and comments to explain the relationship between the 3 kinds of items:
1. Menus (Main-menu/Top-menus/Sub-menus/Context menus) and Toolbars.
2. Groups: a group is a container for other groups and also for commands and sub-menus.
3. Commands
Remember the rules:
* The parent of a top-menu is always the Main menu of VS, never a group
* The parent of a sub-menu is always a group, never directly a toolbar or any kind of menu.
* The parent of a command is always a group, never directly a toolbar or any kind of menu (same rule that for sub-menus)
* The parent of a group can be a menu, a toolbar, a context menu, etc. and it can be also another group.
* A menu (any kind) or toolbar can be either created by your extension (except the main menu of VS) or an existing one of VS, identified by prefix "IDM\_". See [GUIDs and IDs of Visual Studio menus](https://learn.microsoft.com/en-us/visualstudio/extensibility/internals/guids-and-ids-of-visual-studio-menus?view=vs-2017) and [GUIDs and IDs of Visual Studio toolbars](https://learn.microsoft.com/en-us/visualstudio/extensibility/internals/guids-and-ids-of-visual-studio-toolbars?view=vs-2017).
* A group can be either new (created by your extension) or an existing group of Visual Studio, identified by prefix "IDG\_". You have some built-in Visual Studio groups in the links above, but for a more exhaustive list install the [ExtensionTools](https://marketplace.visualstudio.com/items?itemName=MadsKristensen.ExtensibilityTools) extension (Mads Kristensen) that provides intellisense in the .vsct file or check the source code of its [VsctBuiltInCache.cs file](https://github.com/madskristensen/ExtensibilityTools/blob/master/src/VSCT/Completion/VsctBuiltInCache.cs). | **Code example**
```
<?xml version="1.0" encoding="utf-8"?>
<CommandTable xmlns="...">
<!-- Extern section unchanged -->
<Commands package="guidHowToPackagePkg">
<Menus>
<!-- New menu added -->
<Menu guid="guidBasicVSCTSampleCmdSet" id="SubMenu" priority="0x200"
type="Menu">
<Parent guid="guidBasicVSCTSampleCmdSet" id="TopLevelMenuGroup" />
<Strings>
<ButtonText>Other Commands</ButtonText>
<CommandName>Other Commands</CommandName>
</Strings>
</Menu>
</Menus>
<Groups>
<!-- Group changed to SubMenuGroup and attached to SubMenu -->
<Group guid="guidBasicVSCTSampleCmdSet" id="SubMenuGroup"
priority="0x0600">
<Parent guid="guidBasicVSCTSampleCmdSet" id="SubMenu"/>
</Group>
</Groups>
<Buttons>
<!-- We attached these two buttons to SubMenuGroup -->
<Button guid="guidBasicVSCTSampleCmdSet" id="ThirdCommand" priority="0x0100"
type="Button">
<Parent guid="guidBasicVSCTSampleCmdSet" id="SubMenuGroup" />
<Icon guid="guidImages" id="bmpPicX" />
<Strings>
<CommandName>ThirdCommand</CommandName>
<ButtonText>Third Command</ButtonText>
</Strings>
</Button>
<Button guid="guidBasicVSCTSampleCmdSet" id="FourthCommand"
priority="0x0101" type="Button">
<Parent guid="guidBasicVSCTSampleCmdSet" id="SubMenuGroup" />
<Icon guid="guidImages" id="bmpPicArrows" />
<Strings>
<CommandName>FourthCommand</CommandName>
<ButtonText>Fourth Command</ButtonText>
</Strings>
</Button>
</Buttons>
</Commands>
<Symbols>
<!-- We add a SubMenu and changed SubMenuGroup -->
<GuidSymbol name="guidBasicVSCTSampleCmdSet" value="...">
<IDSymbol name="SubMenu" value="0x0101" />
<IDSymbol name="SubMenuGroup" value="0x0201" />
</GuidSymbol>
</Symbols>
</CommandTable>
```
This provides you with the following top-level menu:
[](https://i.stack.imgur.com/jEryl.png)
Here's a full chapter on the topic. This pretty much explains everything there is to know on (hierarchical) menu's.
<http://dotneteers.net/blogs/divedeeper/archive/2010/05/23/vs-2010-package-development-chapter-2-commands-menus-and-toolbars.aspx> |
72,225,209 | I made a method that search through an array list of objects. Then if the searchKey is found in the array list it will print this certain item.
Here is how I iterate through the array list if it contains the searchKey, but I just realized that it is impossible to compare a string and an object.
```
for(int x = 0; x < Student.students.size(); x ++){
if(Student.students.contains(searchKey))
System.out.print(Student.students.get(x));
}
```
Here's how I create the constructor and array list.
```
String firstName, lastName, course, yearLevel, gender;
Student(String firstName, String lastName, String course, String yearLevel, String gender)
{
this.firstName = firstName;
this.lastName = lastName;
this.course = course;
this.yearLevel = yearLevel;
this.gender = gender;
}
static ArrayList<Student> students = new ArrayList<Student>();
``` | 2022/05/13 | [
"https://Stackoverflow.com/questions/72225209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18890007/"
] | You need to compare the one property; also you can use a for-each loop to simplify the code
```java
for(Student s : Student.students){
if(s.getName().equals(searchKey))
System.out.print(s);
}
```
---
Note :
When you use a condition `Student.students.contains(searchKey)` in a loop, and it doesn't use the iteration variable that means there is a problem | You already know comparing Object to String makes no sense. So, most probably what you are trying to do is check if any of the attributes of your Student object(name/course/year etc) has a value that matches your search key. To do that you need to convert your object into a String.
Add a **toString** method to your Student class which will look something like this:
```
public String toString() {
return "Student [firstName=" + firstName + ", lastName=" + lastName + ", course=" + course + ", yearLevel="
+ yearLevel + ", gender=" + gender + "]";
}
```
Then, look for your searchKey in the string representation of your objects while iterating.
```
for(int x = 0; x < students.size(); x ++){
if(students.get(x).toString().contains(searchKey))
System.out.print(students.get(x).toString());
}
```
Edit: As rightly pointed out by Jon Skeet in the comments, the default toString method will generate incorrect results, a custom implementation should be used to convert the object to String. |
72,225,209 | I made a method that search through an array list of objects. Then if the searchKey is found in the array list it will print this certain item.
Here is how I iterate through the array list if it contains the searchKey, but I just realized that it is impossible to compare a string and an object.
```
for(int x = 0; x < Student.students.size(); x ++){
if(Student.students.contains(searchKey))
System.out.print(Student.students.get(x));
}
```
Here's how I create the constructor and array list.
```
String firstName, lastName, course, yearLevel, gender;
Student(String firstName, String lastName, String course, String yearLevel, String gender)
{
this.firstName = firstName;
this.lastName = lastName;
this.course = course;
this.yearLevel = yearLevel;
this.gender = gender;
}
static ArrayList<Student> students = new ArrayList<Student>();
``` | 2022/05/13 | [
"https://Stackoverflow.com/questions/72225209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18890007/"
] | You need to compare the one property; also you can use a for-each loop to simplify the code
```java
for(Student s : Student.students){
if(s.getName().equals(searchKey))
System.out.print(s);
}
```
---
Note :
When you use a condition `Student.students.contains(searchKey)` in a loop, and it doesn't use the iteration variable that means there is a problem | You haven't defined what 'contains' means here but I'm going to assume that it means a Student contains the key if it appears as a substring in any of its String members. So let's start with a method that does that. We can define this as part of the Student class itself.
```
public class Student {
.... other stuff ....
/**
* Return true if any of the properties of this Student
* contain the given substring, false otherwise
*/
public boolean contains(String s) {
// consider addressing null cases - omitting for simplicity
return firstName.contains(s) ||
lastName.contains(s) ||
course.contains(s) ||
yearLevel.contains(s) ||
gender.contains(s);
}
}
```
Now you can iterate over your List and invoke this method to find the matches. Note that you need to handle the case that multiple Students may match a given search key (or none may match). So I would suggest collecting the results in a separate List. One does not generally iterate over Lists via the index. This example uses an enhanced for-loop (aka for-each).
```
public List<Student> findMatches(List<Student> students, String key) {
List<Student> found = new ArrayList<>();
for (Student s : students) {
if (s.contains(key)) {
found.add(s);
}
}
return found;
}
```
This is a good case for using the Stream API.
```
public List<Student> findMatches(List<Student> students, String key) {
return students.stream()
.filter(s -> s.contains(key))
.collect(Collectors.toList());
}
``` |
72,225,209 | I made a method that search through an array list of objects. Then if the searchKey is found in the array list it will print this certain item.
Here is how I iterate through the array list if it contains the searchKey, but I just realized that it is impossible to compare a string and an object.
```
for(int x = 0; x < Student.students.size(); x ++){
if(Student.students.contains(searchKey))
System.out.print(Student.students.get(x));
}
```
Here's how I create the constructor and array list.
```
String firstName, lastName, course, yearLevel, gender;
Student(String firstName, String lastName, String course, String yearLevel, String gender)
{
this.firstName = firstName;
this.lastName = lastName;
this.course = course;
this.yearLevel = yearLevel;
this.gender = gender;
}
static ArrayList<Student> students = new ArrayList<Student>();
``` | 2022/05/13 | [
"https://Stackoverflow.com/questions/72225209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18890007/"
] | You haven't defined what 'contains' means here but I'm going to assume that it means a Student contains the key if it appears as a substring in any of its String members. So let's start with a method that does that. We can define this as part of the Student class itself.
```
public class Student {
.... other stuff ....
/**
* Return true if any of the properties of this Student
* contain the given substring, false otherwise
*/
public boolean contains(String s) {
// consider addressing null cases - omitting for simplicity
return firstName.contains(s) ||
lastName.contains(s) ||
course.contains(s) ||
yearLevel.contains(s) ||
gender.contains(s);
}
}
```
Now you can iterate over your List and invoke this method to find the matches. Note that you need to handle the case that multiple Students may match a given search key (or none may match). So I would suggest collecting the results in a separate List. One does not generally iterate over Lists via the index. This example uses an enhanced for-loop (aka for-each).
```
public List<Student> findMatches(List<Student> students, String key) {
List<Student> found = new ArrayList<>();
for (Student s : students) {
if (s.contains(key)) {
found.add(s);
}
}
return found;
}
```
This is a good case for using the Stream API.
```
public List<Student> findMatches(List<Student> students, String key) {
return students.stream()
.filter(s -> s.contains(key))
.collect(Collectors.toList());
}
``` | You already know comparing Object to String makes no sense. So, most probably what you are trying to do is check if any of the attributes of your Student object(name/course/year etc) has a value that matches your search key. To do that you need to convert your object into a String.
Add a **toString** method to your Student class which will look something like this:
```
public String toString() {
return "Student [firstName=" + firstName + ", lastName=" + lastName + ", course=" + course + ", yearLevel="
+ yearLevel + ", gender=" + gender + "]";
}
```
Then, look for your searchKey in the string representation of your objects while iterating.
```
for(int x = 0; x < students.size(); x ++){
if(students.get(x).toString().contains(searchKey))
System.out.print(students.get(x).toString());
}
```
Edit: As rightly pointed out by Jon Skeet in the comments, the default toString method will generate incorrect results, a custom implementation should be used to convert the object to String. |
69,830,956 | I want to create a function that checks, if a specific time is between two timestamps that are stored in a MySQL database.
The function should be able to ignore the time (`$fullday = true`) or check the time as well.
My presence table has a row with `start = 2021-11-01 10:00:00` and `end = 2021-11-05 18:00:00`.
`is_available('2021-11-02', true);` should give me a result, but is doesn't.
What I expect as well:
`is_available('2021-11-01 09:30:00');` should not have a result, as 9:30 is before 10:00 but `is_available('2021-11-01 10:01:00');` should give me a result. And so on.
The query, my function creates is:
```sql
SELECT *
FROM `presence`
WHERE DATE_FORMAT(start, "%Y-%m-%d") <= "2021-11-02"
AND DATE_FORMAT(end, "%Y-%m-%d") >= "2021-11-02"
```
And this my function so far:
```php
function is_available($date, $fullday = false)
{
$presenceModel = new PresenceModel();
if ($fullday) {
$date = date('Y-m-d', strtotime($date));
$presences = $presenceModel
->where('DATE_FORMAT(start, "%Y-%m-%d") <= "' . $date . '"')
->where('DATE_FORMAT(end, "%Y-%m-%d") >= "' . $date . '"')
->findAll();
} else {
$date = date('Y-m-d H:i:s', strtotime($date));
$presences = $presenceModel
->where('DATE_FORMAT(start, "%Y-%m-%d %H:%i:%s") <= "' . $date . '"')
->where('DATE_FORMAT(end, "%Y-%m-%d %H:%i:%s") >= "' . $date . '"')
->findAll();
}
return count($presences) > 0 ? true : false;
}
``` | 2021/11/03 | [
"https://Stackoverflow.com/questions/69830956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17023379/"
] | You should be able to simplify this dramatically by getting MySQl to do more of the work. You don't need to format DATETIME columns to do comparisons on them, and BETWEEN will further reduce your PHP effort.
Based on your code above I think this will do the job:
```
function is_available($date, $fullDay = false) {
$presenceModel = new PresenceModel();
$date = date('Y-m-d H:i:s', strtotime($date));
if ($fullDay) {
$presences = $presenceModel
->where("'$date' between DATE(`start`) and DATE(`end`)" )
->findAll();
} else {
$presences = $presenceModel
->where("'$date' between `start` and `end`" )
->findAll();
}
return count($presences) > 0 ? true : false;
}
```
However, using `SELECT *` will return the entirety of all the matching rows, when all you really need is whether one exists. You should aim to get your query something close to this, which will return just a single value (`1`) if there's a matching row.:
```
SELECT 1 FROM `presence`
WHERE "2021-11-02" between start AND end
LIMIT 1
``` | My approach would be to use `strtotime()` function to convert the date into an **int** and then convert the other date from the **db** and then compare those **ints** in php.
```
if($datenow > $dbstartdate && $datenow < $dbenddate){
return true;
}else{
return false;
}
``` |
228,492 | I converted a .tif file into a tileset using the gdal2tiles plugin on QGIS. The resulting files are a bunch of .png files, .html files and a .xml file. I zipped these and tried uploading them to Carto but got the error that the file types were not supported.
What am I doing wrong? How does one upload these tiles? | 2017/02/15 | [
"https://gis.stackexchange.com/questions/228492",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/91630/"
] | CARTO is a location intelligence platform aimed to store vector datasets you want to visualize and analyze. CARTO does not support uploading tilesets. You need to publish them elsewhere on a static web service hosting and then if they fit the technical requirements (projection and so on) you'll be able to add them as a basemap to your CARTO visualization. | You can't import directly file formats such as .png, .html or .xml to CARTO due to those are not supported formats (In [this section](https://carto.com/docs/carto-engine/import-api/importing-geospatial-data#supported-geospatial-data-formats) of the documentation of CARTO, you can find detailed information about the supported files to import to CARTO)
In order to add the custom tileset to be added as a basemap to CARTO they would need to be stored in a web server. So you can add them to the map by adding a new basemap using a URL. |
23,849,070 | The Windows Phone Toolkit for Windows Phone 8.0 has a control called LongListMultiSelector that offers a really cool way to select items. It shifts the item content to the right slightly so users can tap that area in order to select that item. The default e-mail application has the exact behavior I want to achieve.
I'm trying to achieve the same behavior in a Windows Phone 8.1 Windows Runtime app, but am having a hard time to get it done. Since the LongListMultiSelector inherits from a simple Control I think it might be possible to convert it to Windows Phone 8.1 but I would rather not do that if I can avoid it.
Anyway, has anyone done this or know how to do it? | 2014/05/24 | [
"https://Stackoverflow.com/questions/23849070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1462485/"
] | There's no reason to implement your DataTemplate with a CheckBox. ListView already supports multiple selection mode, and has supported it since WinRT and Windows 8.
Essentially, all you need to do is change the SelectionMode to multiple, and the CheckBoxes will appear on the left just like you're used to with LongListMultiSelector.
Let's say you have a dummy ListView like this one, with hardcoded items, to keep it simple:
```
<ListView x:Name="ListViewMultiSelector" SelectionMode="None">
<ListViewItem>Dog0</ListViewItem>
<ListViewItem>Dog1</ListViewItem>
<ListViewItem>Dog2</ListViewItem>
<ListViewItem>Dog3</ListViewItem>
<ListViewItem>Dog4</ListViewItem>
<ListViewItem>Dog5</ListViewItem>
</ListView>
```
If you change the SelectionMode in code behind (on some event, button click, page tap, swipe, whatever)
```
this.ListViewMultiSelector.SelectionMode = ListViewSelectionMode.Multiple;
```
it will show the CheckBoxes.
In the SelectionChanged event (in SelectionChangedEventArgs to be more exact) you can get AddedItems and RemovedItems, a list of objects - IList. AddedItems contains the latest selected items which may have triggered the SelectionChanged, and the RemovedItems contains the latest unselected items which may have triggered the SelectionChanged. | @konikos, @Benjamin Diele
This in the XAML
```
<ListView SelectionMode="Single" SelectionChanged="ListMovimentos_OnSelectionChanged" Padding="0 0 0 40" ItemsSource="{Binding ListMovimentos}" ItemContainerStyle="{StaticResource ListItemsContainerGeneric}" x:Name="ListMovimentos"></ListView>
```
and this in the code behind
```
private void ListMovimentos_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ListMovimentos.SelectedItems.Count > 0)
{
ListMovimentos.SelectionMode = ListViewSelectionMode.Multiple;
}
else
{
ListMovimentos.SelectionMode = ListViewSelectionMode.Single;
}
}
```
Did the trick for me and got the animation like Windows Phone LongListMultiSelector. |
14,160,461 | I know that there are a lot of similar questions, but I cannot really fix it.
I've lost a week and I'm still at square one.
I'm trying to export a very basic app that perform a login on Facebook. The code is the same code as in the sample.
It works in debug but exporting it returns the error `Dalvik format failed with error 1`
If I remove the reference and create a blank app, everything works.
If I add the reference to the Facebook sdk, it chrashes.
I've checked my references, paths, cleaned all, rebooted the machine. Nothing works!
I'm not using proguard.
I've installed Java 6.
I'm on win 8 64 bit. | 2013/01/04 | [
"https://Stackoverflow.com/questions/14160461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1230711/"
] | My problem was solved by doing this :
**Uncheck** `Project -> Build Automatically`
Now export your apk. It should work without any problem. | See ["Conversion to Dalvik format failed with error 1" on external JAR](https://stackoverflow.com/questions/2680827/conversion-to-dalvik-format-failed-with-error-1-on-external-jar)
>
> Go to Project » Properties » Java Build Path » Libraries and remove
> all except the "Android X.Y" (in my case Android 1.5). click OK. Go to
> Project » Clean » Clean projects selected below » select your project
> and click OK. That should work.
>
>
>
If this does not help try to update your Android tools (Help --> Check for Updates) or simply download a new copy of Eclipse and install the Android SDK again.
I faced this problem ones and I had to reinstall android-sdks |
14,160,461 | I know that there are a lot of similar questions, but I cannot really fix it.
I've lost a week and I'm still at square one.
I'm trying to export a very basic app that perform a login on Facebook. The code is the same code as in the sample.
It works in debug but exporting it returns the error `Dalvik format failed with error 1`
If I remove the reference and create a blank app, everything works.
If I add the reference to the Facebook sdk, it chrashes.
I've checked my references, paths, cleaned all, rebooted the machine. Nothing works!
I'm not using proguard.
I've installed Java 6.
I'm on win 8 64 bit. | 2013/01/04 | [
"https://Stackoverflow.com/questions/14160461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1230711/"
] | My problem was solved by doing this :
**Uncheck** `Project -> Build Automatically`
Now export your apk. It should work without any problem. | I was having this problem too with an app that used Facebook SDK. I was trying all sorts of stuff, so I'm not sure what exactly fixed but here's settings that worked for me:
FacebookSDK > Properties > Java Build Path > Order and Export
Android 2.2 - NOT CHECKED
Android Private Libraries - CHECKED
Android Dependencies - CHECKED
MyApp > Properties > Java Build Path > Order and Export
Android 4.2.2 - CHECKED
Android Private Libraries - CHECKED
Android Dependencies - CHECKED
In addition, I had done this before, not sure it mattered. Reverted to Facebook SDK version 3.5 from 3.5.2. Updated to latest ADT 22.2.1. Changed Facebook SDK to use Android 2.2 from 4.2.2. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.