text:
Q: Spring boot - Independant scheduled tasks I work with Java 8.
I have about 20 scheduled tasks (so about 20 java class) that execute different process with pdf files. Each task has is own frequency. The frequencies are stored in database. So I can change frequency in database and I don't have to restart my tomcat. This is one of them :
@Service
public class InboundJob implements SchedulingConfigurer {

private static final Logger logger = LoggerFactory.getLogger(InboundJob.class);

@Autowired
InboundService inboundService;

ScheduledTaskRegistrar scheduledTaskRegistrar;

@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
    if (scheduledTaskRegistrar == null) {
        scheduledTaskRegistrar = taskRegistrar;
    }
    if (taskRegistrar.getScheduler() == null) {
        taskRegistrar.setScheduler(inboundService.poolScheduler());
    }

    taskRegistrar.addTriggerTask(
        () -> scheduleCron(inboundService.getJobRepo().findByLibelleIgnoreCase("INBOUND").getFrequency()),
        t -> {
            CronTrigger crontrigger = new CronTrigger(inboundService.getJobRepo().findByLibelleIgnoreCase("INBOUND").getFrequency());
            return crontrigger.nextExecutionTime(t);
            }
        );
}

public void scheduleCron(String cron) {

    try {
        Job inboundJob = inboundService.getJobRepo().findByLibelleIgnoreCase("INBOUND");
        if (inboundJob.getStatus() == null) {
            for (Bannette item : inboundService.getBannetteRepo().findByIdaijobAndStatus(inboundJob.getIdaijob(), null)) {
                if (!inboundService.isFolderExisting(item.getFolderpath())) {
                    logger.error("InboundJob - Le répertoire {} n'existe pas ", item.getFolderpath());
                } else {
                    ArrayList<File> filesList = inboundService.getFileList(item.getFolderpath());
                    if (filesList.size() > 0) {
                        logger.info("InboundJob: " + filesList.size() + " nouveau(x) fichier(s) dans " + item.getFolderpath());
                        inboundService.trtList(filesList, item);
                    }
                }
            }
        }
    } catch (Exception ure) {
        logger.info("InboundJob - ERROR: " + ExceptionUtils.getStackTrace(ure));
    }
}

public void activateScheduler() {
    logger.info("Re-Activating Scheduler");
    configureTasks(scheduledTaskRegistrar);
}

}

The problem is, if a task runs, the others can't start until it has finished...
Is there a way to make them independant ?
------ edit 2022/04/14 -----
this is additionnal info asked in comment
I use spring boot
the imports in my class are
import java.io.File;
import java.util.ArrayList;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

import com.test.mc.entity.Bannette;
import com.test.mc.entity.Job;
import com.test.mc.job.service.InboundService;

and poolScheduler method in my custom InboundService class
 @Bean
public TaskScheduler poolScheduler() {
    ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    scheduler.setThreadNamePrefix("ThreadPoolTaskScheduler");
    scheduler.setPoolSize(1);
    scheduler.initialize();
    return scheduler;
}

The aim of this mecanism is to get information about frequency in database. And if I change the frequency in my table, the new value is effective without to restart tomcat server. It works fine !
Finally, this is the main method of the project with spring boot configuration
@SpringBootApplication
@EnableJpaAuditing
@EnableScheduling
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class MyKlinckApplication extends SpringBootServletInitializer  {

public static void main(String[] args) {
    SpringApplication.run(MyKlinckApplication.class, args);
}

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(MyKlinckApplication.class);
}

}
tell me if you need more


text:
Q: Java MAVEN: Could not find or load main class stigastatistics.stigastatistics.StatisticsGUI I know, it was written here many times, but I tried solutions, but with no success. I have netbeans maven project with dependencies. I want to make executable jar file with dependencies. This is my pom file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>sitgaStatistics</groupId>
<artifactId>StigaStatistics</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    <mainClass>stigastatistics.stigastatistics.StatisticsGUI</mainClass>
</properties>
<build>
    <plugins>
        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>2.4</version>
            <configuration>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
                <archive>
                    <manifest>
                        <mainClass>${mainClass}</mainClass>
                    </manifest>
                </archive>
            </configuration>
            <executions>
                <execution>
                    <id>make-assembly</id>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

    </plugins>
</build>
<dependencies>
    <dependency>
            <groupId>gov.nih.imagej</groupId>
            <artifactId>imagej</artifactId>
            <version>1.42</version>
    </dependency>
</dependencies>
<name>StigaStatisticsGUI</name>
</project>

when I clean and build projext it will create 2 jar files in target direcotry (StigaStatistics-1.0-SNAPSHOT.jar, StigaStatistics-1.0-SNAPSHOT-jar-with-dependencies.jar) when I start them from terminal like:
    java -jar StigaStatistics-1.0-SNAPSHOT-jar-with-dependencies.jar
it will respond me error:
Error: Could not find or load main class stigastatistics.stigastatistics.StatisticsGUI
I really don't know what is wrong with this.
Thanks for answers

A: The problem is the misspelled fully-qualified name of the main class. There is a typo in the first part of the package name.
Either rename the package sitgastatistics.stigastatistics or correct the <mainClass>stigastatistics.stigastatistics.StatisticsGUI</mainClass> property definition so that the package name reads the same.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $ without any path 2 days ago, I created a project, now I am trying to reopen and build it again, but android studio shows such an error, I can't find the solution. The main problem is that there is no path in the error, and it says that error is at 1:1. Can anyone help?
![Look at] https://i.stack.imgur.com/MuaVb.png https://i.stack.imgur.com/MuaVb.png

A: Have a look at the AndroidManifest.xml in your app module.
It probably contains a character somewhere, which makes the Manifest invalid.
I have this sometimes, when I try to save, but accidentally type an "s" instead. E.g look for mistakes like this:
s<?xml version="1.0" encoding="utf-8"?

Note, the extra 's'


text:
Q: Decode base64 to uiimage iOS Swift decodedData is nil but My base64String contains an extremely long string
Encode
var imgProfile:NSData = UIImagePNGRepresentation(imgUI)
let base64String = imgProfile.base64EncodedStringWithOptions(.allZeros)

Decode
let base64String = prefs.valueForKey("imgDefault") as? String
let decodedData = NSData(base64EncodedString: base64String!, options: NSDataBase64DecodingOptions(rawValue: 0) )
var decodedimage = UIImage(data: decodedData!)

I"m having trouble outputting my image from base64
base64 string ENCODE before inserting into db:

iVBORw0KGgoAAAANSUhEUgAAAgAAAAIACAMAAADDpiTIAAAADFBMVEXFxcX////p6enW1tbAmiBwAAAAHGlET1QAAAACAAAAAAAAAQAAAAAoAAABAAAAAQAAAAYAppse6QAABcxJREFUeAHs3et22jAQReEQ3v+di8sikDaxZeGLdPTxpzS202jP9pwRkNWPDw8EEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQiCVwvV4/p8fl9fH3K7cjsau2sBuBqfKvVf/x+ecnDQJtKSn9qw83DQIpDLqktcV/iECCAGFuXf9Rz6o/5UHPEtTe+t9V0Qj6dGCb6t9d4EBvDrzb+b/3gOlvsqAjB97M/f+rf/+KjUEfDuxU/nsb6APBwD/llsn/UycwDTQt1443/9MGSdCqA4eUXxK0Wv6P917xed7hJc8+m6Uw7A922O1/90MOtGXaweWXA8OXnwINKXAtSe1dzvGWcQManND9nzIZBU434MjZ/1n45zP7gVMVOPX2v1ugCZxowHnp/2wBl4tJ4CwFzm7/DwvEwCkGNND+vwzQBI5XoI32/1CAAUcb0Er7fxggBg41oKH2/2WAJnCcAg3Wf/rU4HEABv+Xmqw/Aw6zsq3x7xEB0596wBEStFt/Boxefwbsb0Br27/XBJie2w7u60Dr9WfA6PVnwJ4GtDz/PbPAXmAvB/qov0lw9PozYB8Dern/pyyQAts70Ojrv8/of33mfYHNBeiq/t4X2L

base64 string DECODE when pulling down from db:

