text:
Q: Opening and creating SQLite database in Objective C I want to develop an iOS app, so I am learning Objective C. I followed a tutorial for using a SQLite database in my app. (http://www.techotopia.com/index.php/An_Example_SQLite_based_iOS_7_Application)
I have the following code for opening and creating of my database, but it doesn't work! I get the message "Failed to open or create database". Can someone tell me what is wrong?
- (void)viewDidLoad
{
    [super viewDidLoad];
    NSString *docsDir;
    NSArray *dirPaths;

    // Get the documents directory
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);

    docsDir = dirPaths[0];

    // Build the patht to the database file
    _databasePath = [[NSString alloc]initWithString: [docsDir stringByAppendingPathComponent: @"contacts.db"]];

    NSFileManager *filemgr = [NSFileManager defaultManager];

    if ([filemgr fileExistsAtPath:_databasePath] == NO) {
        const char *dbpath = [_databasePath UTF8String];

        if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK) {
            char *errMsg;
            const char *sql_stmt = "CREATE TABLE IF NOT EXISTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT";

            if (sqlite3_exec(_contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK) {
                _lblStatus.text = @"Failed to create table";

            }

            sqlite3_close(_contactDB);
        } else {
            _lblStatus.text = @"Failed to open or create database";
        }
    }
}

I have included 'libsqlite3.dylib' and added #import  to the H file.

A: In your code, there is some mistake
// Get the documents directory
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);

Use NSDocumentDirectory not NSDocumentationDirectory
I think it will solve your problem.
In my suggestion, you can try core data. It is more simple
You can try this tutorial
http://www.raywenderlich.com/934/core-data-tutorial-for-ios-getting-started
It is really simple and easily understandable.

A: DBConnection.h
#import <Foundation/Foundation.h>
#import <sqlite3.h>

// database name demo.sqlite

#define DB_NAME @"demo.sqlite"//@"Conferencedata////NSLog"

@interface DBConnection : NSObject
{
    @private sqlite3 *g_database;
}

@property (nonatomic,assign,readwrite) sqlite3 *database;

+ (DBConnection *) sharedConnection;
+ (BOOL) executeQuery:(NSString *)query;
+ (NSMutableArray *) fetchResults:(NSString *)query;
+ (int) rowCountForTable:(NSString *)table where:(NSString *)where;
+ (void) errorMessage:(NSString *)msg;
+ (void) closeConnection;

- (id)initConnection;
- (void)close;

@end

DBConnection.m
#import "DBConnection.h"
#import <UIKit/UIKit.h>
#include <sys/xattr.h>

//static sqlite3_stmt *statement = nil;

@interface DBConnection (Private)
- (void) createEditableCopyOfDatabaseIfNeeded;
- (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL;
- (void) initializeDatabase;
@end

@implementation DBConnection
static DBConnection *conn = NULL;

@synthesize database = g_database;

+ (DBConnection *) sharedConnection {
if (!conn) {
conn = [[DBConnection alloc] initConnection];
}
return conn;
}

#pragma mark - Static Methods

+(BOOL) executeQuery:(NSString *)query{
    BOOL isExecuted = NO;

    sqlite3 *database = [DBConnection sharedConnection].database;
    sqlite3_stmt *statement = nil;
    const char *sql = [query UTF8String];
    if (sqlite3_prepare_v2(database, sql, -1, &statement , NULL) != SQLITE_OK) {
        //NSLog(@"Error: failed to prepare agenda query statement with message '%s'.", sqlite3_errmsg(database));
        //NSString *errorMsg = [NSString stringWithFormat:@"Failed to prepare query statement - '%s'.", sqlite3_errmsg(database)];
        //[DBConnection errorMessage:errorMsg];
        //NSAssert1(0, @"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
        return isExecuted;
    }

    // Execute the query.
if(SQLITE_DONE == sqlite3_step(statement)) {
        isExecuted = YES;
    }

// finlize the statement.
sqlite3_finalize(statement);
    statement = nil;

    return isExecuted;
}
+(NSMutableArray *) fetchResults:(NSString *)query{
    NSMutableArray *results = [NSMutableArray arrayWithCapacity:0];
    sqlite3 *database = [DBConnection sharedConnection].database;
    sqlite3_stmt *statement = nil;

    const char *sql = [query UTF8String];
    if (sqlite3_prepare_v2(database, sql, -1, &statement , NULL) != SQLITE_OK) {
        //NSLog(@"Error: failed to prepare fetch results statement with message '%s'.", sqlite3_errmsg(database));
        NSString *errorMsg = [NSString stringWithFormat:@"Failed to prepare query statement - '%s'.", sqlite3_errmsg(database)];
        [DBConnection errorMessage:errorMsg];
        //NSAssert1(0, @"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
        return results;
    }

    while (sqlite3_step(statement) == SQLITE_ROW) {

        id value = nil;
        NSMutableDictionary *rowDict = [NSMutableDictionary dictionaryWithCapacity:0];
        for (int i = 0 ; i < sqlite3_column_count(statement) ; i++) {

            /*
if (strcasecmp(sqlite3_column_decltype(statement,i),"Boolean") == 0) {
value = [NSNumber numberWithBool:(BOOL)sqlite3_column_int(statement,i)];
} else */

            if (sqlite3_column_type(statement,i) == SQLITE_INTEGER) {
                value = [NSNumber numberWithInt:(int)sqlite3_column_int(statement,i)];
            } else if (sqlite3_column_type(statement,i) == SQLITE_FLOAT) {
                value = [NSNumber numberWithFloat:(float)sqlite3_column_double(statement,i)];
            } else {

                if (sqlite3_column_text(statement,i) != nil) {
                    value = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement,i)];
                } else {
                    value = @"";
                }
            }

            if (value) {
                [rowDict setObject:value forKey:[NSString stringWithUTF8String:sqlite3_column_name(statement,i)]];
            }
        }

        [results addObject:rowDict];
        ////NSLog(@"rowDict -- %@", rowDict);
    }

    sqlite3_finalize(statement);
    statement = nil;

    return results;
}
+(int) rowCountForTable:(NSString *)table where:(NSString *)where{
    int tableCount = 0;
NSString *query = @"";

    if (where != nil && ![where isEqualToString:@""]) {
        query = [NSString stringWithFormat:@"SELECT COUNT(*) FROM %@ WHERE %@",
                 table,where];
    } else {
        [NSString stringWithFormat:@"SELECT COUNT(*) FROM %@",
         table];
    }

sqlite3_stmt *statement = nil;

    sqlite3 *database = [DBConnection sharedConnection].database;
    const char *sql = [query UTF8String];
    if (sqlite3_prepare_v2(database, sql, -1, &statement , NULL) != SQLITE_OK) {
        return 0;
    }

if (sqlite3_step(statement) == SQLITE_ROW) {
        tableCount = sqlite3_column_int(statement,0);
    }

sqlite3_finalize(statement);
return tableCount;
}
+(void) errorMessage:(NSString *)msg{
    //UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ERROR" message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    //[alert show];
    //[alert release];
}
+(void) closeConnection{
    sqlite3 *database = [DBConnection sharedConnection].database;
    if (sqlite3_close(database) != SQLITE_OK) {
        //NSAssert1(0, @"Error: failed to close database with message '%s'.", sqlite3_errmsg(g_database));
        NSString *errorMsg = [NSString stringWithFormat:@"Failed to open database with message - '%s'.", sqlite3_errmsg(database)];
        [DBConnection errorMessage:errorMsg];
    }
}
-(id) initConnection {

    self = [super init];

if (self) {
//database = g_database;
if (g_database == nil) {
// The application ships with a default database in its bundle. If anything in the application
// bundle is altered, the code sign will fail. We want the database to be editable by users,
// so we need to create a copy of it in the application's Documents directory.
[self createEditableCopyOfDatabaseIfNeeded];
// Call internal method to initialize database connection
[self initializeDatabase];
}
}
return self;
}

#pragma mark - save db

-(void)createEditableCopyOfDatabaseIfNeeded {
    // First, test for existence.
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *dbDirectory = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"]]];

    if (![fileManager fileExistsAtPath:dbDirectory]) {
        [fileManager createDirectoryAtPath:dbDirectory withIntermediateDirectories:NO attributes:nil error:nil];
        [self addSkipBackupAttributeToItemAtURL:[[[NSURL alloc] initFileURLWithPath:dbDirectory isDirectory:YES] autorelease]];
    }

    NSString *writableDBPath = [dbDirectory stringByAppendingPathComponent:DB_NAME];
    success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
    // The writable database does not exist, so copy the default to the appropriate location.
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:DB_NAME];
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
    if (!success) {
        //NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);

        NSString *errorMsg = [NSString stringWithFormat:@"Failed to create writable database file with message - %@.", [error localizedDescription]];
        [DBConnection errorMessage:errorMsg];
    }
}
-(BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL{
    const char* filePath = [[URL path] fileSystemRepresentation];

    const char* attrName = "com.apple.MobileBackup";
    u_int8_t attrValue = 1;

    int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);
    return result == 0;
}

#pragma mark - Open the database connection and retrieve minimal information for all objects.

-(void)initializeDatabase {
    // The database is stored in the application bundle.
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);

    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *dbDirectory = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"]]];

    NSString *path = [dbDirectory stringByAppendingPathComponent:DB_NAME];
////NSLog(@"SQLite Root: %s", [path UTF8String]);

    // Open the database. The database was prepared outside the application.
    if (sqlite3_open([path UTF8String], &g_database) != SQLITE_OK) {
        // Even though the open failed, call close to properly clean up resources.
        sqlite3_close(g_database);
g_database = nil;
        //NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(g_database));
        NSString *errorMsg = [NSString stringWithFormat:@"Failed to open database with message - '%s'.", sqlite3_errmsg(g_database)];
        [DBConnection errorMessage:errorMsg];
    }
}
-(void)close {

if (g_database) {
// Close the database.
if (sqlite3_close(g_database) != SQLITE_OK) {
//NSAssert1(0, @"Error: failed to close database with message '%s'.", sqlite3_errmsg(g_database));
            NSString *errorMsg = [NSString stringWithFormat:@"Failed to open database with message - '%s'.", sqlite3_errmsg(g_database)];
            [DBConnection errorMessage:errorMsg];
}
g_database = nil;
}
}

@end

use for create table and db
[DBConnection executeQuery:@"CREATE DATABASE demo"];
        if([DBConnection executeQuery:@"CREATE TABLE IF NOT EXISTS product (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)"]){

        }else{
            NSLog(@"CREATE TABLE IF NOT EXISTS product (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)");
        }

A: You should do following:
1) Change NSDocumentationDirectory to NSDocumentDirectory in NSSearchPathForDirectoriesInDomains function parameter in your code.
2) Your code inside first 'if' block is not correct. It should instead be following:
if ([filemgr fileExistsAtPath:_databasePath] == NO)  {
// The database does not exist, so copy the default to the appropriate location.
        NSString *defaultDBPath = [[NSBundle mainBundle] pathForResource:@"contacts.db" ofType:nil];
        BOOL success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
        if (!success) {
            // Failed to copy db from bundle to documents folder.
        }
}