Optional("iVBORw0KGgoAAAANSUhEUgAAAgAAAAIACAMAAADDpiTIAAAADFBMVEXFxcX////p6enW1tbAmiBwAAAAHGlET1QAAAACAAAAAAAAAQAAAAAoAAABAAAAAQAAAAYAppse6QAABcxJREFUeAHs3et22jAQReEQ3v
  di8sikDaxZeGLdPTxpzS202jP9pwRkNWPDw8EEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQiCVwvV4/p8fl9fH3K7cjsau2sBuBqfKvVf/x
  ecnDQJtKSn9qw83DQIpDLqktcV/iECCAGFuXf9Rz6o/5UHPEtTe
  t9V0Qj6dGCb6t9d4EBvDrzb b/3gOlvsqAjB97M/f rf/
  KjUEfDuxU/nsb6APBwD/llsn/UycwDTQt1443/9MGSdCqA4eUXxK0Wv6P917xed7hJc8
  m6Uw7A922O1/90MOtGXaweWXA8OXnwINKXAtSe1dzvGWcQManND9nzIZBU434MjZ/1n45zP7gVMVOPX2v1ugCZxowHnp/2wBl4tJ4CwFzm7/DwvEwCkGNND
  vwzQBI5XoI32/1CAAUcb0Er7fxggBg41oKH2/2WAJnCcAg3Wf/rU4HEABv
  Xmqw/Aw6zsq3x7xEB0596wBEStFt/Boxefwbsb0Br27/XBJie2w7u60Dr9WfA6PVnwJ4GtDz/PbPAXmAvB/qov0lw9PozYB8Dern/pyyQAts70Ojrv8/of33mfYHNB

A: There are two different problems:

*

*It would appear that the + characters have been replaced with spaces. That will happen if you submit an application/x-www-form-urlencoded request without percent escaping the + characters. This probably happened when you first sent the base64 string to be stored in the database.
See https://stackoverflow.com/a/24888789/1271826 for a discussion of some percent encoding patterns. The key point here is to not rely upon stringByAddingPercentEscapesUsingEncoding, because that will allow + characters to go unescaped.

*The string is also missing the trailing = characters. (The string's length should be a multiple of four, and in this case, it's two characters short, so there should be == at the end of the rendition with the + characters in it (the "before" string). While that is sometimes a mistake made by poorly designed base64-encoders, this is not a problem that base64EncodedStringWithOptions suffers from.
In this case, it looks like a much longer base64 string must have been truncated somehow. (Your strings are suspiciously close to 1024 characters. lol.) This truncation could happen if you put the parameters in the URL rather than the body of the request. But nothing in this code sample would account for this behavior, so the problem rests elsewhere.
But look at the length of the original NSData. The base64 string should be 1/3 larger than that (plus rounded up to the nearest four characters, once you include the trailing = characters).
And, once you decode the string that you've provided and look at the actual contents, you can also see that the base64 string was truncated. (According to the portion provided, there should be 1484 bytes of IDAT data, and there's not, plus there's no IEND chunk ... don't worry about those details, but rest assured that it's basically saying that the PNG data stream is incomplete.)

A: If you're getting nil returned, then your base64 string is not valid. NSData(base64EncodedString:options:) requires a base64 string that is padded with = to a multiple of 4.
Here's a similar issue (except in Obj-C).
NSData won't accept valid base64 encoded string


text:
Q: Сравнить объекты DateTime В базе есть таблица, одно из полей имеет тип данных datetime. Существует форма сортировки, пользователь вводит данные в любом доступном для класса DateTime формате, отправляет, мы их принимаем, на их основе формируем объект DateTime, цель - найти совпадения объекта с записью в базе данных. Всё бы ничего, но запись в базе имеет вид '2015-08-07 15:43:07', а нужно найти совпадения ТОЛЬКО ПО ДАТЕ, время роли не играет, LIKE использовать нельзя. Как поступить? (фреймворк Symfony2, ORM Doctrine2)

A: Есть расширения для доктрины: https://github.com/beberlei/DoctrineExtensions
Устанавливаете через composer
Прописываете конфиг config.yml
doctrine:
    orm:
        entity_managers:
            default:
                auto_mapping: true
                dql:
                    datetime_functions:
                        DAY: DoctrineExtensions\Query\Mysql\Day
                        MONTH: DoctrineExtensions\Query\Mysql\Month
                        YEAR: DoctrineExtensions\Query\Mysql\Year

И далее запрос, например:
$now = new \DateTime('now');
$em = $this->getDoctrine()->getManager();
$qb = $em->getRepository('AppBundle:Event')->createQueryBuilder('e');
$qb
    ->where('DAY(e.start_time) = :day')
    ->andWhere('MONTH(e.start_time) = :month')
    ->andWhere('YEAR(e.start_time) = :year')
    ->setParameter('day', $now->format('d'))
    ->setParameter('month', $now->format('m'))
    ->setParameter('year', $now->format('Y'));

$event = $qb->getQuery()->getOneOrNullResult();

A: Сравнение только по дате с использованием ANSI SQL CAST:
CAST(date_time_1 AS DATE) = CAST(date_time_2 AS DATE)


text:
Q: Using a Long Press Gesture only if certain conditions are met I am trying to create a long press gesture that presents a second view controller, once the press has been held for 3 seconds.  However, I only want the second view controller presented if the device is in a certain accelerometer orientation for the ENTIRE 3 seconds.  That is, if the gesture is not held long enough or the device is tilted too much, the gesture is dismissed and the user must try again.
// In FirstViewController.h
#import <UIKit/UIKit.h>
#import <CoreMotion/CoreMotion.h>

@interface FirstViewController : UIViewController

@property (nonatomic, strong) CMMotionManager *motionManager;

@end

// In FirstViewController.m
#import "FirstViewController"
#import "SecondViewController"

@implementation motionManager;

- (void) viewDidLoad
{
    [super viewDidLoad];
    self.motionManager = [[CMMotionManager alloc]init];
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(handleLongPress:)];
    longPress.minimumPressDuration = 3.0;
    [self.view addGestureRecognizer:longPress];
}

- (void) handleLongPress: (UILongPressGestureRecognizer *)sender
{
    // Not sure what to do here
}

I have previously tried chunks of code in the last method but it looks obnoxious and just is not correct.  Instead, I have listed several lines of code below that I know work individually, but I need assistance in making them all work together.
// Accelerometer
if ([self.motionManager isAccelerometerAvailable])
{
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    [self.motionManager startAccelerometerUpdatesToQueue:queue withHandler:^(CMAccelerometerData *accelerometerData,NSError *error)
    {
        if (ABS(accelerometerData.acceleration.x) < 0.3 && ABS(accelerometerData.acceleration.y) < 0.30 && ABS(accelerometerData.acceleration.z) > 0.70) // Phone is flat and screen faces up
        {
            NSLog(@"Correct Orientation!!!");
            [self.motionManager stopAccelerometerUpdates];
        }
        else
        {
            NSLog(@"Incorrect orientation!!!");
            [self.motionManager stopAccelerometerUpdates];
        }];
}

else
{
    NSLog(@"Accelerometer is not available.");
}

// Go to second view controller
if (sender.state == UIGestureRecognizerStateBegan)
{
    SecondViewController *svc = [self.storyboard instantiateViewControllerWithIdentifier:@"SecondViewController"];
    [self presentViewController:svc animated:YES completion:nil];
}

Any ideas?  Or even a more general way to cancel the gesture unless a condition is met would be very helpful.

A: You may be able to do what you want by subclassing UIGestureRecognizer to make your own gesture recognizer similar to  UILongPressGestureRecognizer that listens for accelerometer data in addition to presses of at least 3 second duration.

A: I'd probably override the onTouchesBegan, and onTouchesEnded methods, rather than using a gesture recogniser.
I'd then create a NSTimer object, an NSTimeInterval var and a BOOL in your view controller; for the sake of it, I'll call them, touchTimer, initialTouchTimeStamp, and touchValid.
for the sake of complexity, it's an assumption that the viewControllers view is not multi-touch.
Assume the repeatTime = 0.25f;
longPressTimeRequired = 3;
The timer selector would incorporate your accelerometer method, if the data inside your accelerometer method is invalid, I'd set a touchValid to false (and invalidate the timer), otherwise I'd set it to true  After checking the accelerometer, I'd check if my initialTouchTimeStamp var is longPressTimeRequired or more seconds prior to [touchTimer fireDate] - repeatTime , if it is, and the touchValid is true, then I would go to my second controller.
onTouchesBegan, I'd invalidate touchTimer and create a new one that would repeat every repearTime seconds, and lasts for y seconds.  Set touchValid to NO, and set initialTouchTimeStamp to touch.timestamp.
onTouchesEnded, I'd invalidate touchTimer, and check if my initialTouchTimeStamp var is longPressTimeRequired or more seconds prior to [touchTimer fireDate] - repeatTime , if it is, and the touchValid is true, then I would go to my second controller.
there are many common elements in here, and it's probably not the most elegant way of doing things, but it should work.  Hope this helps.

A: I hope the code is verbose enough for you to read, it's pretty self explanatory - I've stuck with your accelerometer code, and used the same variable names.
#import "ViewController.h"
#import <CoreMotion/CoreMotion.h>

@interface ViewController () {

    NSOperationQueue    *motionQueue;
    NSTimer             *touchTimer;
    NSTimeInterval      initialTimeStamp;
    BOOL                touchValid;

    float                timerPollInSeconds;
    float                longPressTimeRequired;
}

@property (strong, nonatomic)            NSTimer             *touchTimer;
@property (assign, nonatomic)            NSTimeInterval      initialTimeStamp;
@property (assign, nonatomic)            BOOL                touchValid;
@property (assign, nonatomic)            float               timerPollInSeconds;
@property (assign, nonatomic)            float               longPressTimeRequired;
@property (strong, nonatomic)            CMMotionManager     *motionManager;
@property (strong, nonatomic)            NSOperationQueue    *motionQueue;

@end

@implementation ViewController

@synthesize touchTimer = _touchTimer, initialTimeStamp, touchValid, motionQueue = _motionQueue;
@synthesize timerPollInSeconds, longPressTimeRequired, motionManager = _motionManager;

- (void)viewDidLoad
{
    self.timerPollInSeconds = 0.25f;
    self.longPressTimeRequired = 3.0f;
    self.touchTimer = nil;
    self.touchValid = NO;
    self.initialTimeStamp = NSTimeIntervalSince1970;
    self.motionManager = [[CMMotionManager alloc] init];
    self.motionQueue = [[NSOperationQueue alloc] init];
    [_motionQueue setName:@"MotionQueue"];
    [_motionQueue setMaxConcurrentOperationCount:NSOperationQueueDefaultMaxConcurrentOperationCount];

    [super viewDidLoad];

    self.view.multipleTouchEnabled = NO;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Operations

-(void) startLongPressMonitorWithTimeStamp:(NSTimeInterval) timeStamp {
    NSLog(@"Starting monitoring - %g", timeStamp);
    if( self.touchTimer ) {
        if( [_touchTimer isValid] ) {
            [_touchTimer invalidate];
        }
    }

    self.touchTimer = [NSTimer timerWithTimeInterval:self.timerPollInSeconds target:self selector:@selector(timerPolled:) userInfo:nil repeats:YES];

    if( [_motionManager isAccelerometerAvailable] ) {
        NSLog(@"Accelerometer Available");
        if( ![_motionManager isAccelerometerActive] ) {
            NSLog(@"Starting Accelerometer");
            [_motionManager startAccelerometerUpdatesToQueue:self.motionQueue withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {

                if (ABS(accelerometerData.acceleration.x) < 0.3 && ABS(accelerometerData.acceleration.y) < 0.30 && ABS(accelerometerData.acceleration.z) > 0.70) // Phone is flat and screen faces up
                {
                    dispatch_sync(dispatch_get_main_queue(), ^{
                        self.touchValid = YES;
                    });
                }
                else
                {
                    dispatch_sync(dispatch_get_main_queue(), ^{
                        self.touchValid = NO;
                        [self stopLongPressMonitoring:YES];
                    });
                };
            }];
        }
        else {
            NSLog(@"Accelerometer already active");
        }
    }
    else {
        NSLog(@"Accelerometer not available");
    }

    self.initialTimeStamp = timeStamp;

    self.touchValid = YES;
    [_touchTimer fire];

    [[NSRunLoop mainRunLoop] addTimer:self.touchTimer forMode:NSRunLoopCommonModes];
}

-(void) stopLongPressMonitoring:(BOOL) touchSuccessful {
    [_motionManager stopAccelerometerUpdates];
    [_touchTimer invalidate];
    self.touchValid = NO;

    if( touchSuccessful ) {
        NSLog(@"Yes");
    }
    else {
         NSLog(@"No");
    }
}

#pragma mark - User Interaction
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    //We're using the current times, interval since the touches timestamp refers to system boot up
    // it is more than feasible to use this boot up time, but for simplicity, I'm just using this
    NSTimeInterval timestamp = [NSDate timeIntervalSinceReferenceDate];
    [self startLongPressMonitorWithTimeStamp:timestamp];
}

-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    if( self.touchValid && [NSDate timeIntervalSinceReferenceDate] - self.initialTimeStamp == self.longPressTimeRequired ) {
        [self stopLongPressMonitoring:YES];
    }
    else {
        [self stopLongPressMonitoring:NO];
    }
}

#pragma mark - Timer Call back
-(void) timerPolled:(NSTimer *) timer {
    NSTimeInterval firedTimeStamp = [NSDate timeIntervalSinceReferenceDate];
    NSLog(@"Timer polled - %g", firedTimeStamp);
    if( self.touchValid ) {
        NSLog(@"Time elapsed: %d", (int)(firedTimeStamp - self.initialTimeStamp));

        if( firedTimeStamp - self.initialTimeStamp >= self.longPressTimeRequired ) {
            NSLog(@"Required time has elapsed");
            [self stopLongPressMonitoring:YES];
        }
    }
    else {
        NSLog(@"Touch invalidated");
        [self stopLongPressMonitoring:NO];
    }
}

@end


text:
Q: Any way in initialize objects in a constructor that need "this" as a parameter? I ran into the problem in Java, but I guess it's a question about OOP in general. It should be a pretty common need, so I hope there's a solution I'm just unaware of.
What do you do when you need to initialize an object's fields within the constructor, but those objects need this as a parameter?
So this is what you can't do:
public class SomeClass {
    private SomeOtherClass foo;
    public SomeClass (SomeOtherClass foo) {
         this.foo = foo;
    }
}

public class SomeOtherClass {
     private SomeClass bar;
     public SomeOtherClass() {
          bar = new SomeClass(this);
     }
}

I don't know about any solution except having an init() method that does all object initialization, and calling it after I initialize the SomeOtherClass object in my main program. Is there a better way? Or is there a way to make a method of SomeOtherClass (the init() method) run after the constructor is complete, without calling it explicitly?
Thanks!

A: You can do what you've shown. Why do you think it won't work?
The only limitation is passing this to the superclass constructor (which is a much rarer temptation). For example, you can't do this:
public class SomeSubclass extends SomeSuperclass {
  public SomeSubclass() {
    super(this); /* ERROR: Can't pass `this` to super-ctor. */
  }
}

A: I've always used initialize() methods for this. I guess you might be able to spawn some form of thread that runs after object creation, but that's a terrible idea. As far as doing it within the constructor, as you initially asked, I don't see how that would work.
To use a car analogy, you're in the middle of building a car (SomeOtherClass), but are unsure of its state of completion. You want the car to drive on a road (SomeClass), but to use that road you need a complete car. So doing what you say would be like passing the road an engine and expecting everything to work out. It just doesn't make sense in OOP terms.
TL;DR: Use an init() method as you suggested and call it a day.


text:
Q: Switching Orders of Differentiation and Integration in case of Function of 2 Variables I encountered the following equation in my calculus lecture notes:
$$
\frac{d}{dx}\int_0^xf(x,y)dy = f(x,x)+\int_0^x\frac{\partial f}{\partial x}(x,y)dy
$$
Could you show me how to prove the above equality?

A: This is a particular version of what is known as  the Leibniz Integral Rule. The wikipedia link provides a nice proof of the general case(s), and it is not too hard to see how this particular form follows


text:
Q: Post xml data with auth using python I have this xml string i want to POST to an API url, i've been cheking the docs and came up with something like this:
import urllib.request as ur
import urllib.parse as up

auth_handler = ur.HTTPBasicAuthHandler()
auth_handler.add_password(realm='something',
                        uri='http://api/api',
                        user=username,
                        passwd=passw)

opener = ur.build_opener(auth_handler)
opener.addheaders = [('User-agent', 'api-id'), ("Content-Type","applicaiton/xml;charset=utf-8")]

data = up.urlencode(('<?xml version="1.0" encoding="UTF-8"?>'
                "<entry>"
                        "<episode>"+ep_no+"</episode>"
                        "<status></status>"
                        "<score></score>"
                        "<tags></tags>"
                "</entry>"))

bin_data = data.encode('utf-8')
opener.open("http://api/api/add/"+id+".xml", data=bin_data)

However, i'm getting:
...
File "/home/hairo/sandbox/post_test.py", line 124, in post
data = up.urlencode(('<?xml version="1.0" encoding="UTF-8"?>'
...
raise TypeError
TypeError: not a valid non-string sequence or mapping object

It looks like i'm missing something obvious, but i can't figure out what it is, any help?

A: That call to urlencode is only passing a one-element tuple. Here's an example of what type of argument urlencode works with.
"Convert a mapping object or a sequence of two-element tuples".


text:
Q: Forms Authenticate HI ,
i must create an application with a Forms Authentication in WPF, so i create a database(UserId,Username,Password,PasswordQuestion,PassworAnswer) and store data with Linq ToSQL but i don't know the right procedure how to create  LoginForm to authenticate  the username and password with Linq ToSQl and set up the roles for each user.
Do you have any idea or advice to do it right?
Thanks
Bye

A: I think you should look into creating a roles table first.
With that said, your LINQ query would look something like this:
var result =
  (
    from c in dataContext where username == Username and password == Password
    select c
  )

Very vague question, though. If you can clarify, you'll get better results.


text:
Q: Is the source validator (org.eclipse.wst.sse.ui.sourcevalidation) related with the editor or just with the content-type? Currently I have source validator(org.eclipse.wst.sse.ui.sourcevalidation) to check the html source:
<extension point="org.eclipse.wst.sse.ui.sourcevalidation">
    <validator
        scope="total"
        class="com.test.HtmlValidator"
        id="com.test.HtmlValidator.total">
        <contentTypeIdentifier
            id="org.eclipse.wst.html.core.htmlsource">
            <partitionType id="org.eclipse.wst.html.HTML_DEFAULT"/>
            <partitionType id="org.eclipse.wst.html.HTML_DECLARATION"/>
            <partitionType id="org.eclipse.wst.html.HTML_COMMENT"/>
        </contentTypeIdentifier>
    </validator>

The source validator works as expected with the default html editor (org.eclipse.wst.html.core.htmlsource.source) but if I open the same files with the Eclipse Generic Editor (org.eclipse.ui.genericeditor.GenericEditor, Eclipse Wild Web Developer uses it to open all the web development files) the source validator does not work.
Until I know the source validator works directly with the content type not with the editor, my question here is what should I do to make the validator work with both editors?

A: To solve this problem I have found a workaround using the org.eclipse.core.filebuffers.documentSetup extension point, this extension point executes the method IDocumentSetupParticipant.setup(IDocument document), the advantage of this extension point is that it is independent of the editor. org.eclipse.core.filebuffers.documentSetup executes when a file with certain content type is open using any editor.
<extension
       point="org.eclipse.core.filebuffers.documentSetup">
   <participant
      class="setup.HTMLDocumentSetup"
      contentTypeId="org.eclipse.wst.html.core.htmlsource">
    </participant>
 </extension>

In IDocumentSetupParticipant.setup we can register a IDocumentListener, this interface defines 2 methods:

*

*documentAboutToBeChanged

*documentChanged

If we use documentChanged, every time that the user types something in the editor the method will executed.


text:
Q: Reducing the evaporation of water at room temperature Water drops kept on different surface evaporate after a few minutes. How can I reduce the rate of evaporation of these drops? Can I add some additives which suppress evaporation?

A: There are several ways to reduce the rate of evaporation of water. However, first it is important to understand the factors influencing the rate of evaporation:
1) Amount of humidity in the air
2) Speed of air flowing past the water droplets
3) Intramolecular bonding strength
4) Pressure
There are more such as surface area, density, etc. but since we are considering the same drop of same substance these can be ignored. (temperature is there too, obviously)
So what we can do:
Make the air around the drops more humid.
Put the drops in a closed environment, to reduce the speed of air flowing past it. For example, water droplets inside a room will evaporate slower than water droplets placed outside.
There certainly are some additives to help increase the intramolecular bonding strength of a substance. Also, the substance the water droplets are placed on also makes a difference on the rate of evaporation.
Decreasing your altitude will also decrease the rate of evaporation.

A: Depends on what you allow for "additives" .  If you're allowed to coat the surface (as is done when waxing a car), then you can change the surface energy, which changes the surface tension effects.  A given volume of water will evaporate more slowly if it's on a waxed surface and forms a near-spherical shape as opposed to a dull surface where the water droplet forms a flat puddle.  This is because the first case has considerably less surface area.


text:
Q: Postgresql rounds float value with 5 as a last digit so unpredictable So, I found that if I try to round long float value with 5 at the end, I see in the output not what I expect.
This code could sum up my tries:
SELECT to_char(0.7525392242956135::double precision, 'FM0.000000000000000')
UNION ALL
SELECT to_char(0.7525392242956135::numeric, 'FM0.000000000000000')
UNION ALL
SELECT to_char((0.7525392242956135::double precision)::numeric, 'FM0.000000000000000');

And output:
0.75253922429561
0.752539224295614
0.752539224295613

BTW, round() brings same result.
I believe that here should be some proper explanation but unfortunately I can't find it.


text:
Q: Failed to apply plugin [id 'forge'] This is a continuation of this question My initial issue has been solved, but a new one came after.
Following the tutorial mentioned in it, having solved a few errors, I now get an error when I try to run .\gradlew tasks:
FAILURE: Build failed with an exception.

* Where:
Build file 'C:\Users\benji\MinecraftWorkspace\forge-1.7.10-10.13.4.1614-1.7.10-src\build.gradle' line: 18

* What went wrong:
A problem occurred evaluating root project 'forge-1.7.10-10.13.4.1614-1.7.10-src'.
> Failed to apply plugin [id 'forge']
   > You must set the Minecraft Version!
      > java.lang.NullPointerException (no error message)

How do I set the Minecraft version? (1.7.10 in this instance)
Edit to include build.gradle:
buildscript {
    repositories {
        mavenCentral()
        maven {
            name = "forge"
            url = "http://files.minecraftforge.net/maven"
        }
        maven {
            name = "sonatype"
            url = "https://oss.sonatype.org/content/repositories/snapshots/"
        }
    }
    dependencies {
        classpath 'net.minecraftforge.gradle:ForgeGradle:1.2-SNAPSHOT'
    }
}

apply plugin: 'forge'

version = "1.0"
group= "com.yourname.modid" // http://maven.apache.org/guides/mini/guide-naming-conventions.html
archivesBaseName = "modid"

minecraft {
    version = "1.7.10-10.13.4.1614-1.7.10"
    runDir = "eclipse"
}

dependencies {
    // you may put jars on which you depend on in ./libs
    // or you may define them like so..
    //compile "some.group:artifact:version:classifier"
    //compile "some.group:artifact:version"

    // real examples
    //compile 'com.mod-buildcraft:buildcraft:6.0.8:dev'  // adds buildcraft to the dev env
    //compile 'com.googlecode.efficient-java-matrix-library:ejml:0.24' // adds ejml to the dev env

    // for more info...
    // http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html
    // http://www.gradle.org/docs/current/userguide/dependency_management.html

}