3) Finally write the code you already have to open the database.
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK) {
        char *errMsg;
        const char *sql_stmt = "CREATE TABLE IF NOT EXISTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT";

        if (sqlite3_exec(_contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK) {
            _lblStatus.text = @"Failed to create table";

        }

        sqlite3_close(_contactDB);
    } else {
        _lblStatus.text = @"Failed to open or create database";
    }

A: how to add save get in sqlite
ViewController.h
createdata
    @property (strong, nonatomic) NSString *databasePath;
    @property (nonatomic) sqlite3 *contactDB;
ViewController.m
- (void)viewDidLoad {
[super viewDidLoad];

NSString *docsDir;
NSArray *dirPaths;

// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
docsDir = dirPaths[0];

// Build the path to the database file
_databasePath = [[NSString alloc]initWithString: [docsDir
stringByAppendingPathComponent:@"mithun.db"]];

NSLog(@"CREATED DB PATH :%@", _databasePath);

//temp database path
///Users/nschool/Library/Developer/CoreSimulator/Devices/D4755C93-  38F5-4F51-933D-68501B039326/data/Containers/Data/Application/2DCCFB9B-8E96-43CC-A7FC-1AB3E8627397/Documents/contacts.db

NSFileManager *filemgr = [NSFileManager defaultManager];

if ([filemgr fileExistsAtPath: _databasePath ] == NO) {

    const char *dbpath = [_databasePath UTF8String];

    //sqlite3_open(const char *filename, <#sqlite3 **ppDb#>)

    if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK) {

        char *errMsg;
        //for query
        const char *sql_stmt = "CREATE TABLE IF NOT EXISTS CONTACT
     (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT,
     PHONE TEXT)";

          //check sqlite3 connection
        if (sqlite3_exec(_contactDB, sql_stmt, NULL, NULL, &errMsg)
       != SQLITE_OK) {
            _status.text = @"Failed to create table";
        }
        sqlite3_close(_contactDB);
    }
    else {
        _status.text = @"Failed to open/create database";
    }
   }

}

savedata
- (IBAction)saveData:(id)sender {

const char *dbpath = [_databasePath UTF8String];

sqlite3_stmt *statement;

if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK) {

    NSString *insertSQL = [NSString stringWithFormat:
            @"INSERT INTO CONTACT (name, address,
         phone) VALUES (\"%@\", \"%@\", \"%@\")",
             _name.text, _address.text, _phone.text];

    NSLog(@"Insert query :%@", insertSQL);

    const char *insert_stmt = [insertSQL UTF8String];

    sqlite3_prepare_v2(_contactDB, insert_stmt,-1, &statement, NULL);

    if (sqlite3_step(statement) == SQLITE_DONE) {

        _status.text = @"Contact added";
        _address.text = @"";
        _phone.text = @"";

        UIAlertController *test = [UIAlertController
     alertControllerWithTitle:@"Test" message:@"Test"
 preferredStyle:UIAlertControllerStyleActionSheet];

        UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK"
     style:UIAlertActionStyleDefault handler:nil];

        UIAlertAction *cancel = [UIAlertAction
     actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel
  handler:nil];

        [test addAction:ok];
        [test addAction:cancel];

        [self presentViewController:test animated:YES completion:nil
 ];

    }
    else {
        _status.text = @"Failed to add contact";
    }

    sqlite3_finalize(statement);
    sqlite3_close(_contactDB);
}

}

A: .h
#import <UIKit/UIKit.h>
#import <sqlite3.h>

@interface ViewController : UIViewController<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *imageviewTxt;

 @property (weak, nonatomic) IBOutlet UITextField *nameTxt;
  @property (weak, nonatomic) IBOutlet UITextField *mobilenoTxt;
   @property (weak, nonatomic) IBOutlet UITextField *destinationTxt;
 @property (weak, nonatomic) IBOutlet UILabel *status;
 - (IBAction)submit:(id)sender;
@property (strong, nonatomic) NSString *databasePath;
@property (nonatomic) sqlite3 *contactDB;

@end


text:
Q: remove google-assets completely from the wordpress-site to meet GDPR-regulations update: good news: i contacted the developer and they replied - that they are currently working on a solution:
concrete: the developer from astoundify.com sent me a mail:
cit:

We will be soon adding an option to remove Google Maps usage
completely. For Google Fonts, we have already provided an option to
download the fonts locally, see
https://kb.astoundify.com/article/how-to-ensure-your-jobify-theme-is-gdpr-compliant-with-google-fonts/
on how to use it. Make sure you are using the latest version.