processResources
{
    // this will ensure that this task is redone when the versions change.
    inputs.property "version", project.version
    inputs.property "mcversion", project.minecraft.version

    // replace stuff in mcmod.info, nothing else
    from(sourceSets.main.resources.srcDirs) {
        include 'mcmod.info'

        // replace version and mcversion
        expand 'version':project.version, 'mcversion':project.minecraft.version
    }

    // copy everything else, thats not the mcmod.info
    from(sourceSets.main.resources.srcDirs) {
        exclude 'mcmod.info'
    }
}

A: Good day.
For minecraft version 1.7.10.
I was with the same problem, searching the forum in Japanese.
this link Forum
You have to modify the repositories and dependencies of the build.gradle and change the gradle-wrapper.properties to version 5.6.4.
As indicated in this link ForgeGradle-1.2
Contains an example to modify your build.gradle example
build.gradle
buildscript {
repositories {
    mavenCentral()
    maven { url = "https://jcenter.bintray.com/" }
    maven {
        name = "forge"
        url = "https://files.minecraftforge.net/maven"
    }
    maven {
        name = "sonatype"
        url = "https://oss.sonatype.org/content/repositories/snapshots/"
    }
}
dependencies {
    classpath ('com.anatawa12.forge:ForgeGradle:1.2-1.0.+') {
        changing = true
    }
}

gradle-wrapper.properties
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-bin.zip

I made it work
Sorry, my English is very basic. I'm using a translator.

A: pls update the plugin to latest one . For reference check this link and  link.
also try deleting the .gradle folder in your User Home and run it again.

A: I solved this by installing the 'Recommended' version of Forge 1.7.10 instead of the 'Latest'. Simple fix really, although I've already hit another wall.


text:
Q: parameter replacement in a string similar to mysql I am trying to create a user modifiable string that will have already set data to replace certain patches of text
example
dim name1 as string = "John"
dim state as string = "Virginia"
dim idnumb as integer = 122
dim textlist1 as string

textlist1 = "Hello {NAME}, I see you are from {STATE}, and your id number is {ID}."

Ideally I would want to replace these tags with the set strings
I am familiar with
Replace(textlist1, "{NAME}", name1)

my question is: is this the correct way to do this or is there a method more similar to the way we do parameters in MySql

A: Ideally you could use StringBuilder to avoid the reallocation of a new string for every replace.
dim name1 as string = "John"
dim state as string = "Virginia"
dim idnumb as integer = 122
dim textlist1 as StringBuilder = new StringBuilder _
             ("Hello {NAME}, I see you are from {STATE}, and your id number is {ID}.")
textlist1.Replace("{NAME}", name1)

As supposed the StringBuilder approach is not the best for performance related comparisons
This is just a little benchmark executed via LinqPad
Sub Main
    dim name1 as string = "John"
    dim state as string = "Virginia"
    dim idnumb as integer = 122
    dim textlist1 as StringBuilder

    Dim sw = new Stopwatch()
    sw.Start()
    for i = 0 to 100000
        textlist1 = new StringBuilder("Hello {NAME}, I see you are from {STATE}, and your id number is {ID}.")
        textlist1.Replace("{NAME}", name1)
        textlist1.Replace("{STATE}", state)
        textlist1.Replace("{ID}", idnumb.ToString())
    Next
    sw.Stop()
    sw.Elapsed.Dump("StringBuilder.Replace")

    sw = new Stopwatch()
    sw.Start()
    for i = 0 to 100000
        Dim test = "Hello {NAME}, I see you are from {STATE}, and your id number is {ID}."
        Dim test2 = test.Replace("{NAME}", name1)
        Dim test3 = test2.Replace("{STATE}", state)
        Dim test4 = test3.Replace("{ID}", idnumb.ToString())
    Next
    sw.Stop()
    sw.Elapsed.Dump("String.Replace")
End Sub

StringBuilder.Replace
00:00:00.2795878

String.Replace
00:00:00.1642420

So it seems that the cost to allocate a string builder outweight the cost to use a fixed interned string. Of course the memory fragmentation caused by the immutable string behavior is not easily measurable.


text:
Q: Change existing .NET Entity Framework layer from Sql Server to MySql Question : I have an web application that uses .NET Entity Framework library to access a Sql Server Database. What should I do to change it to MySQL ?
Some more details
I tried changing the parameters in app.config and here is my app.config file.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="mysql_db" connectionString="server=localhost;user id=root;password=;database=foo" providerName="MySql.Data.MySqlClient" />
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
     <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
      <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.7.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider>
     </providers>
  </entityFramework>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
</configuration>

I ran the app after using the above file and I get the following error.
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
What else should I change to make it use a MySQL database. I have installed the necessary tools (MySQL, .NET MySQL Connector,  MySQL for Visual Studio).

A: I think you should install  MySQL Connector/Net  and the configure a proper connection string (this is a sample)
Here you can find doc x ef6
        <connectionStrings>
            <add name="MyContext" providerName="MySql.Data.MySqlClient"
                connectionString="server=localhost;port=3306;database=mycontext;uid=root;password=********"/>
        </connectionStrings>
        <entityFramework>
            <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"/>
            <providers>
                <provider invariantName="MySql.Data.MySqlClient"
                    type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6"/>
                <provider invariantName="System.Data.SqlClient"
                    type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
            </providers>
        </entityFramework>


text:
Q: render JSON array in HTTP node.js I have a JSON string that I get from an express GET request which queries a mongo db.
res.write(string) gives me:
[
 {
  "_id":{
     "epc":"30742503C40AE4AE128918B1",
     "audit":109
  },
  "ss":{
     "x":1674,
     "y":96,
     "ts":"2016-05-09T02:24:03.000Z",
     "regions":[
        419,
        416,
        415,
        401
     ]
  },
  "v3":{
     "ts":"1970-01-01T00:00:00.000Z",
     "sts":"2016-05-09T16:10:16.549Z",
     "location":"A002R028S03100100"
  }
 }
]

However, I want to only render certain information from the string, for example: epc, audit, ss.ts, v3.ts and v3.location.
How do I do this?

A: You can use res.json and filter by the desired fields.
res.json({ ss: string.ss.ts });
res.json({ v3: string.v3.ts });
// ... etc

Or you can use res.write and filter the results:
res.write(JSON.stringify(
    string.map(function (result){
         return {ss: result.ss.ts};
    })
));


text:
Q: Setting up multiple node servers using Nginx without subdomains I have been looking all over but haven't found a single person hosting multiple node sites on the same server without using subdomains. I want something like the following...
website.com/app1 -> 127.0.0.1:3000
website.com/app2 -> 127.0.0.1:9000
upstream node {
   server 127.0.0.1:3000;
   keepalive 64;
}

server {
    listen 80;
    server_name  webaddress.com;

    root /var/www/trucks/;

    location /livereload {

        proxy_pass http://localhost:35729;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
    }

    location /app1 {
        rewrite ^/app1/?(.*) /$1 break;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;

        proxy_pass http://127.0.0.1:3000;
        root /var/www/trucks;
}

I have even tried rewriting the request; however, that doesn't appear to be having any effect. If I remove /app1 it works correctly. The closest I have gotten is forwarding to multiple sites but then the local express routes are invalid.

A: I have a working setup as follows:
server {
  listen 8080;
  server_name localhost;
  location / {
    proxy_pass http://localhost:3000;
    proxy_set_header Host $host;
  }
  location /api {
    proxy_pass http://localhost:3001;
    rewrite ^/api(.*) /$1 break;
    proxy_set_header Host $host;
  }
}

A: Have you tried to use the proxy_redirect directive instead of rewrite ?
http://wiki.nginx.org/HttpProxyModule#proxy_redirect

A: *

*Use node-http-proxy as reverse proxy

*Use connect-vhost

*or maybe you can find it here

A: the problem with your configuration its that you are mixin regular http applications proxying with websockets application proxying. There is no need to use rewrite. Here is the simplest configuration I could come up with:
server {
  listen 80;
  index index.html index.htm;

  server_name _;

  proxy_http_version 1.1;
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection "upgrade";
  proxy_set_header Host $host;

  location /node1 {
      proxy_pass http://localhost:8888;
  }
  location /node2 {
      proxy_pass http://localhost:9999;
  }
}

I recommend you redding the websockets related documentation on nginx site:
http://nginx.org/en/docs/http/websocket.html


text:
Q: mySQL populate table with missing rows I have 2 tables for my game script, one is a database of all the weapons ingame (db_firearms) and the other is a list of the weapons in the stores (store_firearms).
db_firearms
(the store field says whether it will appear in stores, 0 = no, 1=yes)
id    name      store
-----------------------
1     Pistol    1
2     Shotgun   1
3     Sniper    0

store_firearms
(weapon field relates to the id of the weapon in db_firearms)
id    city      weapon
-----------------------
1     Miami     1
2     Miami     2
3     New York  2

What I want to do, is populate the store_firearms table with each MISSING weapon from the db_firearms table with store=1 (where city= $city).
What's the best way to do a query for this in mySQL?

A: EDIT Completely botched that first try, using NOT EXISTS works.
INSERT INTO store_firearms (City, Weapon)
SELECT $city, F.Id
FROM db_firearms F
WHERE F.Store = 1 AND NOT EXISTS (
    SELECT * FROM store_firearms WHERE City = $city AND Weapon = F.Id)

If $city were 'New York', this would insert 'New York', 1 into store_firearms

A: try this:
SELECT  ID, Name, Store
FROM    db_firearms
WHERE   STORE = 1 AND
        ID NOT IN
            (SELECT weapon
            FROM store_firearms
            WHERE city = $city)


text:
Q: Different output for the string function strlen() in C The following program gives different results when compiled using gcc compiler, and turbo C
#include<stdio.h>
#include<string.h>

void main()
{
    char* c = "gatecs2017";
    char* p = c;
    printf( "%d", (int)strlen( c + 2[p] - 6[p] - 1 ) );
}

Somebody please explain the working of the program. Also why it generates different results?

A: strlen(c+2[p]-6[p]-1) is translated to strlen(((c + 't') - '2') - 1) = strlen(((c + 116) - 50) - 1), thus, accessing outside of the bounds of the string (undefined behaviour).

A: As clearly explained by others, c + 2[p] - 6[p] - 1 is past the array bounds.
Where exactly, and why different results, here's the redundant explanation that hasn't been given yet:
c+116 is an address on your stack that's address of c + 116 bytes. Then call strlen(address) and you'll get the length of the area starting from c+116 on your stack until there's a '\0'. Since that area is uninitialized or is set differently by different compilers since it's likely somewhere in your executable when loaded to the memory by the kernel running your executable (assuming a kernel ran it), you'll get different results with each compiler-output executable.


text:
Q: Virtualbox on OSX not showing VT-x/AMD-V option I just set up my new Macbook Pro 15" (2017). During the installation and configuration of my Virtualbox VM's I realised, that the "Enable VT-x/AMD-V" option which can be found under Virtual Machine Settings - System - Acceleration is not available on my new Macbook Pro while it was on my previous one (Macbook Pro 15" 2014). Do you have any ideas what might be the reason for that? Both of the Macbooks are running under macOS Sierra 10.12.6 and they both have the latest version of VirtualBox installed. Since I am doing a lot of work in VM's I would be really happy to be able to enable this option.
Would appreciate it a lot if someone could help me.
Regards

A: It seems the option does not show up in VirtualBox any more. However, the "Acceleration" details do show up on the VirtualBox dashboard screen on the right, under the System details.
In my case (on Mac), when "default" paravirtualization-interface option is selected (under Acceleration tab), the VB dashboard shows VT-x to be enabled.

A: In Terminal list all VMs with
vboxmanage list vms

Find yours and then
vboxmanage modifyvm "Your_name_2004" --nested-hw-virt on


text:
Q: Need derived class for java generics declaration I've run into a sticky problem that I can't seem to solve with java generics.  This is a bit complicated, but I couldn't think of a simpler scenario to illustrate the problem...  Here goes:
I have a Processor class that requires a Context.  There are different types of Context; most processors just need any abstract Context, but others require a specific subclass.  Like this:
abstract class AbstractProcessor<C extends Context> {
    public abstract void process(C context);
}

class BasicProcessor extends AbstractProcessor<Context> {
    @Override
    public void process(Context context) {
        // ... //
    }
}

class SpecificProcessor extends AbstractProcessor<SpecificContext> {
    @Override
    public void process(SpecificContext context) {
        // ... //
    }
}

Ok, cool: Processors can declare the type of Context they need, and they can assume the right type will be passed into process() without casting.
Now, I have a Dispatcher class that owns a mapping of Strings to Processors:
class Dispatcher<C extends Context> {
    Map<String, AbstractProcessor<? super C>> processorMap = new HashMap<String, AbstractProcessor<? super C>>();

    public void registerProcessor(String name, AbstractProcessor<? super C> processor) {
        processorMap.put(name, processor);
    }

    public void dispatch(String name, C context) {
        processorMap.get(name).process(context);
    }
}

Ok, so far so good!  I can create a Dispatcher for a specific type of Context, then register a batch of processors that may expect any abstraction of that Context type.
Now, here's the problem: I want the abstract Context type to own the Dispatcher, and derived Context types should be able to register additional Processors.  Here's the closest I could find to a working solution, but it doesn't fully work:
class Context<C extends Context> {
    private final Dispatcher<C> dispatcher = new Dispatcher<C>();

    public Context() {
        // every context supports the BasicProcessor
        registerProcessor("basic", new BasicProcessor());
    }

    protected void registerProcessor(String name, AbstractProcessor<? super C> processor) {
        dispatcher.registerProcessor(name, processor);
    }

    public void runProcessor(String name) {
        dispatcher.dispatch(name, this); // ERROR: can't cast Context<C> to C
    }
}

// this is totally weird, but it was the only way I could find to provide the
// SpecificContext type to the base class for use in the generic type
class SpecificContext extends Context<SpecificContext> {
    public SpecificContext() {
        // the SpecificContext supports the SpecificProcessor
        registerProcessor("specific", new SpecificProcessor());
    }
}

The problem is that I need to declare a generic Dispatcher in the base Context class, but I want the type-variable to refer to the specific derived type for each Context sub-type.  I can't see a way to do this without duplicating some code in each Context subclass (specifically, the construction of the Dispatcher and the registerProcessor method). Here's what I think I really want:
Dispatcher<MyRealClass> dispatcher = new Dispatcher<MyRealClass>();

Is there a way to declare the generic type of an object with the type of the SUBCLASS of the declaring class?
Yes, I can address this problem with a little bit of low-risk casting, so this is mostly an academic question...  But I'd love to find a solution that just works top-to-bottom!  Can you help?  How would you approach this architecture?

UPDATE:
Here's the full source, updated to incorporate Andrzej Doyle's suggestion to use <C extends Context<C>>; it still doesn't work, because Context<C> != C:
class Context<C extends Context<C>> {
    private final Dispatcher<C> dispatcher = new Dispatcher<C>();

    public Context() {
        // every context supports the BasicProcessor
        registerProcessor("basic", new BasicProcessor());
    }

    protected void registerProcessor(String name, AbstractProcessor<? super C> processor) {
        dispatcher.registerProcessor(name, processor);
    }

    public void runProcessor(String name) {
        dispatcher.dispatch(name, this); // ERROR: can't cast Context<C> to C
    }
}

// this is totally weird, but it was the only way I could find to provide the
// SpecificContext type to the base class for use in the generic type
class SpecificContext extends Context<SpecificContext> {
    public SpecificContext() {
        // the SpecificContext supports the SpecificProcessor
        registerProcessor("specific", new SpecificProcessor());
    }
}

abstract class AbstractProcessor<C extends Context<C>> {
    public abstract void process(C context);
}

class BasicProcessor extends AbstractProcessor {
    @Override
    public void process(Context context) {
        // ... //
    }
}

class SpecificProcessor extends AbstractProcessor<SpecificContext> {
    @Override
    public void process(SpecificContext context) {
        // ... //
    }
}

class Dispatcher<C extends Context<C>> {
    Map<String, AbstractProcessor<? super C>> processorMap = new HashMap<String, AbstractProcessor<? super C>>();

    public void registerProcessor(String name, AbstractProcessor<? super C> processor) {
        processorMap.put(name, processor);
    }

    public void dispatch(String name, C context) {
        processorMap.get(name).process(context);
    }
}

A: It sounds like your problem is that you need the generics to refer to the specific exact type of the subclass, rather than inheriting the generic definition from the parents.  Try defining your Context class as
class Context<C extends Context<C>>

Note the recursive use of the generic parameter - this is a bit hard to wrap one's head around, but it forces the subclass to refer to exactly itself.  (To be honest I don't quite fully get this, but so long as you remember that it works, it works.  For reference, the Enum class is defined in exactly the same way.)  There's also a section in Angelika Langer's Generics FAQ that covers this.
This way the compiler gets more information about exactly what types are permissable, and should allow your case to compile without the superfluous casting.
UPDATE: Having thought about this a bit more, my above comments were along the right track but were not entirely on the money.  With self-recursive generic bounds, as above, you can never really use the actual class you define them on.  I'd actually never fully noticed this before, as by luck or judgement I'd apparently always used this in the right point of the class hierarchy.
But I took the time to try and get your code to compile - and realised something.  The class with these bounds can never be referred to as itself, it can only ever be referred to in the context of a specific subclass.  Consider the definition of BasicProcessor for example - Context appears ungenerified in the generic bounds for AbstractProcessor.  To prevent a raw type from appearing, it would be necessary to define the class as:
class BasicProcessor extends AbstractProcessor<Context<Context<Context<...

This is avoided with subclasses because they incorporate the recursiveness in their definition:
class SpecificContext extends Context<SpecificContext>

I think this is fundamentally the problem here - the compiler cannot guarantee that C and Context<C> are the same types because it doesn't have the required special-casing logic to work out that the two are actually an equivalent type (which can only actually be the case when the wilcard chaining is infinite, since in any non-infinite sense the latter is always one level deeper than the first when expanded).
So it's not a great conclusion, but I think in this case your cast is needed because the compiler is unable to derive the equivalence for itself otherwise.  Alternatively, if you were using a concrete subclass of Context in a similar position the compiler is able to work it out and this would not be a problem.
If you do happen to find a way to get this working without casting or having to insert a dummy subclass then please report back - but I can't see a way to do that, that would work with the syntax and semantics available to Java's generics.


text:
Q: PackageManagement Cmdlets are not recognized by powershell Hi there i have a problem on a windows server 2016. I can't install any packages with the PackageManagement Cmdlets. Im always getting the error that it's not recognized as a cmdlet or function if i use them.
i tired importing the module which works. But i still cant use any command. The Error is in german and im not sure it will help you that much.
This happens when i try to install a module :
PS C:\Windows\system32> install-module powershellget
PackageManagement\Get-PackageProvider : Die Benennung "PackageManagement\Get-PackageProvider" wurde nicht als Name
eines Cmdlet, einer Funktion, einer Skriptdatei oder eines ausführbaren Programms erkannt. Überprüfen Sie die
Schreibweise des Namens, oder ob der Pfad korrekt ist (sofern enthalten), und wiederholen Sie den Vorgang.
In C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\1.0.0.1\PSModule.psm1:7277 Zeichen:26
+ ...        $nugetProvider = PackageManagement\Get-PackageProvider -ErrorA ...
+                             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (PackageManagement\Get-PackageProvider:String) [], CommandNotFoundExcept
   ion
    + FullyQualifiedErrorId : CommandNotFoundException

PackageManagement\Get-PackageProvider : Die Benennung "PackageManagement\Get-PackageProvider" wurde nicht als Name
eines Cmdlet, einer Funktion, einer Skriptdatei oder eines ausführbaren Programms erkannt. Überprüfen Sie die
Schreibweise des Namens, oder ob der Pfad korrekt ist (sofern enthalten), und wiederholen Sie den Vorgang.
In C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\1.0.0.1\PSModule.psm1:7291 Zeichen:40
+ ... ailableNugetProviders = PackageManagement\Get-PackageProvider -Name $ ...
+                             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (PackageManagement\Get-PackageProvider:String) [], CommandNotFoundExcept
   ion
    + FullyQualifiedErrorId : CommandNotFoundException


text:
Q: Graylog2 Server unable to connect to ElasticSearch I'm trying to install GrayLog2 on my Ubuntu server to manage all logs from multiple location.
I have install Mongodb, Java and Elastic Search but it failed to detect the elastic search when I run
sudo java -jar /opt/graylog2-server/graylog2-server.jar --debug
Error from graylog
2014-12-11 03:29:23,700 INFO : org.elasticsearch.transport - [graylog2-server] bound_address   {inet[/0:0:0:0:0:0:0:0:9350]}, publish_address {inet[/10.175.112.147:9350]}
2014-12-11 03:29:26,739 WARN : org.elasticsearch.discovery - [graylog2-server] waited for 3s and no initial state was set by the discovery
2014-12-11 03:29:26,739 INFO : org.elasticsearch.discovery - [graylog2-server] graylog2/MNpZ3HLXRbaKkpw--872Mw
2014-12-11 03:29:26,739 DEBUG: org.elasticsearch.gateway - [graylog2-server] can't wait on start for (possibly) reading state from gateway, will do it asynchronously
2014-12-11 03:29:26,740 INFO : org.elasticsearch.node - [graylog2-server] started
2014-12-11 03:29:26,886 DEBUG: org.elasticsearch.discovery.zen - [graylog2-server] filtered ping responses: (filter_client[true], filter_data[false]) {none}
2014-12-11 03:29:29,897 DEBUG: org.elasticsearch.discovery.zen - [graylog2-server] filtered ping responses: (filter_client[true], filter_data[false]) {none}
2014-12-11 03:29:31,783 ERROR: org.graylog2.Main -
ERROR: Could not successfully connect to ElasticSearch. Check that your cluster state is not RED and that ElasticSearch is running properly.