well: thats sounds great and very promising - and i hope that this will solve the issues. That sounds great and would be a awesome.
lets hope that. i will keep you up to date - i will repost all the new things and will update this thread as soon as possible.
see all - the issue: and the phenomenon: due to the challenging GDPR-regulations in Germany, I would like to remove Google maps completely from my website. Actually I do not use it with the theme jobify (see https://kb.astoundify.com/article/how-to-remove-maps-in-jobify-results-page/ )
The theme Jobify i use in combination with the plugin wp-jobmanager ( see.: https://wordpress.org/plugins/wp-job-manager/ )
pulls content from  5 Domains
    pulls data from 5 foreign Domains from so called third countries

tested with this Test-tool: https://www.ccm19.de/cookie-scanner/
    fetch https://maps.googleapis.com/maps/api/js?v=3&libraries=geometry%2Cplaces&language=en&ver=6.1.1

    stylesheet https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,60...

    script https://maps.googleapis.com/maps/api/js?v=3&libraries=geometry%2Cplaces&language=en&ver=6.1.1

    image: https://maps.gstatic.com/intl/en_us/mapfiles/iw_close.gif

    xhr: https://maps.googleapis.com/maps/api/mapsjs/gen_204?csp_test=true

it seems that the site and the system is still using google maps as a source. How can I remove it completely to comply with the german GDPR?
In addition I would also like to get rid of the new em-search-group-type-list – especially the maps display option.  How can I do that?
btw; i allready tird what the jobfy-team suggested to do:
How to Remove Maps in Jobify Results page https://kb.astoundify.com/article/how-to-remove-maps-in-jobify-results-page/
If you have your demo imported the most times you will have the Jobs results page indicating the map section at the top of the page. This simply displays the location of all the job listings within the map using pins. The maps display within this page because the template in use is the maps & results template. Therefore to remove the maps in the find a job page or simply the results page simply head over to edit the page and go to the page attributes on the right side, then under the dropdown select the default template instead. See the screenshot below
approach: i guess that  Google Maps is not included in WordPress core, so there's no general purpose solution. well the developer-documentation shows how to remove the map, but they're clearly still loading the Google Maps assets. We need to find out how to specifically remove those assets from the plugin.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Handling ties when ranking from the highest to the lowest I am trying to make a ranking manager for a small project.The totals are stored in the database.I can easily get the max and min using mysql and also arrange the records descending.The problem comes in when there is a tie.I need to show a tie in the form:1,2,3,3,4,5,6,7,7,7,7, etc.The repeated numbers will show the ties.I have been thinking of ways of achieving the above but i need more ideas;mine is seems long and complicated.
Can anybody share his/her idea of doing the ties.

A: $data = array(
  'A'=>19,'B'=>18,'C'=>17,'D'=>17,'E'=>16,'F'=>15
);

$rank = 0;
$lastScore = PHP_INT_MAX;
foreach( $data as $name=>$score ) {
  if ( $lastScore !== $score ) {
    $lastScore = $score;
    $rank += 1;
  }
  printf("%s %d (%d)\n", $name, $score, $rank);
}

prints
A 19 (1)
B 18 (2)
C 17 (3)
D 17 (3)
E 16 (4)
F 15 (5)

A: Could you not just do that in SQL as well? The records with duplicate ranks will still get output, however the order within the tie will be undefined.
SELECT id, rank FROM mytable ORDER BY rank ASC;

Ah, looks like I misunderstood the question, thanks Matchu. This could still be achieved with a relatively simple SQL query. The key is using a subquery to count the distinct scores that have already passed.
SELECT id, score, (
  SELECT COUNT(DISTINCT score) + 1
  FROM mytable
  WHERE score < outerscore.score
  ORDER BY score ASC
) AS rank
FROM mytable as outertable
ORDER BY score ASC;


text:
Q: ExternalFileField in Solr 3.6 I am trying to use Solr 3.6.1 ExternalFileField. Here is my fieldtype definition:
<fieldtype name="file" keyField="id" defVal="0" stored="true" indexed="true" class="solr.ExternalFileField" valType="float"/>

and here is the field definition:
<field name="fviews" type="file"/>

I was able to test it by sorting on fviews like
http://localhost:8983/solr/select?q=tag_id:1&sort={!func}fviews desc

and it is working correctly.
But I am running into two issues:
I need this field back in my search results. Even though I've marked the field as stored="true" I do not get it back. I even tried adding &fl=* query param but it doesn't work.
If I make changes to the external file, they are not getting reflected in the search results immediately (which is the very reason why I wanted to use external file field). The documentation for solr 4.0 at https://lucene.apache.org/solr/api-4_0_0-BETA/org/apache/solr/schema/ExternalFileField.html reads "If the external file has already been loaded, and it is changed, those changes will not be visible until a commit has been done.". I tried doing a commit using http://localhost:8983/solr/update?commit=true in the hope that Solr may read the edited file based on modified timestamp, but it does not work. However, if I do a full import, then the results are correct.
Update (Answer): The 2nd question has been answered by @Persimmonium below. The answer for the first question (how to retrieve the value) is to use fl=*,field(EXTERNAL_FILE_FIELD_NAME) as mentioned in this blog post I wrote.

A: Regarding external field not being returned, I was not aware of that, but it is probably a limitation of such fields, as they cannot be searched either.
Regarding reloading, I had to do this so they were reloaded:
In solrconfig.xml add the following handler:
<requestHandler name="/reloadCache" class="org.apache.solr.search.function.FileFloatSource$ReloadCacheRequestHandler" />

Now modify some values of the file that would change the sorting. And here is the most important thing, hit the following url otherwise Solr will not use the new values.
http://your.host:8983/solr/core0/reloadCache


text:
Q: Tangent point of sphere and circle I would like to know parametric equation of the tangent point of a sphere and a circle. Circle center point is $(a,b,c)$ and its radius is $K$. Sphere center point is $(d,e,f)$ and its radius is $L$.
I assume that specified circle and a sphere intersect on one tangent point. I would like to know how I can determine the tangent point $(x,y,z)$.
If there is a misinformation please define for me.
Thanks in advance.

A: In the plane passing through the centers $A,B$ and the tangent point $C$, you get a triangle $ABC$ of which you know the three sides.
So you can determine every parameter of it, and in particular the height $h$ from $C$ to the side $AB$.
When reported in $3$D, the triangle is free to rotate around the axis $AB$ and the point C can be whichever along a circle on the sphere of radius $h$ from the $AB$ axis.
You need one more constraint to fix the circle.


text:
Q: Sensu and Graphite. Configure transmission through AMQP I want to use Sensu as monitoring system and Graphite as backend for graphics.
I wish to configure Sensu for receiving data from RabbitMQ via AMQP protocol that's why I configured Carbon in such way:
# vim /etc/carbon/carbon.conf

# Enable AMQP if you want to receve metrics using an amqp broker
ENABLE_AMQP = True

# Verbose means a line will be logged for every metric received
# useful for testing
AMQP_VERBOSE = True

AMQP_HOST = 10.0.3.16
AMQP_PORT = 5672
AMQP_VHOST = /sensu
AMQP_USER = sensu
AMQP_PASSWORD = kubuntu710
AMQP_EXCHANGE = metrics_my
AMQP_METRIC_NAME_IN_BODY = True

Per my understanding Carbon with some frequency requests data from RabbitMQ (via AMQP) and save it via Whisper.
On other side Sensu saves some metrics in RabbitMQ, I configured it in next way:
root@sensu_server:/etc/sensu/conf.d# vim graphite_handler_amqp.json

{
  "handlers": {
    "graphite_amqp": {
      "type": "transport",
      "pipe": {
        "type": "topic",
        "name": "metrics_my",
        "durable": "true"
      },
      "mutator": "only_check_output"
    }
  }
}

And of course I attached this handler in such way:
root@sensu_server:/etc/sensu/conf.d# cat metrics_cpu.json
{
  "checks": {
    "metrics_cpu": {
      "type": "metric",
      "command": "/opt/sensu/embedded/bin/metrics-cpu-pcnt-usage.rb",
      "interval": 10,
      "subscribers": ["MONGO"],
      "handlers": ["graphite_amqp"]
    }
  }
}

Everything fine but Graphite can't draw metrics. This is log from Graphite side:
13/06/2016 18:57:16 :: New AMQP connection made

And this is from rabbitMQ on Sensu server side:
=INFO REPORT==== 13-Jun-2016::15:57:16 ===
accepting AMQP connection <0.25298.0> (10.0.3.95:43722 -> 10.0.3.16:5672)

=ERROR REPORT==== 13-Jun-2016::15:57:16 ===
Channel error on connection <0.25298.0> (10.0.3.95:43722 -> 10.0.3.16:5672, vhost: '/sensu', user: 'sensu'), channel 1:
operation exchange.declare caused a channel exception precondition_failed: "inequivalent arg 'durable' for exchange 'metrics_my' in vhost '/sensu': received 'true' but current is 'false'"

Why rabbitMQ thinks that "durable": set to "false", when Sensu should set it to true?
Can anybody share own expirience with such logic?
PS. Configuration with just tcp handler is working fine for me.

A: operation exchange.declare caused a channel exception precondition_failed: "inequivalent arg 'durable' for exchange 'metrics_my' in vhost '/sensu': received 'true' but current is 'false'"

The exchange metrics_my already exists and has the durable property set to false. Some other process is now trying to re-declare that same exchange with a different value for durable (true).
It looks like that when the processes start up they are trying to configure RabbitMQ using the configuration you have specified - making sure the required exchanges and queues exist.
However, RabbitMQ does not allow changing some properties of exchanges and queues after they have been created, so one of the processes is starting up, trying to make sure the exchange exists but is failing because it is specifying a different value for the durable property than what it already is.
My guess is that carbon and sensu have been configured to have a different value of durable for the metrics_my exchange.
Based on the snippets of configuration you provided, I don't see an option for changing the durable property for carbon, but you can for sensu.
You need to make everyone agree on what durable should be, delete the exchange (if durable will be different) and restart everything.
PS: The durable property specifies that the exchange should be persisted to disk and survive restarts of the RabbitMQ process.


text:
Q: How can I tell if my FireWire port is 400 or 800? (Linux) I know this sounds very similar to How do I tell if my firewire connection is running as 400 or 800?, but the difference is, I don't have a FireWire device yet.
The whole reason I'm asking is that I'm trying to decide between two portable hard drives - which both have USB interfaces regardless - and are completely identical except one has a FireWire 800 interface (and is more expensive, natch).
I don't know if my port/controller supports 800 MHz speeds or not. I've done a lot of internet searching and even tried jujuutils, but that was a little too low-level for me to interpret the results.
Here's the lspci output, fwiw:
04:00.0 FireWire (IEEE 1394) [0c00]: O2 Micro, Inc. 1394 OHCI Compliant Host Controller [1217:13f7] (rev 05) (prog-if 10 [OHCI])
    Subsystem: Dell Device [1028:0494]
    Control: I/O- Mem+ BusMaster+ SpecCycle- MemWINV- VGASnoop- ParErr- Stepping- SERR- FastB2B- DisINTx-
    Status: Cap+ 66MHz- UDF- FastB2B- ParErr- DEVSEL=fast >TAbort- <TAbort- <MAbort- >SERR- <PERR- INTx-
    Latency: 0, Cache Line Size: 64 bytes
    Interrupt: pin A routed to IRQ 17
    Region 0: Memory at e4b30000 (32-bit, non-prefetchable) [size=4K]
    Capabilities: [a0] Power Management version 3
        Flags: PMEClk- DSI- D1+ D2+ AuxCurrent=0mA PME(D0+,D1+,D2+,D3hot+,D3cold+)
        Status: D0 NoSoftRst- PME-Enable- DSel=0 DScale=0 PME-
    Capabilities: [48] MSI: Enable- Count=1/1 Maskable+ 64bit+
        Address: 0000000000000000  Data: 0000
        Masking: 00000000  Pending: 00000000
    Capabilities: [80] Express (v1) Endpoint, MSI 00
        DevCap: MaxPayload 128 bytes, PhantFunc 0, Latency L0s <4us, L1 <64us
            ExtTag- AttnBtn- AttnInd- PwrInd- RBE+ FLReset-
        DevCtl: Report errors: Correctable- Non-Fatal- Fatal- Unsupported-
            RlxdOrd+ ExtTag- PhantFunc- AuxPwr- NoSnoop+
            MaxPayload 128 bytes, MaxReadReq 512 bytes
        DevSta: CorrErr+ UncorrErr- FatalErr- UnsuppReq+ AuxPwr- TransPend-
        LnkCap: Port #0, Speed 2.5GT/s, Width x1, ASPM L0s L1, Latency L0 <64ns, L1 unlimited
            ClockPM+ Surprise- LLActRep- BwNot-
        LnkCtl: ASPM L0s Enabled; RCB 64 bytes Disabled- Retrain- CommClk-
            ExtSynch- ClockPM+ AutWidDis- BWInt- AutBWInt-
        LnkSta: Speed 2.5GT/s, Width x1, TrErr- Train- SlotClk- DLActive- BWMgmt- ABWMgmt-
    Capabilities: [100 v1] Virtual Channel
        Caps:   LPEVC=0 RefClk=100ns PATEntryBits=1
        Arb:    Fixed- WRR32- WRR64- WRR128-
        Ctrl:   ArbSelect=Fixed
        Status: InProgress-
        VC0:    Caps:   PATOffset=00 MaxTimeSlots=1 RejSnoopTrans-
            Arb:    Fixed- WRR32- WRR64- WRR128- TWRR128- WRR256-
            Ctrl:   Enable+ ID=0 ArbSelect=Fixed TC/VC=ff
            Status: NegoPending- InProgress-
    Capabilities: [200 v1] Advanced Error Reporting
        UESta:  DLP- SDES- TLP- FCP- CmpltTO- CmpltAbrt- UnxCmplt- RxOF- MalfTLP- ECRC- UnsupReq- ACSViol-
        UEMsk:  DLP- SDES- TLP- FCP- CmpltTO- CmpltAbrt- UnxCmplt- RxOF- MalfTLP- ECRC- UnsupReq- ACSViol-
        UESvrt: DLP+ SDES+ TLP- FCP+ CmpltTO- CmpltAbrt- UnxCmplt- RxOF+ MalfTLP+ ECRC- UnsupReq- ACSViol-
        CESta:  RxErr- BadTLP- BadDLLP- Rollover- Timeout- NonFatalErr+
        CEMsk:  RxErr- BadTLP- BadDLLP- Rollover- Timeout- NonFatalErr+
        AERCap: First Error Pointer: 00, GenCap- CGenEn- ChkCap- ChkEn-
    Kernel driver in use: firewire_ohci
    Kernel modules: firewire-ohci

A: Maybe when the firewire-ohci driver was loaded, it outputs the detected speed.  Look in your /var/log/dmesg for kernel output from your last boot and see if you find where the driver is being loaded.
You could also rmmod firewire-ochi and then insmod firewire-ochi to see if any informational messages are output.

A: Just look at your firewire port on your computer.
If you have a 9 pin connector, then it will run at 800 and 400
If you have a 6 pin or a 4 pin connector, then it will run at 400

9 pin connector

6 pin connector

Resources
http://www.cablestogo.com/support/connector-guides/firewire
https://en.wikipedia.org/wiki/IEEE_1394


text:
Q: What is the meaning of void* volatile* in c++ I am looking at the following code:
inline void* interlocked_read_acquire(void* volatile* x);

and am wondering why not just a volatile void* as an argument. In general what is the semantics or definition of a volatile*? I am also making the assumption that you could use the volatile* qualifier with any other type besides void. Is that correct?

A: void * ptr1; means that ptr1 is a variable whose type is void *. This type indicates a "generic pointer" - it points to some memory location but contains no type information what what is in that location.
void * volatile ptr2; means that the variable ptr2 is also a generic pointer, but ptr2 is also volatile. The keyword volatile is called a cv-qualifier and it has the same grammar rules as const.
The meaning of a volatile variable is that when some other code says ptr2, the compiler cannot optimize that out; it must read or write the memory location where ptr2 is stored; it must allow for the possibility that some external process is also reading or writing that location.
Finally, void * volatile *x is something that can point to ptr2.   For example we could have void * volatile * x = &ptr2; . If we then write *x = NULL; for example, then *x has type void * volatile which has the same implications as we just looked at for ptr2.
The compiler would complain if you omitted the qualifier, e.g. void * *y = &ptr2; . This is because the expression *y would then have type void * (non-volatile) so the compiler might perform optimizations around it, however this is incorrect behaviour because ptr2 does not permit those optimizations.   (You may recognize that "volatile-correctness" is the same sort of thing as const-correctness).

A: Use cdecl or the clockwise spiral rule to decipher C-style declarations :
void* volatile* x

*

*declares x as pointer to volatile pointer to void
which is different from :
volatile void* x

*

*declare x as pointer to volatile void

A:
wondering why [void* volatile* and] not just a volatile void*...?

They're different things.

*

*void* volatile* is a pointer to a volatile (void*) (so dereferencing and accessing the volatile void* is possible without casting, but would just give you the address of some as-yet unspecified thing in memory)

*volatile void* is a pointer to a volatile void (so you must cast to a type like say volatile int* or volatile My_Class* before dereferencing)

A: volatile is an add-on property, you can first remove it to read from
void* volatile* x

to:
void* *x

This is very familiar. For example, an array of malloc-ed memory pointers.
And you won't get confused with
volatile void*

which is reduced to
void* x.


text:
Q: Clearing jQuery Mobile Multiple Select Lists I have a page element
<select name="geoLocationIndicatorClassID" id="int_geoLocationIndicatorClassID" multiple="multiple" data-native-menu="false">

With the  elements generated dynamically
$('#int_geoLocationIndicatorClassID').append($('<option></option>').val(results.rows.item(i).geoLocationIndicatorClassID).html(results.rows.item(i).geoLocationIndicatorClassName));

Where results is an Sql object.
My problem is clearing the list when the user has submitted data.
I have tried
$('#int_geoLocationIndicatorClassID a').each(function(){
$(this).removeClass('ui-checkbox-on').addClass('ui-checkbox-off');
});

$('#int_geoLocationIndicatorClassID :selected').each(function(i, selected){
$(selected).attr("selected", false);
$(selected).removeClass('ui-checkbox-on').addClass('ui-checkbox-off');
});

$('#int_geoLocationIndicatorClassID').selectmenu('refresh');

and
$("#int_geoLocationIndicatorClassID option:selected").removeAttr("selected");

But this does not clear selections. Is there a better way of clearing dynamically generated multiple selects?

A: Give this a try: $("#int_geoLocationIndicatorClassID option:selected").prop("selected", false);

A: try
$("#int_geoLocationIndicatorClassID").val([]).selectmenu('refresh', true);

The true on the refresh() method forces jQM to rebuild the widget after setting the selected vals to an empty array.


text:
Q: R: Winsorize one column per year for panel data I would like to winsorize the column "Return". However, I want to winsorize per Year.
My data looks like this:
structure(list(Name = c("A", "A", "A", "A", "A", "A", "B", "B",
"B", "B", "B", "B", "C", "C", "C", "C", "C", "C"), Date = c("01.09.2018",
"02.09.2018", "03.09.2018", "05.11.2021", "06.11.2021", "07.11.2021",
"01.09.2018", "02.09.2018", "03.09.2018", "05.11.2021", "06.11.2021",
"07.11.2021", "01.09.2018", "02.09.2018", "03.09.2018", "05.11.2021",
"06.11.2021", "07.11.2021"), Return = c(0.05, 0.1, 0.8, 1.5,
0.1, -2, 0.4, 0.6, 0.6, 0.2, -0.5, -0.9, -0.4, 1.7, 0.3, -4,
0.6, 0.5), Year = c("2018", "2018", "2018", "2021", "2021", "2021",
"2018", "2018", "2018", "2021", "2021", "2021", "2018", "2018",
"2018", "2021", "2021", "2021")), row.names = c(NA, -18L), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"), groups = structure(list(Year = c("2018",
"2021"), .rows = structure(list(c(1L, 2L, 3L, 7L, 8L, 9L, 13L,
14L, 15L), c(4L, 5L, 6L, 10L, 11L, 12L, 16L, 17L, 18L)), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -2L), .drop = TRUE))