More infomation
ElasticSearch Health Status
curl -XGET 'http://localhost:9200/_cluster/health?pretty=true
{
"cluster_name" : "graylog2",
"status" : "green",
"timed_out" : false,
"number_of_nodes" : 1,
"number_of_data_nodes" : 1,
"active_primary_shards" : 0,
"active_shards" : 0,
"relocating_shards" : 0,
"initializing_shards" : 0,
"unassigned_shards" : 0
}

Graylog2Server Version: 0.20.2
ElasticSearch Version: 0.90.0
Thanks


text:
Q: passing data by POST method between views in asp.net I have data in a particular view page(collected from the user) which I need to send to another view page which has a form needing this data. Now I can use:-
1.  post method of javascript(jquery)
$().redirect('/Events/Create', {'arg1': 'value1', 'arg2': 'value2'});

or

*

*A form:-

$('#inset_form').html(' < form action="/Events/Create"
  method="post"style="display:none;">< input type="text" name="lat"
  value="' + latitude + '" />< /form>');
document.forms['vote'].submit();

Now my question is, which method should be chosen?
Also, the '/Events/Create' page has form in the following way:-
@using (Html.BeginForm()) {
  @Html.AntiForgeryToken()
  @Html.ValidationSummary(true)

       @Html.LabelFor(model => model.lat)

        @Html.EditorFor(model => model.lat)---------> THIS field accepts the POSTed data
        @Html.ValidationMessageFor(model => model.lat)

       ....OTHER INPUT FIELDS.....

        <input type="submit" value="Create" />

}

So, my next question is how do I make the text box 'lat' created by @Html.EditorFor in the form show the POSTed data as its default value. Then, the user can fill other fields and then submit the form.

A: As per HTTP standards, if a call is not changing the state of the website (i.e. data), you should use a GET request. This means you should provide the user with a link including the proper query string to populate the form on the /Events/Create page.
Also, keep in mind you never send data from view to view in MVC. Everything goes through a controller action so make sure your "Create" action on the "Events" controller accepts the proper arguments to populate the form for submission. If the Model.lat variable has a value in it when rendering the view, the text box will be prepopulated with that value.

A: Why do you want to POST the data to the second form? If you want to show the form and load it with default values, create a GET action method for it and pass the default values in the url. Although there's nothing stopping you having two POST methods for the same view, the normal approach would be to load the form using a GET, then POST back the data after editing.
 [HttpGet]
 public ActionResult Create(string lat)
 {
     MyView view = new MyView();
     view.lat = lat;
     View(view);
 }

 [HttpPost]
 public ActionResult Create(MyView view)
 {
     //process posted data after editing
 }

The view object here is a ViewModel class containing properties for the data that you will edit on the form. Make your View strongly typed to this ViewModel type.
To invoke the GET method from your jQuery (above):
window.location = "Events/Create?lat=myValue";


text:
Q: How to force SurfaceView to occupy specific section othe screen I am trying to use SurfaceView. So I created a SurfaceView widget in the layout file as shown below in the code. The problem I have is how to set a weight to the SurfaceView?
As shown below in the code I set :
android:layout_weight=".4"

but still the SurfaceView occupies the eintire screen, what i want is to make the SurfaceView occupies only 40% of the screen. I also refered to a post in this link SurfaceView in Layout
but it does not show how to set the weight to the SurfaceView from the xml file.
Please let me know how to set weight to the SurfaceView from the xml file.
code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.surfaceview_00.MainActivity">

<SurfaceView
    android:id="@+id/mainActivity_surfaceView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight=".4"/>
</RelativeLayout>

update:
I also tried the below code but still i got one SurfaceView that occupies the whole screen. I expected after running the below code is to have two SurfaceViews each occupies half of the screen, but i got only one
code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.surfaceview_00.MainActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="2">

    <SurfaceView
        android:id="@+id/mainActivity_SurfaceView1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <SurfaceView
        android:id="@+id/mainActivity_SurfaceView2"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>
</LinearLayout>

</RelativeLayout>

A: RelativeLayout does not support layout_weight. You need to use the LinearLayoutfor that.
Read more at https://developer.android.com/guide/topics/ui/layout/linear.html
But basically change it to something like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools"
      android:id="@+id/activity_main"
      android:layout_width="match_parent"
      android:orientation="vertical"
      android:layout_height="match_parent"
      android:weightSum="1">

         <SurfaceView
              android:id="@+id/mainActivity_surfaceView"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_weight=".4"/>

</LinearLayout>

A: android:layout_weight is only used by LinearLayout. Since you use RelativeLayout it is ignored.

A: SurfaceView doesn't belong to App's view hierarchy. It creates separate layer on the background, and position it depending on its size. All other views are displayed over SurfaceView. To do what you want you need to use TextureView.


text:
Q: Php array to json encode not working I have a ajax connection to my json.php file and its not working... do you have any idea what is going on?
is it my $output variable is it not convertible to json  can it be my ajax?!
any help will be greatly appreciated. PS: when i click on a city that does not exist.. it does output the $output variable.When i click on a city that doe exist I get nothing.
It`s killing me.
 var_dump($output) {if it is not encoded} is:
    array (size=1)
  0 =>
    array (size=4)
      0 =>
        object(SimpleXMLElement)[9]
      1 =>
        object(SimpleXMLElement)[8]
      2 =>
        object(SimpleXMLElement)[7]
      3 =>
        object(SimpleXMLElement)[10]

json.php file:
<?php

if(isset($_POST['city'])){
    $city = $_POST['city']; //checks if variable city is set if not it will be set as default
    var_dump($city);
}else{
    $city = 'New York';

}
//loads data as simple xml
$result = "http://api.wunderground.com/api/KEY/geolookup/conditions/q/ro/$city.xml";
$xml = simplexml_load_file($result);
#echo htmlspecialchars($result, ENT_QUOTES, 'UTF-8');
$place = $xml->location->city; //gets the city name
#var_dump($place);
if(!empty($place)){ //checks if city exits
  foreach($xml->current_observation as $item){
    $current = (string)$item->weather;
    $temperature = (string)$item->temp_c;
    $time = (string)$item->local_time_rfc822;
    $wind = (string)$item->wind_string;
    $humidity = (string)$item->relative_humidity;
    $output[] = array($time, $temperature, $current, $wind);

}

    }
}else{
    $output = 'No results found, please try a different city.';  //if variable $place is empty it will print this
}

header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('data' => $output),true);
?>

And jQuery file:
 $(document).ready(function() {
    $('li').click(function(){
            var city = $(this).text(); //get the li content as variable city
            $.ajax({

                type : 'POST',      //sending data method
                url : 'json.php',
                data : {city:city}, //data to be sent
                dataType: 'json',
                success : function(data){
                $("#result").html(data);
            }
            });

    });
});

EDIT 1:
I have updated my code in such a way that my output is json encoded and equal to
{"data":[["Thu, 24 Sep 2015 02:00:58 +0300","19.3","Clear","From the West at 1.6 MPH Gusting to 2.5 MPH"]]}

I think the problem now is in my AJAX(I am a new user of jQuery) I get no info printed when I Click on a city.

A: Many Times it occurs when our content of the array is not Encoded. Generally we use UTF-8 Encoding.
So, To Solve this issue you need to add this,
mysqli_set_charset($con, 'utf8');
Just after the connection.

A: Take a  look at the following tutorial: https://lostechies.com/seanbiefeld/2011/10/21/simple-xml-to-json-with-php/
You'll do str_replace and trim then encode the data for the web.


text:
Q: Keep showing the tooltips in telerik's radgrid I have a radgrid that displays some (normal) tooltips for headers and cell content.
Take for example the header tooltip for this column:
<telerik:GridBoundColumn
            HeaderText="<%$ Resources:IFW_Global, FamilyName  %>" HeaderTooltip="<%$ Resources:IFW_Global, FamilyNameTtip  %>" UniqueName="column"
            AllowFiltering="False" DataField="LastName"
</telerik:GridBoundColumn>

And a data cell tooltip, set in code behind:
Dim item As GridDataItem = CType(e.Item, GridDataItem)
item("DocumentTypeCode").ToolTip = "customdoctooltip"

The tooltips stays visible for only about 5 seconds on mouseover and then it dissapears.
I want all the tooltips to remain visible onmouseover without dissapearing.
How would I do this? I'm looking for a simple solution.

A: here is some information.  I used to use Telerik a ton and I went straight to their forums when I had a question.  They are quick to answer.  I just searched your question on Telerik and found this:

you can set the AutoCloseDelay property to 0 which will prevent the
  tooltip from hiding after an interval.

A: I've solved this by adding this RadToolTipManager to my masterpage:
<telerik:RadToolTipManager ID="RadToolTipManager1" runat="server" Position="BottomRight" AutoTooltipify="true" AutoCloseDelay="0" OffsetY="10">
</telerik:RadToolTipManager>

AutoTooltipify="true" converts the standard tooltips to radTooltips.
AutoCloseDelay="0" gets me the behaviour that I want.


text:
Q: How many bits of an int match the precsion of a 32 bit floating point? I am trying to compare the timing and cost of synthesizing floating point operators vs integer operators, but in order to properly compare them I need to use the same relative amount of bits for the integer operation that is represented in a 32 bit floating point number. Appreciate any help!

A: An IEEE 32 bit floating point has one sign bit, eight exponent bits, and 23 mantissa bits. So an int with 24 bits has the same expressive power for precision, but of course the whole point of a float is that you have extra range. You can emulate the floating point in software if you want, this is likely to be valuable as a learning exercise. Or you can use fixed point ints with as many bits as you want after the binary point, but you'll need 24 to represent 1.xxxx as accurately as a float. It's not clear what you intend to do.


text:
Q: Jquery datatable dropdown filter in header sorts I wanted to create a datatable with dropdown list box on its header which filters the rows to be displayed according to the selected column in the box. I modified the examples here column filtering example to display the dropdown list box in the header
   /* Add a select menu for each TH element in the table footer */
   //   $("tfoot th").each( function ( i ) {
      $("thead th").each( function ( i ) {
       ...

It works fine but it performs sorting when I click the dropdown list box. Is it possible to disable the sorting when I'm performing actions on the dropdown and just trigger sorting when I clicked anywhere in the cell which is not part of the dropdown.
Thanks.

A: $("thead th").each( function ( i ) {
    this.innerHTML = fnCreateSelect( oTable.fnGetColumnData(i) );
    $('select', this).change( function () {
        oTable.fnFilter( $(this).val(), i );
    } );
    $('select', this).click( function (event) {
        event.stopPropagation();
    } );
} );

A: Don't handle the onChange event for the select or remove the sort call. You can bind a click event in the cells, I believe. If not, format your table to include an anchor tag in each cell that you can handle the click event on.


text:
Q: TCPDF/PHP & Fonts: Uppercase Numbers (Descent numbers? Old style?) I'm given a special font with numbers like that:

As you can see on the 3 for example, some numbers descent below the baseline. What I like to achieve is, that these numbers don't go below the line and that it looks like this:

In Word this can be easily set in the character settings for the same font. How can one render digits in TCPDF like this? I'm totally stuck there and have no clue how to proceed.
Cheers for any help!

A: It can be done, but it's messy... In principle you'll have to do something like this:

*

*Break your text output into substrings where it changes from letters to numbers - probably using preg_split().

*Output the text with Cell() or MultiCell(), up to the point where the letters end and the numbers start.

*Raise the current Y-position using SetY().

*Output the numbers.

*Reset the Y-position to where it was before step 3 (assuming that you haven't crossed a line break).

*Repeat as necessary....

Of course, this raises the baseline for all numbers - from your sample it looks as if you need to raise the baseline for just some of them, which will be even more fiddly.
Good luck! :-)


text:
Q: How to detect active appearance for NSView or for its parent NSWindow? All native controls have different appearance when their parent window is active or inactive. How should we check this state in custom components e.g. while rendering a button cell?
We could inspect controlView.window's properties like isMainWindow and isKeyWindow, but they don't cover all cases. For instance, if you open one window of the app on the Desktop and another in a full-screen Space, only one of them can be key or main according to public APIs. However, standard controls seem to render them as active in both Spaces:

Please note how toolbar buttons in both Safari windows are rendered as active. How do we achieve the same behavior?

A: Fortunately, SwiftUI allows to inherit a new magic property from the Environment:
/// Window state.
@Environment(\.controlActiveState)
var windowState: ControlActiveState

This is an official solution. Cheers!


text:
Q: Which method is preferred when prototyping in JavaScript? Here's a contrived example:
I want to divide two numbers and I need to write a method for doing so. I could write something like this:
function divide(dividend,divisor) {
    return dividend/divisor;
};

//Assign the result of the divide function to an element on the page.
$(".firstanswer").html(divide(6,2));

I could also write something like this:
Number.prototype.dividedBy = function (divisor) {
    var dividend = this;
    return dividend/divisor;
};

var six = 6;
var two = 2;
$(".secondanswer").html(six.dividedBy(two));

Both methods yield the same answer, so what I'd like to know is this:
What are the advantages or disadvantages to using either method. Is there a significant performance (load/run time) difference? Is one more reusable than the other in terms of memory impact? What about ease of comprehension? Ultimately, for an example as simplistic as this, does it matter?
I've also created a Fiddle because code is better.

A: There is no disadvantage in first method (except for different syntax)
In second method, you risk the implementation, what if it becomes part of Number or Math object or some other third party library having same function name :)
Though normally to avoid it, this is done:
Number.prototype.dividedBy = Number.prototype.dividedBy || function (divisor) {
    var dividend = this;
    return dividend/divisor;
};

This way, you say, if there is that function already present use that else create my own.

For more details, check out (yet another great article by @Kangax as always)

*

*Extending built-in native objects. Evil or not?


text:
Q: Maven lifecycle wrong order I deploy my application during the package phase:
<plugin>
    <groupId>org.glassfish.maven.plugin</groupId>
    <artifactId>maven-glassfish-plugin</artifactId>
    <version>2.1</version>
    <executions>
        <execution>
            <id>gf-redeploy</id>
            <goals>
                <goal>redeploy</goal>
            </goals>
            <phase>package</phase>
        </execution>
    </executions>
</plugin>

And run some integration-tests in the integration-test phase
<plugin>
    <groupId>com.lazerycode.jmeter</groupId>
    <artifactId>jmeter-maven-plugin</artifactId>
    <version>1.10.1</version>
    <executions>
        <execution>
            <id>jmeter-tests</id>
            <phase>integration-test</phase>
            <goals>
                <goal>jmeter</goal>
            </goals>
        </execution>
    </executions>
</plugin>

However when I look into my console, the JMeter test is executed before the redeploy. How is that possible? Did I miss something?


text:
Q: Array content isn't updated after System.arraycopy() Maybe someone can tell me why this does not work and why the data in array is not updated after calling setListData??
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

      list1 = (ListView) findViewById(R.id.ListView01);
      list1.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, array));

      final EditText EditMessage = (EditText) findViewById(R.id.editTextWebSite);
      Button button = (Button) findViewById(R.id.button1);

        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                String website = EditMessage.getText().toString();

                //String returnString = loaddata(website);
                Toast.makeText(v.getContext(),
                        "Updating Information",
                        Toast.LENGTH_LONG).show();
                setListData();

                BaseAdapter la = (BaseAdapter)list1.getAdapter();
                ((BaseAdapter) la).notifyDataSetChanged() ;

                Toast.makeText(v.getContext(),
                        "Updated",
                        Toast.LENGTH_LONG).show();

            }
        });

private void setListData()
    {
        String array2[] = { "Iphone", "Tutorials", "Gallery", "Android",    "item 1", "item 2", "item3", "item 4" };
         System.arraycopy(array, 0, array2, 0, array.length);
    }

A: Because of you swapped the params for
System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length).
As you can see, it is first the source and then the destination.
Currently you are copying the content of array into the local temporary array2.


text:
Q: How to display all rake taks that are up-to-date or pending? I have a rakefile with several tasks and some of them take a lot of time (hours or days).  I usually run some tasks, and left the rest to be executed in another day.  How can I list the status of all the tasks?  I am imaging something like rake --status that shows the pending and up-to-date tasks?  I do not want to write a separate to-do list to record the status of tasks.  Is there a solution for this?

A: I can run the Rakefile as any other ruby script.  Then I can access the tasks by using the following code:
Rake.application.tasks.each do |tsk|
   puts "#{tsk.name}: #{tsk.needed?}"
end

This shows the status of each task.
Also, the class Task can be extended to record the status of tasks in a database, and to provide more information about the execution of tasks.


text:
Q: Auto sort a certain range in excel - VBA I am trying to create a code which automatically sorts a column when I add a new value at the bottom or change an existing value. So I have values ranging from E3:E210; and if I add or change a value at E211. I want it to automatically sort that range (E3:E210) or if I change a value at E205. I also want it to go to the cell that it was sorted to (if possible). So If I add a value at E211 and it sort to let's say E150. I want it to select that cell so I basically stay on that cell.
This is all the code I am running on the sheet:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Dim Rng As Range
Set Rng = Range(Cells(3, 6), Cells(500, 7))
Dim Intersection
Set Intersection = Application.Intersect(Target, Rng)

If Target.Cells.Count = 1 Then
    If Not Intersect(Target, [B2]) Is Nothing Then _
        Range("E:E").Find(vbNullString, [E3], , , , xlNext).Select
End If

If Not Intersection Is Nothing Then
    If IsNumeric(Selection.Value) And Selection.Value <> "" Then
        If (GetAsyncKeyState(vbKeyRButton)) Then 'right mouse button
            Selection.Value = (Selection.Value + 1)
            Cells(Selection.Row, 1).Select
        End If
    End If
End If

End Sub

Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
    Dim Rng As Range
    Set Rng = Range(Cells(3, 6), Cells(500, 7))
    Dim Intersection
    Set Intersection = Application.Intersect(Target, Rng)

    If Not Intersection Is Nothing Then
    Cancel = True
    End If
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
Target.EntireColumn.Sort Key1:=Target, Order1:=xlAscending, Header:=xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom
End Sub

The last part is my attempt to do autosort (with the help of forums). It does sort the values. But it does not sort a certain range and it does not stay on the cell. If anyone can help, much appreciated!

A: If you want to automatically sort on any change in the column, something like:
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim myRng As Range
    Dim S As String
Set myRng = Cells.Columns(5) '<--change to column you want to sort
If Not Intersect(Target, myRng) Is Nothing Then
    Application.EnableEvents = False
    S = Target.Text
    myRng.Resize(columnsize:=3).Sort key1:=myRng, order1:=xlAscending, Header:=xlNo, Orientation:=xlSortColumns
    myRng.Find(what:=S, LookIn:=xlValues, lookat:=xlWhole, MatchCase:=True).Select
    Selection.Show
    Application.EnableEvents = True
End If

End Sub

(I am not entirely certain that the .Show statement is required).
EDIT: changed to sort columns E:G together


text:
Q: Rules about relationships in a Domain Object Is there such of a constraint that can validate relationships in a Domain object?
For example if you had a Meeting object with Participants and an Organization. Is there a way that you could make the Meeting contain a constraint that the Participants were a member of the Organization object?

A: Besides the fact you can author your own types of constraints, you also have the ability to write your own validation routines using validator. The Grails documentation covers a lot of the details but a quick example would be:
class Meeting {
  static belongsTo = [org: Orginization]
  static hasMany = [partcipants: Person]
  ...
  static constraints {
    org(validator: {val, obj ->
      if (obj.partcipants.find{ it.org.id != val.id }) return 'some.message.code'
    })
  }
  ...
}

Keep in mind the above is off the top of my head (and I have a head cold) but it should point you in the right direction.


text:
Q: Automatically start scren recording in SuperTuxKart I would like to set up SupertTuxKart to automatically start screen recording when it is launched. I saw documentation on the in-game screen recorder, and was hoping to use that since initial experiments yield a much higher framerate than my other solution, x11grab via ffmpeg.
When the game starts, I can manually initiate the screen recording by pressing ctrl+PrintScreen. However, I wish to automate this whenever the game is launched, so I launch it as follows:
(sleep 5 && xdotool key 'ctrl+Print' &); supertuxkart

This results in a png formatted screenshot, not a video, appearing in ~/.local/share/supertuxkart/screenshots/ (I verified that manually pressing ctrl+Print does result in a .webm recording).
Where am I going wrong?


text:
Q: Could not locate Gemfile or .bundle/ directory I am trying to use docker on with a rails apps. This setup works on other developers machines, but not mine. I can get the mysql to "up" but not the rails app. I've been at it for 2 days now.
I'm on windows 10 home using the Docker Quickstart Terminal. I was able to run this about a year ago on the same machine.
Here is my Dockerfile:
FROM ruby:2.5.3

ARG workdir=/bundle-api

RUN apt-get update -qq && apt-get install -y build-essential netcat graphviz
RUN mkdir -p ${workdir}

WORKDIR ${workdir}

ADD Gemfile ${workdir}/Gemfile
ADD Gemfile.lock ${workdir}/Gemfile.lock

RUN bundle install

ADD . ${workdir}

Here is my docker-compose file:
version: '2'
services:
  db:
    image: mysql:5.7
    container_name: bundle-mysql
    volumes:
      - db_data:/var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: bundle_api_pwd
      MYSQL_DATABASE: bundle_api_dev
      MYSQL_USER: bundle_api
      MYSQL_PASSWORD: bundle_api_pwd
    ports:
      - "3306:3306"
  web:
    build: .
    container_name: bundle-rails
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    volumes:
      - .:/bundle-api:cached
      - bundle_cache:/bundle_cache
    ports:
      - "3100:3000"
    environment:
      DB_HOST: db
      DB_USERNAME: root
      DB_PASSWORD: bundle_api_pwd
      BUNDLE_PATH: /bundle_cache
      GEM_HOME: /bundle_cache
      GEM_PATH: /bundle_cache

    depends_on:
      - db
    stdin_open: true
    tty: true
  bundle_cache:
    image: busybox
    volumes:
      - bundle_cache:/bundle_cache
volumes:
  db_data:
  bundle_cache:

To start fresh I run this:
docker-compose build --no-cache
Everything seems to work fine. I can see all the gems install.
Once it runs, I run: docker-compose up and get this error.
bundle-rails    | Could not locate Gemfile or .bundle/ directory
bundle-rails exited with code 10

            Name                           Command                State                  Ports
------------------------------------------------------------------------------------------------------------
bundle-backend_bundle_cache_1   sh                               Exit 0
bundle-mysql                    docker-entrypoint.sh mysqld      Up        0.0.0.0:3306->3306/tcp, 33060/tcp
bundle-rails                    bundle exec rails s -p 300 ...   Exit 10

A: Looks like you are setting BUNDLE_PATH in the docker-compose.yml but you don't set it in the Dockerfile. That means you gems will be installed to /usr/local/bundle but then when you start the container ruby looks in /bundle-cache for the gems.


text:
Q: how to include pulltorefresh library in project? I have trouble including the PullToRefresh library in my android project. Its distributed as a source code form on Github and I have imported it as a separate project in Eclipse. File -> Import Existing Code Into Workspace. Compile it, then added it to my project's build path. (Project->Properties->Java Build Path->Project Tab. Problem is, that it does not get compile into the dex file in the apk. I have used dex2jar to verify the issue exists. Anyone used this lib before? Am I importing it correctly?
UPDATE: It appears that the R.class in not being benerated in the library .jar file. Anyone knows why that might be the case?

A: Its likely a library project
Do the following
1)You need to download the full folder (https://github.com/johannilsson/android-pulltorefresh/tree/master/pulltorefresh)
2) Import to eclipse as a project (file>import>existing android code)
3) In your app, right click> Properties> Android(down the left side pane)> add library(bottom right)
4) Select the library and it should work


text:
Q: Book with time travel and aliens using collars to mind control I'm looking for the title of a book series I read at as child.
The story starts on a future Earth in which people are sent back to live in medieval times. However, unknown to the future Earth, the old Earth is now ruled by aliens who capture all time travelers and use them as slaves by controlling them with collars. Bronze collars are for the working class, silver collars are for telepaths and gold collars are for humans collaborating with the aliens.
I never finished these books as a child and now it's been nagging me how they end.

A: This would be Julian May's series Saga of Pliocene Exile. It matches your query in pretty good detail: Time travel, aliens are both there.  The control is by means of torcs in bronz, silver and gold. The only difference is that it's not to Medieval times, but much further back to the Pliocene era.
The most-used US cover (by Michael Whelan) of the first book:

Besides the books of this series, there is a larger n-ology of books (Galactic Milieu) set mainly in the near future which sets up the background to the Pliocene books.


text:
Q: Extracting Specific files from large zip thru python I have a big zip with 300.000+ files in with all directories and subdirectories
On the other hand, I have a list of 1200 files I need to extract from the zip.
This list has the dir path and file name in it as one (see exp)
Exp:
/var/db/bla/file.ext
At this moment, I use the following code to search and extract the files from the zip (with keeping the timestamp). It works, but it's really slow. Is there a better way? Now it's reading all the files from the zip, and if it's a match, it extracts it.
Is there maybe a way to give the file location (thru the list) directly and extract it without making a list of all the files in it?
files = df2.drop_duplicates().drop_duplicates().values.tolist()
pbar_max = (len(files))
pbar = tqdm(total=int(pbar_max))

##
for count, i in enumerate(files):

    for item in (f for f in zip_file.filelist if i in f.filename):

        e = item.date_time
        gettime = "%s/%s/%s %s:%s" % (e[0], e[1], e[2], e[3], e[4])

        #print(item.filename)
        zip_file.extract(item.filename, directory)
        filep = directory + item.filename
        timearry = time.mktime(time.strptime(gettime, '%Y/%m/%d %H:%M'))
        os.utime(filep, (timearry, timearry))

        pbar.update(1)

pbar.close()

Hope somebody has a clever Idea, thanks

A: There is a good chance your script is spending most of the time in zip_file.extract, so there may not be much you can do. You would need to run the script through a profiler to know for sure.
That said, you may be able to make things better by restructuring the two loops. At the moment you the outer loop is iterating through zip_file.filelist 1600 times. That outer loop can be eliminated completely, like this
# store the file list as a set
files = set( df2.drop_duplicates().drop_duplicates().values.tolist() )

# now only have to iterate the zip once
for item in (f for f in zip_file.zipinfo if f.filename in files):
    e = item.date_time
    gettime = "%s/%s/%s %s:%s" % (e[0], e[1], e[2], e[3], e[4])

    #print(item.filename)
    zip_file.extract(item.filename, directory)
    filep = directory + item.filename
    timearry = time.mktime(time.strptime(gettime, '%Y/%m/%d %H:%M'))
    os.utime(filep, (timearry, timearry))

    pbar.update(1)

You will need to test the code to see if that makes much difference.
[EDIT]
Here is a worked example
First create a zip file
$ touch alpha beta gamma delta
$ zip test.zip alpha beta gamma delta
updating: alpha (stored 0%)
updating: beta (stored 0%)
updating: gamma (stored 0%)
updating: delta (stored 0%)

Now walk through the zip file
import zipfile

# want to match against these three names
files = { 'alpha', 'gamma', 'omega' }

with zipfile.ZipFile('test.zip') as zip_file:
    for item in (f for f in zip_file.filelist if f.filename in files):
        print(item.filename)

outputs
alpha
gamma

Note that this will only work if you know the exact filename in the zip file you match against. Your code was doing a substring match.


text:
Q: Remove last decimal value I am trying to remove the last decimal point from a floating value but I am not sure how to do this. For example: 3.567, I want the result to be 3.56.
I am trying to do this but it rounds off the value, that is, the value changes to 3.40 instead. I do not want this. How do I solve it to remove the last or 3rd decimal value ?
float value = 3.567f;
value = Mathf.Round (value * 10f) * 0.1f;


text:
Q: python extract links from an RSS feed I am using a URL which is http://www.sec.gov/Archives/edgar/monthly/xbrlrss-2012-02.xml and parsing it with feedparser-5.1.3 using the command:
g = feedparser.parse('http://www.sec.gov/Archives/edgar/monthly/xbrlrss-2012-02.xml')
If you go to that URL you will see that there are many zip files per link in a list.
My objective is to find and extract all the links for the zip files.
By putting the command: g['feed'] in python Shell i get the feed.
The webinar(slide 8) offers some code for this purpose which i am unable to utilize.
An excerpt i put to this post:
for item in feed.entries:
    print( item[ "summary" ], item[ "title" ], item[ "published" ] )
    try:
        # Identify ZIP file enclosure, if available
        enclosures = [ l for l in item[ "links" ] if l[ "rel" ] == "enclosure" ]

How can i do it?

A: Change name from g to feed and you will can use this code.


text:
Q: Override parent's max-width from child css I am using VuePress for docs and for the home page I wanted something more customizable. My problem is that the class .theme-default-content has a max-width of 740px, if I override this class and change it's max-width, it'll mess up all the other pages too not only the main page, since on VuePress all pages are linked to the main theme.
What I want is the child class that'll be inside header to extend with width: 100% of the page.
Currently this would doesn't work, no matter how much I try it'll never override it. I could make it absolute but that'll create even more problems.
Is there a way to override the parent's property from inside?

A: You cannot override the parent styles with child styles in CSS, as there is no parent selector in CSS.
However, you don't need to override anything to give the child element a width that spans 100% of the viewport; simply use the viewport unit vw as width: 100vw:

body {
  margin: 0;
}

.outer {
  height: 100px;
  width: 200px;
  max-width: 200px;
  background: red;
  padding: 25px;
}

.inner {
  height: 100px;
  width: 100vw;
  background: blue;
}

Notre that if you have padding on the parent, you may want to subtract this from the width of the viewport (so that there are no horizontal scrollbars). This can be done with calc():

body {
  margin: 0;
}

.outer {
  height: 100px;
  width: 200px;
  max-width: 200px;
  background: red;
  padding: 25px;
}

.inner {
  height: 100px;
  width: calc(100vw - 25px);
  background: blue;
}


text:
Q: Is it worth adding a new sorting button named "Last Activity" to the Users page? Sometimes I need to view who is online, but clicking his/her profile one by one seems to be tedious/cumbersome task. It will be convenient if there is a new button "Last Activity" providing us with a rectangular list of users and the seen values (e.g., 20 seconds ago, just now, etc). Viewing 50 users in one page is also helpful, I believe.
Is it worth adding a new sorting button named "Last Activity" to the Users page?

A: I would suggest that the basic premise of this question is flawed.

[…] I need to view who is online […]

This is not a "need" in the sense that it is required for proper use of the site. In fact i would go so far as to suggest that if this is a "felt need" you are probably doing something wrong. Stack Exchange is not intended to play the role of a social network. You don't come here to interact with specific users, you come here for the content.
There are times when knowing how long it's been since a user was active might help make a decision on how to handle their content.

*

*Knowing when a specific individual was last seen can occasionally make a difference in knowing how to handle their content. Have they dropped off the map? Are they going to update that post that needs fixing? Have they had a chance to see comments that can now be removed as obsolete?

*Chat rooms also provide functionality to see who is in the room and who is recently active. Knowing this information is relevant to the function of those tools. For the main site, a sorted list of active users is simply not relevant.

*Some information about the most active users is relevant to the reputation leagues.
Adding such a feature would prove to be a distraction, subverting the way things work best.