I tried the following code which also works:
Data <- Data %>%
  group_by(Year) %>%
  mutate("Winsorized Return" = Winsorize(`Return`, probs=c(0.01, 0.99)))

Now I do the same but without grouping the data per year:
Data <- Data %>%
  mutate("Winsorized Return" = Winsorize(`Return`, probs=c(0.01, 0.99)))

I get exactly the same results even though I used "group_by(Years) in the first code.
Can someone explain me why the results are the same? Even when I do the same with my real (very large) dataset I get the same results.
Do I have to use another code in order to winsorize the column "Return" per year?
Thank you very much already for any help!


text:
Q: Perl uninitialized value error after parsing html I'm using Bioperl to find GOterms for genes.
I retrieve an html file, convert it to text, get rid of all extra spaces and newlines, and try to go through the resulting array.
However, I keep getting errors for accessing uninitialized values in the array. I put in many checks to make sure the array is not empty and that I'm not going out of bounds. How can I get rid of this error?
I reposted the code in a more readable format. Thank you for your help.
It seems to successfully parse out the correct data from the html so I don't know what's wrong.
#!/usr/bin/perl -w
use strict;
use LWP::Simple;
use HTML::TreeBuilder;
use HTML::FormatText;

my $URL         = get("http://amigo.geneontology.org/amigo/term/GO:0000001");
my $Format      = HTML::FormatText->new;
my $TreeBuilder = HTML::TreeBuilder->new;
$TreeBuilder->parse($URL);
my $Parsed = $Format->format($TreeBuilder);
print "$Parsed";
my @parsed = split( /[ ]{2,}|(\n+)|(\r+)/, $Parsed );
if ( @parsed == 1 ) { return; }

my %termhash;
my $count = 0;

while ( $count < @parsed ) {
    if ( defined $parsed[$count] && $parsed[$count] eq 'Name' ) {
        my $count2 = $count;
        while ( ( $parsed[$count2] ne 'Feedback' ) && ( $count2 < @parsed ) ) {
            $count2++;
        }
        $count2--;
        @parsed = @parsed[ $count .. $count2 ];    # Gets the slice of the array needed
        last;
    }
    $count++;
}

if ( @parsed <= 1 ) { return; }
print "\n";

print @parsed;

$count = 0;
while ( $count < @parsed ) {
    if ( $parsed[$count] eq 'Name' ) {
        while ( $parsed[$count] ne 'Ontology' && ( $count < @parsed )) {
            $termhash{'Name'} .= $parsed[$count];
            $count++;
        }
    }
    if ( $parsed[$count] eq 'Ontology' ) {
        while ( $parsed[$count] ne 'Synonyms' && ( $count < @parsed )) {
            $termhash{'Category'} .= $parsed[$count];
            $count++;
        }
    }
    if ( $parsed[$count] eq 'Synonyms' ) {
        while ( $parsed[$count] ne 'Definition' && ( $count < @parsed )) {
            $termhash{'Aliases'} .= $parsed[$count];
            $count++;
        }
    }
    if ( $parsed[$count] eq 'Definition' ) {
        while ( $parsed[$count] ne 'Comment' && ( $count < @parsed )) {
            $termhash{'Definition'} .= $parsed[$count];
            $count++;
        }
    }
    if ( $parsed[$count] eq 'Comment' ) {
        while ( $parsed[$count] ne 'History' && ( $count < @parsed )) {
            $termhash{'Comment'} .= $parsed[$count];
            $count++;
        }
    }
    if ( $parsed[$count] eq 'History' ) {
        while ( $parsed[$count] ne 'Subset' && ( $count < @parsed )) {
            $termhash{'Version'} .= $parsed[$count];
            $count++;
        }
    }
    if ( $parsed[$count] eq 'Subset' ) {
        while ( ( $parsed[$count] ne 'Community' ) && ( $count < @parsed ) ) {
            $count++;
        }
    }
    if ( $parsed[$count] eq 'Community' ) {
        while ( ( $parsed[$count] ne 'Related' ) && ( $count < @parsed ) ) {
            $count++;
        }
    }
    if ( $parsed[$count] eq 'Related' ) {
        for ( $count < @parsed ) {
            $termhash{'Definition references'} .= $parsed[$count];
            $count++;
        }
    }
}
if ( $termhash{'Definition'} =~ m/OBSOLETE/ ) { $termhash{'Is obsolete'} = 1 }
else { $termhash{'Is obsolete'} = 0 }
#print %termhash;

The main error messages are:

*

*Use of uninitialized value $parsed[127] in string ne at
/home/adur/workspace/BI7643/ParseGOhtml.pl line 23.
Use of uninitialized value $parsed[1] in print at
/home/adur/workspace/BI7643/ParseGOhtml.pl line 35.
Use of uninitialized value $parsed[1] in string ne at
/home/adur/workspace/BI7643/ParseGOhtml.pl line 42.
Use of uninitialized value $parsed[1] in concatenation (.) or string
at /home/adur/workspace/BI7643/ParseGOhtml.pl line 41.
Use of uninitialized value $parsed[17] in string ne at
/home/adur/workspace/BI7643/ParseGOhtml.pl line 48.
Use of uninitialized value $parsed[17] in concatenation (.) or string
at /home/adur/workspace/BI7643/ParseGOhtml.pl line 47.
Use of uninitialized value $parsed[29] in string ne at
/home/adur/workspace/BI7643/ParseGOhtml.pl line 54.
Use of uninitialized value $parsed[29] in concatenation (.) or string
at /home/adur/workspace/BI7643/ParseGOhtml.pl line 53.
Use of uninitialized value $parsed[41] in string ne at
/home/adur/workspace/BI7643/ParseGOhtml.pl line 60.
Use of uninitialized value $parsed[41] in concatenation (.) or string
at /home/adur/workspace/BI7643/ParseGOhtml.pl line 59.
Use of uninitialized value $parsed[79] in string ne at
/home/adur/workspace/BI7643/ParseGOhtml.pl line 66.
Use of uninitialized value $parsed[79] in concatenation (.) or string
at /home/adur/workspace/BI7643/ParseGOhtml.pl line 65.
Use of uninitialized value $parsed[83] in string ne at
/home/adur/workspace/BI7643/ParseGOhtml.pl line 72.
Use of uninitialized value $parsed[83] in concatenation (.) or string
at /home/adur/workspace/BI7643/ParseGOhtml.pl line 71.
Use of uninitialized value $parsed[95] in string ne at
/home/adur/workspace/BI7643/ParseGOhtml.pl line 77.
Use of uninitialized value $parsed[107] in string ne at
/home/adur/workspace/BI7643/ParseGOhtml.pl line 82.

A: Did you mean to not quote the second and third call to parse?
htmlparse('GO:0000001');
htmlparse(GO:0000002);
htmlparse(GO:0000003);

Should be;
htmlparse('GO:0000001');
htmlparse('GO:0000002');
htmlparse('GO:0000003');

Also, make sure to add to the top of your file the following
use warnings;
use diagnostics;

Post back the resulting error messages if there is still a problem.
Also, according to http://geneontology.org/page/lead-database-guide you can query the online database directly without having to parse html, they provide the following example using their tool;
GOshell.pl -d go_latest -dbuser go_select -dbauth amigo -port 4085 -h mysql.ebi.ac.uk

Relevent cpan information; http://cpansearch.perl.org/src/SJCARBON/go-db-perl-0.04/doc/go-db-perl-doc.html


text:
Q: Serve RSS feed with different languages for different items Is it possible to create an RSS (2.0) feed with multiple languages? Say I blog mainly in English (en), but sometimes I create German (de) posts.
Is there support for this in the RSS spec? I couldn't find anything in the RSS spec on this issue.
There doesn't seem to be a language sub-element below item and I'm not sure if it's valid to put multiple language codes separated by comma in the language element of channel.
Actually I don't care too much about setting the language for specific items in the feed, but rather I'd like to specify a primary language and a secondary language.

A: The specific RSS <language> element is only valid at the top level and specifies:

The language the channel is written in.

Atom uses the more general xml:lang attribute and makes clear that in can be used on any element:

Any element defined by this specification MAY have an xml:lang
attribute, whose content indicates the natural language for the
element and its descendents.

It would be acceptable to use xml:lang on specific items in an RSS feed. However, with RSS or Atom, your decision will largely be affected by whether clients pay attention to it.


text:
Q: Format Column Headers during Pipe Delimited Concatenation (Oracle SQL) Overview: I am tasked with providing a data extract from an Oracle database as a pipe-delimited output text file. I will be using SQLPlus to do this on the server where the data lives. Ordinarily, this task is not beyond my experience, but this time, the business desires column headers to be present.
Consider the following five columns that I need to output:
SELECT
    a.USER_NAME || '|'
    || a.LAST_NAME || '|'
    || a.FIRST_NAME || '|'
    || b.PRODUCT_PURCHASED || '|'
    || c.DATEPURCHASED
FROM ...
WHERE ... ;

This SQL works fine, where the output looks like:
omnusruthius|ruthius|omnus|stackoverflow_prod|19-APR-16

However, the business wants it to look like:
USER_NM|LAST|FIRST|PROD|EFFECTIVE_DATE
omnusruthius|ruthius|omnus|stackoverflow_prod|19-APR-16

Problem: So the objective here is essentially to output the first row with custom-named column headers (aliases), as shown above. So my first approach was to try something like:
    SELECT
    a.USER_NAME AS USER_NM || '|'
    || a.LAST_NAME AS LAST || '|'
    || a.FIRST_NAME AS FIRST || '|'
    || b.PRODUCT_PURCHASED AS PROD || '|'
    || c.DATEPURCHASED AS EFFECTIVE_DATE
    FROM ...
    WHERE ...

Unfortunately, I receive:

ORA-00923: FROM keyword not found where expected

I'm not sure how that would help anyway, as the original SQL output without aliases does not show column headers in the first row anyway. Remember, this is through the command line (SQLPlus), not Toad or some other RDMS.
So then I tried:
SELECT
   'USER_NM', 'LAST', 'FIRST', 'PROD', 'EFFECTIVE_DATE' FROM DUAL
UNION ALL
SELECT
    a.USER_NAME || '|'
    || a.LAST_NAME || '|'
    || a.FIRST_NAME || '|'
    || b.PRODUCT_PURCHASED || '|'
    || c.DATEPURCHASED
FROM ...
WHERE ...

Which gives the following error:

ORA-01789: query block has incorrect number of result columns

I feel so close to the solution, what am I missing here? Any help will be appreciated!
Edit: Just a note to a future reader, both answers here will help you solve this problem, but upon further tweaking, I realize we've all been overthinking the solution. I'm not going to propose a new solution as the change is trivial, but consider doing the following instead:
SELECT 'USER_NM|LAST|FIRST|PROD|EFFECTIVE_DATE' FROM DUAL;
SELECT a.USER_NAME AS USER_NM || '|'
|| a.LAST_NAME AS LAST || '|'
|| a.FIRST_NAME AS FIRST || '|'
|| b.PRODUCT_PURCHASED AS PROD || '|'
|| c.DATEPURCHASED AS EFFECTIVE_DATE
FROM ...
WHERE ...
ORDER BY ... ;

The key here is the use of the semicolons in SQL*Plus. That first SELECT statement is completely independent from the second; no UNION is necessary as the output of the first query is automatically displayed immediately before the output of the second query. Both can have their own rules, which is especially convenient if your latter query is much more complicated. I can confirm the above query is working, and I'm surprised it took me that long to make that realization...

A: When concatenating make sure the header is a single string. Because you are concatenating the values in columns to be on one row.
If comma separation is used, as you have it in the question, the result block should also have 5 columns,which is not the case.
SELECT
   'USER_NM|LAST|FIRST|PROD|EFFECTIVE_DATE' FROM DUAL
UNION ALL
SELECT
    a.USER_NAME || '|'
    || a.LAST_NAME || '|'
    || a.FIRST_NAME || '|'
    || b.PRODUCT_PURCHASED || '|'
    || c.DATEPURCHASED
FROM ...
WHERE ...

Edit: The columns can also be sorted.
SELECT 'USER_NM|LAST|FIRST|PROD|EFFECTIVE_DATE' FROM DUAL
UNION ALL
SELECT * FROM (
SELECT
    a.USER_NAME || '|'
    || a.LAST_NAME || '|'
    || a.FIRST_NAME || '|'
    || b.PRODUCT_PURCHASED || '|'
    || c.DATEPURCHASED
FROM ...
WHERE ...
ORDER BY DATEPURCHASED) --add any other columns needed

A: Since you tagged the question with SQL*Plus, you can use the PROMPT command to generate the header, which avoids complications ordering the results with a union:
PROMPT USER_NM|LAST|FIRST|PROD|EFFECTIVE_DATE

SELECT
a.USER_NAME AS USER_NM || '|'
|| a.LAST_NAME AS LAST || '|'
|| a.FIRST_NAME AS FIRST || '|'
|| b.PRODUCT_PURCHASED AS PROD || '|'
|| c.DATEPURCHASED AS EFFECTIVE_DATE
FROM ...
WHERE ...
ORDER BY ...

That takes the headings out of the SQL and into the client realm, where it arguably belongs. This also works in SQL Developer, and other clients may be able to do something similar. It won't work if you run the query on its own from another client, or over JDBC, or whatever; but then whatever is running the query can (and maybe should) provide the header in that case too.
If you aren't already, you could also consider doing SET HEADING OFF or SET PAGESIZE 0 to suppress the column headings from the query itself (though from what you said you're already doing that); and possibly SET EMBED OFF, though I don't think that's needed unless you do a separate query to generate the header line.


text:
Q: How to save data to generate primary key automatically I would like someone to modify the following code to save data to generate the primary key for each record automatically. PS. In the database,the ID column is the primary key and the Is Identity is set Yes.
Try
cmd = New SqlCommand("Insert into StudentDetails.programmes(ID,Programme,Form,AcademicYear,Class) values(@ID,@Programme,@Form,@AcademicYear,@Class)", cn)

cmd.Parameters.AddWithValue("@Programme", txtProgramme.Text)
cmd.Parameters.AddWithValue("@Form", txtForm.Text)
cmd.Parameters.AddWithValue("@AcademicYear", txtAcademicYear.Text)
cmd.Parameters.AddWithValue("@Class", txtClass.Text)

cmd.ExecuteNonQuery()

MessageBox.Show("Record successfully saved", "Saved", MessageBoxButtons.OK, MessageBoxIcon.Information)

A: Simply remove the ID from query. If not given, it will generate automatically.
cmd = New SqlCommand("Insert into StudentDetails.programmes(Programme,Form,AcademicYear,Class) values(@Programme,@Form,@AcademicYear,@Class)", cn)


text:
Q: How to get ML Agents to run in Unity? I've tried going through the documentation but the steps mentioned there aren't quite clear enough. Is there a good step by step video tutorial that can be helpful? The ones I saw on YouTube are pretty old and don't work with the latest updates on GitHub https://github.com/Unity-Technologies/ml-agents

A: This will help you to setup ml agent version 14.
https://github.com/Unity-Technologies/ml-agents/blob/master/docs/Installation.md
I am currently using this version.
I suggest you create a new python environment for only this purpose.
Don't use pip install mlagents in your python environment terminal. This is not updated to 14 when i installed it, so use the link above to see complete guide but here's the important stuff.
Download zip file
Ml Agents master
When you extract this Zip, you should open this extracted folder .
Then open cmd at that location. Activate your python environment and follow these steps:
You should install the packages from the cloned repo rather than from PyPi. To do this, you will need to install ml-agents and ml-agents-envs separately.Open cmd inside ml-agents=master folder and activate your python environment then, From the repo's root directory, run:
cd ml-agents-envs
pip3 install -e ./
cd ..
cd ml-agents
pip3 install -e ./

It is very important that both packages are installed from same ml agent folder, this will not work if the version are not compatible. if installed from same folder both packages will have same version i.e. 14 in this case.
These two packages will help you to use predefined PPo and SAC  algo.
I suppose you have installed 2018 or 2019 Unity. Open it and Goto File → Open project
Now in open dialog box select folder Project inside ml-agents-master folder that you have downloaded.

Sorry that most of the things are named project but don't be confused, earlier project was a folder inside ml-agents-master but after opening it you will see a Project toolbar. Follow Assets\ML-Agents\Examples\3DBall\Scenes now double click on 3Dball.
This will open a scene as you can see here. You can also see TFModels and Scirpts they are predefined neural network and code, respectively.

Select Agent in Hierarchy toolbar in left side (this will make change for only that instance of 3Dball it will be better to go to prefabs then double click on 3Dball this will open only one 3Dball whose settings will be applied on all instances now in hierarchy you will see only one 3Dball, now select it's Agent rest is same but now changes will affect all copies of 3Dball, prefabs are used to control all the copies this helps to train multiple agents at same time) then in right side Inspector view will open, inside Behaviors parameters you can see Model and a input in its box. Keep the agent selected otherwise this inspector view will disappear .
Now Goto TFModels folder, you will see a 3DBall file that looks like Neural network. Drag this to that Agent's Behavior parameters Model.
After Following all these steps Click on play option on top . Now the predefined model will start playing and you will see that it can balance the ball pretty well.
Now that you are able to see how trained model work and want to train again using predefined PPO and SAC, follow this
goto: ml-agents-master\config, here you will find a file trainer_config.yaml, now open cmd then activate your environment and enter code
mlagents-learn trainer_config.yaml --run-id=firstRun --train
When the message "Start training by pressing the Play button in the Unity Editor" is displayed on the screen, you can press the ▶ button in Unity to start training in the Editor. You can press Ctrl+C to stop the training, and your trained model will be at models run-identifier → behavior_name.nn where behavior_name is the name of the Behavior Name of the agents corresponding to the model.
Move your model file into Project/Assets/ML-Agents/Examples/3DBall/TFModels/.
Open the Unity Editor, and select the 3DBall scene as described above.
Select the 3DBall prefab Agent object.
Drag the <behavior_name>.nn file from the Project window of the Editor to the Model placeholder in the Ball3DAgent inspector window.
Press the ▶ button at the top of the Editor.
Now, for your own RL algorithm in python:
see this jupyter notebook it shows how we activate unity gym and get observations, rewards and reset environment. For this use can also create Unity executable, it's just creating exe files with some settings which you will find here

Hope this works without any issues. And Good Luck with this.


text:
Q: Pull deployment in Windows environment I'm looking for a way to setup pull deployment as apposed to the traditional push deployment model under Windows.
The optimal situation would be:

*

*Deploy the file(s) to the master server

*The child server would check to see if the master had an update at a given time or time interval.

*If the master server contains an update, then it would download the update and/or execute a script (something like nant?)

The solution needs to be as light weight as possible and must run under a Windows environment.
I've taken a look at Chef and SmartFrog but are not suited for this particular situation.
Edit: There are multiple pieces of software being deployed. These are database scripts, windows services and a web site. Each child will have it's own unique script as it's requirements and authentication details are different from the rest.
Edit 2:
So far people have come up with great answers but the end solution really does need to be secure, run internally and all happen at the same time. This is due to compliancing,  industry regulations and version issues (eg. db server out of sync with services). The end solution that I have in mind would be something like an FPT server on the master and Nant running on the children to execute the install routines (starting, stopping services, installing sql scripts, logging installs). This is the closest thing currently available, but is not ideal as nant works on a push basis (only executes when someone or program, eg. cruisecontrol, runs the script). I'm sure there has to be a solution to do a proper PULL deployment for Windows. Windows update and APT on Linux are great examples of pull deployment if you could do the the deployment across multiple servers all at the same time.

A: You say you want to do Windows Software Deployment and yet you talk about build scripting languages such as NAnt.  If it was me,  I'd write a Windows Installer package using InstallShield and take advantage of it's UpdateManager service to get the clients pulling updates from your update server.   These tools have been around and proven for a long time and will be far more secure then anything that you reinvent.

A: I'm not 100% clear on the type of app to be deployed - but if this is a Windows Forms application to be distributed to clients / end users, then you have looked at ClickOnce? This has modes for automatically polling and pulling down deltas from clients. But it seems that you are distributing to other servers?

A: A couple of years ago I've implemented a system that did about what you are looking for.
For the client application we used ClickOnce deployment which just works great. For the windows services and websites we had to implement our own system because we could find nothing that would work for us.
For the database we tried replication (sql2005), this didn't work out to well took a lot of time and processor power. We chose to make a backup and restore data (it was all readonly on client servers)
In a nutshell
1) The master server will hold several zipfiles with the new version of Webservices, Websites and databases.
2) The client servers windows service daily scan the master server (using ftp) for new versions of the software.
3) When found it would
- uninstall the windows service and replace the files and reinstall it
- replace website files
- replace the database

A: Windows Live Sync
Have you given any thought to windows live Sync?
Its free, and all you would have to do is set up two folders. One in your Master server and one in your Child server.
Once set up, all files will be automatically synced.
Update should be really easy, once you update your Master folder, it will automatically be replicated in the Child end.
It is totally fire and forget.
I use this system (one deployed on a server) with six 'child' nodes, syncing 1000's files daily with ease.
Edit 1:
Forgot to mention, the files are encrypted, and it uses reverse connection, so there is zero router/firewall configuration.

A: Are yoy running domain controller? So that you can jsut "advertise" them? Doesn;t get any lighter that that. Modify this line for your path to see the UI, but it should be scriptable as well - at leas in PowerShell.
"C:\Windows\SysWOW64\rundll32.exe" "C:\Windows\SysWOW64\shell32.dll",#44 "C:\Windows\SysWOW64\CCM\SMSRAP.cpl",Run Advertised Programs

A: I have used a combination of cruise control .net and subversion for this exact usage with lot success in the past.
Subversion is secure and will act as the master server. Cruise control .net fully support both subversion and nant. Of course it can do a lot more. We used to have very complicated logic due to the industry we were in and its requirements (utility).

A: I've heard of this situation before when I was talking to someone when I was in St. Louis for the "birthday party" of their website. I wonder if that was you.
In any case, I would use the Web Deployment Tool (MSDeploy) for this. MSDeploy is more like a sync tool then anything else. The concept is that you have a source and a dest, you want to sync them up. If you are doing a normal push deployment your build server would sync the output of some build with each target server. If you want to do a pull deployment, just drop the files you want into a shared location (you're calling this master server) then your client machine can  sync itself to that master server.
Here are some more details which you mentioned in your question:
Deploy files to master server
Your build server can use MSDeploy to deploy files to master server
The child server would check to see if the master had an update at a given time or time interval.
There is no direct support for this, but there are really two things here. Thing one: You can run MSDeploy from a script (.cmd/PowerShell/MSBuild/etc) and it can determine if there is a newer version. I would do this by dropping a version file at the top level of your output folder. Then when your script kicks off just read what version is on the server. If a newer one is available then kick off a new new deployment. Thing two: MSDeploy supports incremental deployment so even if you kick off a new deploy it will just not make any changes. This is tricky when you start talking about DB deployments though so in your case probably ill-advised, I would go with some flavor of Thing one.
If the master server contains an update, then it would download the update and/or execute a script
This is what msdeploy.exe is going to do for you.
Other related items

*

*Incremental publishing: If your web contains 1000 files but only 5 changed, then only those 5 get deployed

*Customization: MSDeploy supports parametrization, so when a client starts a sync you can provide the specific values for that client. With these you can change all types of files including web.conig/.xml files/text files/etc. You can even provide custom IIS settings

*Authentication: You can use normal windows auth if you are using IIS 7 you can create WMSvc users and use those.

*Security: WMSvc can be used for this

Does this suit your needs?


text:
Q: Reversing 32bit integer I was trying out a question which asked me to reverse a 32bit signed integer, I created this python program
input1=int(input("Enter the number: "))
binary=bin(input1).replace('0b','')
result=binary.zfill(32)
num=list(result)
num=num[::-1]
result=''.join(num)
ans=int(result,2)
print(ans)

This code passed one test case when the value of input1 was 2 but failed in second testcase, when the value of input1 was 1
Expected answer = -2147483648
My answer = 2147483648
What changes should I make in the code to make it pass second testcase ?

A: You need to look at the sign bit of the binary version of your number. You can do that by looking at the 0-indexed value of either your num variable or result.
input1 = int(input("Enter the number: "))
binary = bin(input1).replace('0b', '')
result = binary.zfill(32)
num = list(result)
num = num[::-1]
result = ''.join(num)
if num[0] == '0':
    ans = int(result, 2)
else:
    # flip the sign
    ans = -int(result, 2)

print(ans)

A: input1 = int(input("Enter the number: "))
binary = bin(input1 ).replace("0b","").zfill(32)
reverse = binary[::-1]
result = int(reverse,2)
print(result if reverse[0] == "0" else -result)


text:
Q: R - how to programmatically get number of citations for a research article? For data mining research literature in R, is there a way to retrieve the number of citations for an article (assuming I have a pmid, doi, or some other article identifier)?

A: Well... I came up with this:
#imagine the DOI is : 10.1097/PAI.0b013e3181ecaf1c
#so for google you need to substitute '/' for %2F

doi <- "10.1097/PAI.0b013e3181ecaf1c"
doi2 <- gsub("/", "%2F", doi)
thepage = readLines(paste('http://scholar.google.com.br/scholar?q=', doi2, sep=""))

theDOI <- thepage[grep(paste('doi:', doi, "|Cited by", thepage)]
citedBy <- gregexpr("Cited by", theDOI)

n_of_citations <- lapply(1:length(theDOI), function(x){
    substr(x=theDOI[[x]], start=citedBy[[x]], stop=citedBy[[x]]+10)
})

#usualy on google the first match is the correct result search... so..
n_of_citations[[1]]

[1] "Cited by 23"

is based on google result. However, not all results have the citation numbers, and not always the first result on google is the correct result...


text:
Q: How to include more JavaScript inside Atom editor by Github? I've been playing with snippets for Atom editor,
and see that I've learned I can include
JavaScript inside of a snippet, as my example shows.
(It inserts a TODO Comment with date)
TODO: (RAM) Fix this  -  2014-11-23 20:55
HELLO

How can I include MORE JavaScript.?
For example
inside the snippet to set
var= to something

or
call a JS library

or
ask for input from user i.e. confirm();

and proceed on basis of confirm() function.
Any help would be appreciated, I looked for a long time,
but not much documentation on this. Submlime Text's snippets allowed lots of code to be inserted via Python.
Thanks
~Rob
Inside file snippets.cson
'.source.js':

'Date TODO: insert':
'prefix': 'datetd'
'body': """
TODO: (RAM) $1  -  #{datetime = new Date(); datetime.getFullYear()}-#{(datetime.getMonth()+1)}-#{datetime.getDate()} #{datetime.getHours()}:#{datetime.getMinutes()}
 #{"hello".toUpperCase(); }
 $2
"""

A: Update: With the merge of atom/atom#4791, the capability of putting CoffeeScript code in CSON configuration files has been removed from Atom. The rest of the answer has been left intact for historic reference.
Actually, the syntax of the file is CoffeeScript (hence .cson as in CoffeeScript Object Notation), not JavaScript. It just so happens that you typed in JavaScript that is allowed as CoffeeScript. CoffeeScript doesn't use the var keyword, so you can assign variables like you did in your example:
datetime = new Date()

The other items, you'll probably have to get a little creative. I don't believe that the snippets package was intended to be used in this manner, which is why the lack of documentation on the "feature".


text:
Q: Is there a way to connect using a cipher suite not supported by the server? I have a C# application running on a Windows 2012 R2 server that needs to post requests to a partner.
It's failing at WebRequest.GetRequestStream() with The request was aborted: Could not create SSL/TLS secure channel.
I can get results through Postman on the same servers. My best guess is that the cause is from a mismatch of cipher suites.
From https://www.ssllabs.com/, the only supported cipher suites are:
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (0xc02f)   ECDH secp256r1 (eq. 3072 bits RSA)   FS    128
TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (0xc030)   ECDH secp256r1 (eq. 3072 bits RSA)   FS    256
These two aren't available with 2012 R2.
https://learn.microsoft.com/en-us/windows/win32/secauthn/tls-cipher-suites-in-windows-8-1
I'm seeing instructions on how to restrict cipher suites on the servers, but not adding them.
Is there a way to add new cipher suites from the program?

A: Please try this update on the server: https://support.microsoft.com/en-us/topic/update-adds-new-tls-cipher-suites-and-changes-cipher-suite-priorities-in-windows-8-1-and-windows-server-2012-r2-8e395e43-c8ef-27d8-b60c-0fc57d526d94 - While I cannot try it myself it looks promising.
The suites added are listed in the middle of this article.


text:
Q: Why std::pair calls explicit constructors in assignment Consider the following code:
#include<iostream>
#include<utility>

struct Base
{
    int baseint;
};

struct Der1 : Base
{
    int der1int;
    Der1() : der1int(1) {}
    explicit Der1(const Base& a) : Base(a), der1int(1)
    {
        std::cerr << "cc1" << std::endl;
    }
};

struct Der2 : Base
{
    int der2int;
    Der2() : der2int(2) {}
    explicit Der2(const Base& a) : Base(a), der2int(2)
    {
        std::cerr << "cc2" << std::endl;
    }
};

template <typename T, typename U>
struct MyPair
{
    T first;
    U second;
};

int main()
{
    Der1 d1;
    Der2 d2;

    std::pair<Der1, int> p1;
    std::pair<Der2, int> p2;

    p1 = p2; // This compiles successfully

    MyPair<Der1, int> mp1;
    MyPair<Der2, int> mp2;

    mp1 = mp2; // This will raise compiler error, as expected.
}

Tested under GCC 4.5.2
The reason lies in std::pair sources:
  /** There is also a templated copy ctor for the @c pair class itself.  */
  template<class _U1, class _U2>
    pair(const pair<_U1, _U2>& __p)
    : first(__p.first),
      second(__p.second) { }

Is that behaviour compliant with the C++ standard? For a first sight it looks inconsistent and counterintuitive. Do the other implementations of STL work the same way?

A: I am not sure that I understand the question, but basically you are asking why two unrelated std::pair can be implicitly convertible even if the instantiating types are not implicitly convertible. That is, why the implicitly convertible property of the instantiating types does not propagate to the pair.
The standard does not provide explicit assignment operators for the std::pair template, which means that it will use the implicitly generated assignment operator. To be able to assign pairs of convertible types, it relies on a templated constructor that allows an implicit conversion from std::pair<A,B> to std::pair<C,D>, the behavior of which is defined in §20.2.2 [lib.pairs]/4
template<class U, class V> pair(const pair<U, V> &p);

Effects: Initializes members from the corresponding members of the argument, performing implicit con-
  versions as needed.

The standard seems to only require the implementation to use implicit conversions, and in this particular implementation the conversion is actually explicit, which seems to contradict the wording of the standard.

A: As part of class std::pair the constructor
template<class T1, T2>
class pair
{
public:

    template<class _U1, class _U2>
    pair(const pair<_U1, _U2>& __p)
         : first(__p.first),
           second(__p.second)
    { }

};

is not a copy constructor, but a converting constructor from any pair<_U1, _U2> to pair<T1, T2>. This works for cases where the first and second members are convertible to the corresponding member of the other pair.
Converting each member separately is according to the standard.

A: This should really be a comment, but I prefer some room to type this out.
So, lets say we have two types:
typedef std::pair<A,B> pairAB;
typedef std::pair<S,T> pairST;

Now I want to assign one to the other:
pairAB x;
pairST w;

x = w; // how?

Since std::pair doesn't have an explicit assigment operator, we can only use the default assignment pairAB & operator=(const pairAB &). Thus we invoke the implicit conversion constructor, which is equivalent to:
x = pairAB(w);  // this happens when we say "x = w;"

However, has has been pointed out, this conversion constructor calls the explicit member constructors:
pairAB(const pairST & other) : first(other.first), second(other.second) { }

Thus for each member individually we do use explicit conversion.

A: Quick answer: Because the standard says it should.
Your next question, of course, will be: Why does the standard say so?
Imagine this line, which I think you agree should work:
std::pair<long, long> x = std::make_pair(3, 5);

But as 3 and 5 are ints, we are trying to assign a std::pair<int, int> to a std::pair<long, long>. Without a templated constructor and a templated assignment operator, it would fail, as your MyPair proved.
So to answer your question: the templated constructor is for convenience. Everyone expects to be able to assign an int to a long. So it is reasonable to be able to assign e.g. a pair of ints to a pair of longs.


text:
Q: What is the architecture of laptop's blinking light. I have an Asus R558u laptop When I put my laptop on sleep mode, the light starts to blink which is fine. But even after 10 hours of leaving it uncharged, the battery is retained very well. I want to know what is the architecture behind this power saving design.

A: It is called ACPI.  10 hours is nothing.. I have a tiny laptop that sat in a sleep state for 22 days before running out of power.  Even then, the operating system used the last little bit of power to hibernate so I STILL didn't lose any data.
In addition to the hardware allowing it (ACPI), the operating systems keep getting better and better at power management.
BTW, the blinking LED takes almost no power.. keeping the ram powered is where much of the battery goes when it is in a sleep state.
Read about ACPI  here


text:
Q: Exception on Startup with Neo4j 2.0 with Spring Data 3.0 Rest I'm trying to upgrade to Neo4j 2.0, and Spring Data 3.0. I'm getting a null pointer when the application starts, before any of my code is executed.
Caused by: org.springframework.dao.InvalidDataAccessResourceUsageException: Error executing statement MATCH (ref:ReferenceNode {name:{name}}) RETURN ref; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: Error executing statement MATCH (ref:ReferenceNode {name:{name}}) RETURN ref; nested exception is java.lang.NullPointerException
at org.springframework.data.neo4j.support.query.CypherQueryEngine.query(CypherQueryEngine.java:56)
at org.springframework.data.neo4j.support.ReferenceNodes.executeQuery(ReferenceNodes.java:77)
at org.springframework.data.neo4j.support.ReferenceNodes.getReferenceNode(ReferenceNodes.java:81)
at org.springframework.data.neo4j.support.typerepresentation.SubReferenceNodeTypeRepresentationStrategy.isStrategyAlreadyInUse(SubReferenceNodeTypeRepresentationStrategy.java:95)
at org.springframework.data.neo4j.support.typerepresentation.TypeRepresentationStrategyFactory.chooseStrategy(TypeRepresentationStrategyFactory.java:56)
at org.springframework.data.neo4j.support.typerepresentation.TypeRepresentationStrategyFactory.<init>(TypeRepresentationStrategyFactory.java:39)
at org.springframework.data.neo4j.config.Neo4jConfiguration.typeRepresentationStrategyFactory(Neo4jConfiguration.java:146)
at org.springframework.data.neo4j.config.Neo4jConfiguration$$EnhancerByCGLIB$$4b018b97.CGLIB$typeRepresentationStrategyFactory$6(<generated>)
at org.springframework.data.neo4j.config.Neo4jConfiguration$$EnhancerByCGLIB$$4b018b97$$FastClassByCGLIB$$5306fd26.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:286)
at org.springframework.data.neo4j.config.Neo4jConfiguration$$EnhancerByCGLIB$$4b018b97.typeRepresentationStrategyFactory(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:160)
... 112 more
Caused by: org.springframework.dao.InvalidDataAccessResourceUsageException: Error executing statement MATCH (ref:ReferenceNode {name:{name}}) RETURN ref; nested exception is java.lang.NullPointerException
at org.springframework.data.neo4j.support.query.CypherQueryEngine.parseAndExecuteQuery(CypherQueryEngine.java:67)
at org.springframework.data.neo4j.support.query.CypherQueryEngine.query(CypherQueryEngine.java:53)
... 128 more
Caused by: java.lang.NullPointerException
at org.neo4j.cypher.ExecutionEngine.prepare(ExecutionEngine.scala:75)
at org.neo4j.cypher.ExecutionEngine.execute(ExecutionEngine.scala:60)
at org.neo4j.cypher.ExecutionEngine.execute(ExecutionEngine.scala:65)
at org.neo4j.cypher.javacompat.ExecutionEngine.execute(ExecutionEngine.java:78)
at org.springframework.data.neo4j.support.query.CypherQueryEngine.parseAndExecuteQuery(CypherQueryEngine.java:65)
... 129 more

Neo4j and spring-data dependencies on Pom.xml
<properties>
    <spring.version>3.2.6.RELEASE</spring.version>
    <springSecurity.version>3.2.0.RELEASE</springSecurity.version>
    <jackson.version>1.9.13</jackson.version>
    <neo4j.version>2.0.0</neo4j.version>
    <springDataNeo4j.version>3.0.0.RC1</springDataNeo4j.version>
    <neo4j-rest-graphdb.version>2.0.0</neo4j-rest-graphdb.version>
</properties>
<!--Neo4j-->
    <dependency>
        <groupId>org.neo4j</groupId>
        <artifactId>neo4j</artifactId>
        <version>${neo4j.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-neo4j</artifactId>
        <version>${springDataNeo4j.version}</version>
    </dependency>

    <dependency>
        <groupId>org.neo4j</groupId>
        <artifactId>neo4j-rest-graphdb</artifactId>
        <version>${neo4j-rest-graphdb.version}</version>
    </dependency>

Context file
<neo4j:config graphDatabaseService="graphDatabaseService" />

<bean id="graphDatabaseService" class="org.neo4j.rest.graphdb.RestGraphDatabase">
    <constructor-arg value="http://localhost:7474/db/data"/>
</bean>

<context:annotation-config />

Neo4j is up and running.
When connecting through http://localhost:7474/browser/ everything works fine, including the offending query MATCH (ref:ReferenceNode {name:{name}}) RETURN ref;

A: I believe that you don't need any org.neo4j.* dependencies. Maybe it would work with only <artifactId>spring-data-neo4j</artifactId> and <artifactId>spring-data-neo4j-rest</artifactId>. This is the configuration you should try :
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-neo4j</artifactId>
    <version>3.0.0.RC1</version>
</dependency>
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-neo4j-rest</artifactId>
    <version>3.0.0.RC1</version>
</dependency>

Update
What is sure is that the error message is generated by org.springframework.data.neo4j.support.ReferenceNodes in getReferenceNode (http://bit.ly/1eDYlYS).
The getReferenceNode method is called only from one place in SDN, at org.springframework.data.neo4j.support.typerepresentation.SubReferenceNodeTypeRepresentationStrategy (http://bit.ly/LW5gly).
This call is looking for a node with label :ReferenceNode and an attribute name equal to root.
So I would suggest trying to create such a node using Cypher :
CREATE (n:ReferenceNode {name:"root"}) RETURN n;

and see if the error still happens.


text:
Q: Why is DocumentsContract.getTreeDocumentId(uri) giving me the doc ID for a parent of the Uri argument? The app sends the user to SAF picker with ACTION_OPEN_DOCUMENT_TREE:
void openStoragePicker() {
    String messageTitle = "Choose directory app to use";
    Intent intent = new Intent(ACTION_OPEN_DOCUMENT_TREE);
    startActivityForResult(Intent.createChooser(intent, messageTitle), Dry.REQUEST_CHOOSE_APP_DIR);
}

In onActivityResult, we take persistable permission and store a String of the Uri:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
    switch (resultCode) {
        case Activity.RESULT_OK:
            if (requestCode == Dry.REQUEST_CHOOSE_APP_DIR) {
                if (resultData == null) {
                    Log.d(Dry.TAG, "result data null");
                } else {
                    if (resultData.getData() != null) {
                        Uri uri = resultData.getData();
                        Storage.releasePersistedPermissions(this);
                        getContentResolver().takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                        Storage.setSharedPrefString(uri.toString(), Storage.SHARED_PREF_APP_DIR_URI, this);
                        dbw.clearAlreadyPlayed();
                    }
                }
            }
            break;
        case Activity.RESULT_CANCELED:
            //
            break;
    }
}

We recreate the tree Uri when we need it:
static Uri getTheDir(Context context) {
    String result = Storage.getSharedPrefString(SHARED_PREF_APP_DIR_URI, context);
    if (result == DEFAULT_SHARED_PREF_STRING) {
        return null;
    }
    Uri dirUriParsed = Uri.parse(Uri.decode(result));
    Log.d(Dry.TAG, "the dir uri parsed: " + dirUriParsed.toPath());
    return dirUriParsed;
}

We want to list the files, and we can, using the pattern shown here.
static ArrayList<String> getFiles(Context context) {
    ArrayList<String> fileStrings = new ArrayList<>();
    Uri rootUri = getTheDir(context);
    if (rootUri == null) {
        return fileStrings;
    }

    long startTime = System.currentTimeMillis();

    ContentResolver contentResolver = context.getContentResolver();
    String theDocToReturnChildrenFor = DocumentsContract.getTreeDocumentId(rootUri);
    Log.d(Dry.TAG, "theDocToReturnChildrenFor: " + theDocToReturnChildrenFor);
    Uri childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(rootUri, theDocToReturnChildrenFor);
    List<Uri> dirNodes = new LinkedList<>();
    dirNodes.add(childrenUri);
    while(!dirNodes.isEmpty()) {
        childrenUri = dirNodes.remove(0);
        Cursor c = contentResolver.query(childrenUri, new String[]{DocumentsContract.Document.COLUMN_DOCUMENT_ID, DocumentsContract.Document.COLUMN_DISPLAY_NAME, DocumentsContract.Document.COLUMN_MIME_TYPE}, null, null, null);
        try {
            while (c.moveToNext()) {
                final String docId = c.getString(0);
                final String name = c.getString(1);
                final String mime = c.getString(2);
                if (isDirectory(mime)) {
                    if (Arrays.asList(SUBDIRECTORIES_TO_OMIT).contains(name)) {
                        continue;
                    }
                    final Uri newNode = DocumentsContract.buildChildDocumentsUriUsingTree(rootUri, docId);
                    dirNodes.add(newNode);
                } else {
                    for (String ext: SUPPORTED_FILE_EXTENSIONS) {
                        if (name.endsWith(ext)) {
                            fileStrings.add(docId);
                            break;
                        }
                    }
                }
            }
        } finally {
            closeQuietly(c);
        }
    }

    Log.d(Dry.TAG, "fileStrings length: " + fileStrings.size() + "time spent building song list: " + ((System.currentTimeMillis() - startTime) / 1000.0) + "s");
    return fileStrings;
}

But, this only works as expected when the directory happens to be a top-level directory within the storage volume. If the directory that the user chose is not a direct child of the volume root, then, when we try DocumentsContract.getTreeDocumentId(rootUri), it returns not the document ID for that URI, but rather the document ID for its highest parent before the volume root!
The log call that prints the reconstructed Uri gives this output:

the dir uri parsed: /tree/primary:a test dir/a child test dir/3rd level dir

But the other log call that prints the doc ID prints this:

theDocToReturnChildrenFor: primary:a test dir

Am I doing it wong? Is this an Android bug? I noticed this question describes the exact same behavior from this method. That issue was solvable by following the established recursive listing pattern, but, that user says:

It is almost like getTreeDocumentId(rootUri) is returning what getRootId(rootUri) should be returning.

The docs for this method are not helpful, they are brief and have a typo, leaving the meaning unclear. DocumentsContract.getTreeDocumentId docs.
Target SDK of the app is 30. The device Android version is also api 30 (Android 11).
If someone could help me to get the correct doc ID for the user-selected directory, I would appreciate it.

A:

Uri dirUriParsed = Uri.parse(Uri.decode(result))

Try:
  Uri dirUriParsed = Uri.parse(result)


text:
Q: "We have eaten breakfast together every morning since our honeymoon."
We have eaten breakfast together every morning since our honeymoon. (I don't understand it.)

We have been eating breakfast together every morning since our honeymoon. (I understand it.)

Is there a difference in meaning between them?
For me the second sentence looks much better. I could understand the first sentence if it were "We have eaten every breakfast together since our honeymoon." This way it would sound like "We have gained every score in this game since the beginning."
What prevents me from understanding the first one is that to eat something every morning is a habitual action and it calls for Present Simple:

We eat breakfast together every morning since our honeymoon.

By the way, is this sentence correct?

A: You're using the present perfect tense in the first, and the present perfect progressive in the second.
present perfect tense

1. "We have eaten breakfast together every morning since our honeymoon."

This means as a married couple, you and your spouse have never spent a single breakfast alone from the first day of your marriage until the present day. The action is repeated, and does not exclude the fact that having breakfast together requires a certain duration of time.
Perfectly acceptable, although an unlikely situation if the marriage is older than six months. (I'm joking!)
Present perfect *progressive/continuous* tense

2. We have been eating breakfast together every morning since our honeymoon.

Literally, this could be interpreted as both of you eating breakfast non-stop since day one of your marriage.
This of course does not make sense; however, the fact you have inserted every morning means the action is being repeated, it is not uninterrupted as it might appear at first glance. You need to avoid this ambiguity, native speakers will tend to do this automatically without thinking.
Opting for:
Present perfect

"We have eaten breakfast together every morning since our honeymoon."

or
Present perfect

"We have always had/eaten breakfast together since the day of our honeymoon."

or
Simple present

We always have breakfast together; ever since our honeymoon.

(Insert always to emphasize an action is repeated regularly).

A: I started to write, "The second one, though likely to be understood in context, would actually be one long breakfast that never ended." I then thought about it some more: They both actually mean the same thing; both are natural and, as far as I can tell, grammatically correct.


text:
Q: How to consume an API from MVC view in .NET Core api? I'm building a web API and I want to consume it through an MVC view. The API controller is to insert the user data and the MVC controller is to create the view. I have been looking for information and this is what I have been able to do with that information.
So, the API controller, simply inserts the data to the database through an stored procedure, I've tested with Postman and works fine:
[Route("api/[controller]")]
[ApiController]

public class UserController : ControllerBase
{
    [HttpPost]
    public IActionResult post(Models.Request.UserModel model)
    {
        using (Models.AdminOrchardContext db = new Models.AdminOrchardContext())
        {
            Models.UserModel oUsuar = new Models.UserModel();

            Models.OrchardTable tOrchard = new Models.OrchardTable();

            oUsuar.Name = model.Name;
            oUsuar.Email = model.Email;
            tOrchard.OrchardLocation = model.OrchardLocation;

            var uName = new SqlParameter("@name", oUsuar.Name);
            var uEmail = new SqlParameter("@email", oUsuar.Email);
            var hOrchardLocation = new SqlParameter("@OrchardLocation", tOrchard.OrchardLocation);

            var idUserReg = db.Usuarios.FromSqlRaw("Exec UserAndOrchardInsert @name, @email" +
                "@OrchardLocation",
                new[] { uName, uEmail, hOrchardLocation});

            db.SaveChanges();

        }
        return Ok();
    }
 }

The MVC controller where the view is added, from here the API is used with the user data on the view:
    [HttpPost]
    public IActionResult post(Models.Request.User model)
    {
        HttpClient hc = new HttpClient();
        hc.BaseAddress = new Uri("https://localhost:44325/api/User");

        var addRecToDB = hc.PostAsJsonAsync<Models.Request.User>("User", model);

        addRecToDB.Wait();

        ViewBag.message = "Ok!";

        return View();
    }

And the view:
@model Huerbog.Models.Request.User

@{
    ViewData["Title"] = "post";
 }

User registration

        <form asp-action="post">

                <input asp-for="Name" class="form-control" />

                <input asp-for="Email" class="form-control" />

Orchard-related field

                <input asp-for="OrchardLocation" class="form-control" />

                <input type="submit" value="Create" class="btn btn-primary" />

        </form>

@ViewBag.message

    Back to List

@section Scripts {
     @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Now, the problem is that when I open the view, even when the API is running, on the page appears the Error 405, I don't know what or where exactly is the error.

A:
the problem is that when I open the view, even when the API is running, on the page appears the Error 405, I don't know what or where exactly is the error.

Please note that your action post contains the [HttpPost] attribute, which constrains matching to HTTP Post request(s) only.
While you enter URL to access https://xxx/controller_name/post from browser side, browser would help make HTTP Get request to server, which cause 405 Method Not Allowed error.
To fix it, you can try to add a HttpGet post method to make the endpoint support HTTP Get method request(s), like below.
[HttpGet]
public IActionResult post()
{
    return View();
}

[HttpPost]
public IActionResult post(Models.Request.User model)
{
    //...


text:
Q: Laravel Performance issue in Production server Hi i just put my app in production and the laravel application is very slow, even slow then in my local server.
May i know any trips and tricks to increase peformance.

A: Run this in command line to boost the performance
   composer dump-autoload
php artisan clear-compiled
php artisan config:cache
php artisan route:cache
php artisan optimize --force


text:
Q: How to add the fetched file time to the text column? This is a text that stores the download address and it looks like this.
http://speedtest.newark.linode.com/100MB-newark.bin
http://speedtest.dallas.linode.com/100MB-dallas.bin
http://speedtest.london.linode.com/100MB-london.bin
http://speedtest.tokyo2.linode.com/100MB-tokyo2.bin

I would like to get the modification time of the download link and add it to the front of the download address.
This is the expected result.
2020-11-22 22:01:38 http://speedtest.newark.linode.com/100MB-newark.bin
2020-08-09 14:18:58 http://speedtest.dallas.linode.com/100MB-dallas.bin
2020-11-22 16:25:05 http://speedtest.london.linode.com/100MB-london.bin
2020-08-09 00:26:50 http://speedtest.tokyo2.linode.com/100MB-tokyo2.bin

I know I can get the file time through the http header, which is the query command.
curl -sLI link | grep -i '^Last-Modified' | cut -c16- | date -f- '+%Y-%m-%d %T'

So the question is, how do I add the query results to the file column?
Any help, thanks in advance!

A: first get all links' Last-Modified timestamp to a file then paste them together doing as following:
<links.txt xargs -L -n1 -I{} curl -sLI {} |grep -i '^Last-Modified' |cut -c16- |date -f- '+%Y-%m-%d %T' >last.modifiedOutput
paste -d' ' last.modifedOutput links.txt


text:
Q: Login and Registration error 3840 I'm following along on this tutorial
http://www.raywenderlich.com/13511/how-to-create-an-app-like-instagram-with-a-web-service-backend-part-12 and got to the part where you implement the login and registration through Objective-c. Every time I press register or login I receive an error saying "The operation couldn't be completed. (cocoa error 3840). Also I'm not getting an error back in xcode. Help please
I just checked the mysql database and it inserts a user id but no text into username and password field

A: This error can occur when the program encounters invalid JSON in the response. To determine if the JSON response is valid, use a tool like HTTPSnoop to examine the output of the PHP script.


text:
Q: Session object doesn't work inside Flask stream_with_context function I am creating the web app, which will process data, so I am using Server Sent Event in Flask.
I need to store session variable in a SSE function, but flask doesn't see it outside the function. Can I fix it somehow?
MWE:
server.py:
from flask import Flask, render_template, session, Response, stream_with_context
import time

app = Flask(__name__)
app.secret_key = b'132d2dcf59f9604c0b48e4e3a1a1cd19a0abf121b48a4777'

@app.route('/')
def get_page():
    return render_template('progress.html')

@app.route('/progress')
def progress():
    def generate():
        x = 0
        while x < 100:
            x = x + 10
            print(x)
            time.sleep(0.2)
            yield "data:" + str(x) + "\n\n"
        session['result'] = x
        print(session['result']) #100
    return Response(stream_with_context(generate()), mimetype= 'text/event-stream')

@app.route('/done')
def done():
    print(session['result']) #KeyError: 'result'
    return session['result']

if __name__ == '__main__':
    app.run(debug=True)

progress.html:
<!DOCTYPE html>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

A: The session is a cookie.  Cookies are sent as headers.  Headers are sent first in a response, before the rest of the stream is sent.  You can't modify the session after beginning the response.  Send whatever data you need to in the stream, and handle it on the receiving end.


text:
Q: Get all retweets of a certain tweet with Twitter4J As the title suggests, I'm trying to get all the retweets of a certain tweet.
I'm aware of getRetweets but it returns only 100 of the first retweets.
I'm not even sure this is possible without some elevated perms since this limitation appears to be there to prevent overloading, but if it I'd be happy for some help.
Thanks in advance.

A: This appears to be a limitation of the Twitter API, not twitter4j
https://dev.twitter.com/docs/api/1/get/statuses/retweets/:id


text:
Q: How to get full response or set pagination using Microsoft Graph API? I am not sure if my API has the limit for the response.
My Graph API is the following.
https://graph.microsoft.com/v1.0/sites/{site-id}/drive/items/{folder-id}/children
Actually, the children has more than 1,500 results(folders and files), but it responses only 1206 results.
Does the API provide limited response?
I tried to add some filters including $top, $skip, etc, but they were not working.
And when I tried to add ?$skip=1000 to get skip 1,000 results, but it was saying the error.

Please let me know what I should do to get full results or add some filters to paginate using the API.
Thank you.

A: Drive apis have service limitations as mentioned here, https://learn.microsoft.com/en-us/graph/throttling#files-and-lists-service-limits and here is the guidance on how to handle throttling issues - https://learn.microsoft.com/en-us/graph/throttling#files-and-lists-service-limits
This method supports the $expand and $select OData query parameters to customize the response.

A: I found the answer. I should use "@odata.nextLink" property while it does exist.
You could refer to the doc.


text:
Q: onEvent() is not being called? I am passing data from AsyncTask to a fragment of tabbed activity. Why onEvent() of EventBus is not being called?
BackgroundWorker.java doInBackground() is called by MainActivity
public class BackgroundWorker extends AsyncTask<String,Void,String> {

   @Override
   protected void onPostExecute(String line) {
     userResult =  line.split(" ");
     String result = userResult[0];

     if(result.equals("Success")){
       CustomMessageEvent event = new CustomMessageEvent();
       event.setCustomMessage(line);
       Intent intent = new Intent(context,TabActivity.class);
       intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
       context.startActivity(intent);
       EventBus.getDefault().post(event);
     }
   }
}

ProfileTab.java This file is a fragment of tabbed activity. Is there anything that should be done in tabbed activity or should doInBackground must be called again.
public class ProfileTab extends Fragment {

  public TextView t1;
  private View rootView;

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.profile, container, false);

    t1 = (TextView) rootView.findViewById(R.id.textView4);

    EventBus.getDefault().register(this);
    Log.d(TAG, "onCreateView: ");

    return rootView;
  }

  @Subscribe(threadMode = ThreadMode.ASYNC)
  public void onEventAsync(CustomMessageEvent event) {
    Log.d(TAG, "onEvent: ");
    t1.setText(event.getCustomMessage());
  }

}

Tried LocalBroadcastManager and the result was same, onReceive() was not called. Where am I going wrong?

A: If you start Activity in your onPostExecute, I suggest pass data by intent, not events - it is simpler.
Your subscribed method isn't called, because event is posted before you register -  use postSticky instead of post, and you will get an event.
I assume, you want to pass line (String). So construct intent:
Intent intent = new Intent(context,TabActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("LINE", line);
context.startActivity(intent);

Than, in your TabActivity in onCreate read passed value:
String line = getIntent().getStringExtra("LINE", "");