text:
Q: Is this proper use of Mongoose statics? I'm in the process of creating a template to generate a Mongoose / MongoDB web service from an existing database.  I've read some docs on statics vs methods and I'm wondering if the example below would work long-term.
What should be changed to be useful in a production MongoDB / Mongoose environment?
The actual template is located here:

*

*Template Source

*Output Sample

/**
* Generated by fredl_000 on 2/23/2015 12:08:25 PM
* Copyright 2015 Fred Lackey
* Direct questions to the author: Fred Lackey <fred.lackey@gmail.com>
*/
var moment = require('moment'),
    mongoose = require('mongoose'),
    strings = require('dzstrings');
    uids = require('dzuuids');

var signupRequestSchema = new mongoose.Schema({
    _id: { type: String, trim: true, uppercase: true, default: uids.newUid, required: false },
    emailAddress: { type: String, trim: true, required: false },
    confirmationCode: { type: String, trim: true, required: false },
    _k: { type: Date, default: null, required: true }
});

signupRequestSchema.index({
    emailAddress: 1,
    _k: 1
}, { unique: true });

signupRequestSchema.statics.validateItem = function(item, callback) {
    if (typeof item == 'undefined'){ return callback(new Error('No item to validate')); }
    if (typeof item._id != 'undefined'){ if (!strings.isValidString(item._id)){ return callback(new Error('_id (id) is not a valid String')); } else { item._id = strings.trimToNull(item._id); } }
    if (typeof item.emailAddress != 'undefined'){ if (!strings.isValidString(item.emailAddress)){ return callback(new Error('emailAddress is not a valid String')); } else { item.emailAddress = strings.trimToNull(item.emailAddress); } }
    if (typeof item.confirmationCode != 'undefined'){ if (!strings.isValidString(item.confirmationCode)){ return callback(new Error('confirmationCode is not a valid String')); } else { item.confirmationCode = strings.trimToNull(item.confirmationCode); } }
    if (typeof item._k != 'undefined'){ if (!strings.DateOrNull(item._k)){ return callback(new Error('_k (auditDeletedDate) is not a valid Date or null value')); } else {  } }
    return callback(null, item);
};

signupRequestSchema.statics.toDto = function(item, callback) {
    if (!item){ return callback(new Error('No item to convert')); }
    var dto = {};
    if (typeof item._id != 'undefined'){ dto.id = item._id; }
    if (typeof item.emailAddress != 'undefined'){ dto.emailAddress = item.emailAddress; }
    if (typeof item.confirmationCode != 'undefined'){ dto.confirmationCode = item.confirmationCode; }
    if (typeof item._k != 'undefined'){ dto.auditDeletedDate = item._k; }
    return dto;
};

signupRequestSchema.statics.toDtoFull = function(item, callback) {
    if (!item){ return callback(new Error('No item to convert')); }
    var dto = {
        id: ((typeof item._id != 'undefined') ? item._id : null),
        emailAddress: ((typeof item.emailAddress != 'undefined') ? item.emailAddress : null),
        confirmationCode: ((typeof item.confirmationCode != 'undefined') ? item.confirmationCode : null),
        auditDeletedDate: ((typeof item._k != 'undefined') ? item._k : null)
    };
    return dto;
};

signupRequestSchema.statics.toItem = function(dto, callback) {
    if (!dto){ return callback(new Error('No DTO to convert')); }
    var item = {};
    if (typeof dto.id != 'undefined'){ item._id = dto.id; }
    if (typeof dto.emailAddress != 'undefined'){ item.emailAddress = dto.emailAddress; }
    if (typeof dto.confirmationCode != 'undefined'){ item.confirmationCode = dto.confirmationCode; }
    if (typeof dto.auditDeletedDate != 'undefined'){ item._k = dto.auditDeletedDate; }
    return item;
};

signupRequestSchema.statics.toItemFull = function(dto, callback) {
    if (!dto){ return callback(new Error('No DTO to convert')); }
    var item = {
        _id: ((typeof dto.id != 'undefined') ? dto.id : null),
        emailAddress: ((typeof dto.emailAddress != 'undefined') ? dto.emailAddress : null),
        confirmationCode: ((typeof dto.confirmationCode != 'undefined') ? dto.confirmationCode : null),
        _k: ((typeof dto.auditDeletedDate != 'undefined') ? dto.auditDeletedDate : null)
    };
    return item;
};

signupRequestSchema.statics.getById = function(id, callback) {
    var query = { _id: id, _k: null };
    signupRequestSchema.statics.validateItem(query, function(err){
        if (err){ return callback(err); }
        return this.findOne(query, function(err, item){
            if (err){ return callback(err); }
            return signupRequestSchema.statics.toDto(item);
        });
    });
};

signupRequestSchema.statics.getOneByEmailAddress = function(emailAddress, callback) {
    var query = {
        emailAddress: emailAddress,
        _k: null
    };
    signupRequestSchema.statics.validateItem(query, function(err){
        if (err){ return callback(err); }
        return this.findOne(query, function(err, item){
            if (err){ return callback(err); }
            return signupRequestSchema.statics.toDto(item);
        });
    });
};

signupRequestSchema.statics.create = function(emailAddress, confirmationCode, callback) {
    var data = {
        emailAddress: emailAddress,
        confirmationCode: confirmationCode,
        _k: null
    };
    signupRequestSchema.statics.validateItem(query, function(err){
        if (err){ return callback(err); }
        var newItem = new this(data);
        newItem.save(function(err, item){
            if (err){ return callback(err); }
            return signupRequestSchema.statics.toDto(item);
        });
    });
};

signupRequestSchema.statics.init = function(emailAddress, confirmationCode, suppressError, callback) {
    var dupErr = suppressError ? null : (new Error('Duplicate Signup Request detected'));
    signupRequestSchema.statics.getOneByEmailAddress(emailAddress, function(err, existing){
        if (err){ return callback(err); }
        if (existing){ return callback(dupErr, existing); }
        signupRequestSchema.statics.create(emailAddress, confirmationCode, callback);
    });
};

signupRequestSchema.statics.modify = function(queryDto, updateDto, callback) {
    if (!updateDto){ return callback(new Error('Nothing to update')); }
    signupRequestSchema.statics.toItem(queryDto, function(err, query){
        if (err){ return callback(new Error('Problem with query: ' + err.message)); }
        signupRequestSchema.statics.toItem(updateDto, function(err, query){
            if (err){ return callback(new Error('Problem with update: ' + err.message)); }
            return this.findAndUpdate(query, update, function(err, items){
                if (err){ return callback(err); }
                return signupRequestSchema.statics.toDtos(items);
            });
        });
    });
};

signupRequestSchema.statics.modifyOne = function(queryDto, updateDto, callback) {
    if (!updateDto){ return callback(new Error('Nothing to update')); }
    signupRequestSchema.statics.toItem(queryDto, function(err, query){
        if (err){ return callback(new Error('Problem with query: ' + err.message)); }
        signupRequestSchema.statics.toItem(updateDto, function(err, query){
            if (err){ return callback(new Error('Problem with update: ' + err.message)); }
            return this.findOneAndUpdate(query, update, function(err, item){
                if (err){ return callback(err); }
                return signupRequestSchema.statics.toDto(item);
            });
        });
    });
};

signupRequestSchema.statics.delete = function(queryDto, callback) {
    var updateDto = { auditDeletedDate: moment().utc().toDate() };
    signupRequestSchema.statics.modify(queryDto, updateDto, callback);
};

signupRequestSchema.statics.deleteOne = function(queryDto, callback) {
    var updateDto = { auditDeletedDate: moment().utc().toDate() };
    signupRequestSchema.statics.modifyOne(queryDto, updateDto, callback);
};

var model = mongoose.model('SignupRequest', signupRequestSchema);

module.exports = model;


text:
Q: How to define multi-argument decorators within a class in 2.6 Generally don't do OO-programming in Python.  This project requires it and am running into a bit of trouble.  Here's my scratch code for attempting to figure out where it went wrong:
class trial(object):
    def output( func, x ):
        def ya( self, y ):
            return func( self, x ) + y
        return ya
    def f1( func ):
        return output( func, 1 )
    @f1
    def sum1( self, x ):
        return x

which doesn't compile.  I've attempted to add the @staticmethod tag to the "output" and "f1" functions but to no avail.  Normally I'd do this
def output( func, x ):
    def ya( y ):
        return func( x ) + y
    return ya

def f1( func ):
    return output( func, 1 )

@f1
def sum1( x ):
    return x

which does work.  So how do I get this going in a class?

A: There's no need for your method decorators to be a part of the class:
def output(meth, x):
    def ya(self, y):
        return meth(self, x) + y
    return ya

def f1(meth):
    return output(meth, 1)

class trial(object):
    @f1
    def sum1( self, x ):
        return x

>>> trial().sum1(1)
2

I tend to use meth instead of func in decorators I know I'll be applying to methods, just to try to keep it straight in my own head.

A: Try this ugly solution
class trial(object):

    def __init__(self):
        #doing this instead of @ statement
        self.sum1 = self.f1(self.sum1)

    def output(self, func, x ):
        def ya(y):
            return func(x) + y
        return ya

    def f1(self, func):
        return self.output( func, 1 )

    def sum1(self, x ):
        return x

t = trial()

print t.sum1(5)

A: No way.
This is a wrong design.
Follow for The Zen of Python
When you decorate a function calling the decorator by @ it must be already defined.
You must at first - define decorator and at the second step decorate a function.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to push new data from Realtime Database to Cloud Firestore? I am pushing data to Firebase via Zapier and it lands in the Realtime Database. However, I am using Cloud Firestore. I've looked through a lot of documentation for both services but neither seems to have answers.. (there is information on migrating but I would like to keep both DBs).
How would I push each new or updated data entry from Realtime Database to Cloud Firestore?

A: There is nothing built into Firebase to automatically do this.
The fastest I can think of is to build a Cloud Function that listens for the Realtime Database writes, and then also sends them to Firestore.
Alternatively, doesn't Zapier allow you to have two zaps, one that writes to each database?


text:
Q: Is it possible to automate the TeamCity Pin Functionality on a "Run Custom Build" I'm using TeamCity with a build step to tag a certain build into SVN if I run a Custom Build with one of the flags set to true.
However, after this build has completed, I would like to automate TeamCity to pin the just-created custom build. Is this possible? I've read about the REST API, but I am not sure if it's the solution.

A: I figured it out by using the REST API instead of utilizing the plugins.
By creating a Command Line build step using the Custom Script field, you can use cURL to effectively pin builds. There might be some modifications required to pin a build that is already running.
This curl call pins the build:
curl -v --request PUT %teamcity.serverUrl%/httpAuth/app/rest/builds/id:%teamcity.build.id%/pin -u "TCuser:TCpass"

This curl call adds/edits the tags for the specific build:
curl -v -H "Content-Type:text/plain" -d "Deliverable" %teamcity.serverUrl%/httpAuth/app/rest/builds/id:%teamcity.build.id%/tags -u "TCuser:TCpass"

Also you should make sure to install/place a curl executable on the build agent so that you can call curl as a command line tool.

A: REST is the only way to do that without writing java code. Or you can write a plugin which listens for buildFinished event and pins the build if it has particular property.


text:
Q: How can I use a Maven project as a dependency to another Maven project? I'm new to Maven, therefore, sorry in advance if my question is too general. I have a Maven project, call it projectA, which resides in my company's Mercurial repository (let's call it https://hg.mycompany.com/niceprojects/). Recently, I built a separate Maven project, call it projectB in the same repository. I now want to use in projectB some classes that I have in projectA. The directory structure in the repository is currently:
-----niceprojects
       |
       |__projectA
       |     |__pom.xml
       |
       |__projectB
             |__pom.xml

What is a neat way of doing this? I would like to avoid manually building projectA, then adding its jars in projectB. I would also like to keep the same directory structure. Step-by-step instructions would be greatly appreciated. Many thanks!

A: A general advice when using Maven is to use a Maven Repository Manager such as Nexus.
In this case Nexus has the addtional benefit that it can host your jars.
So I advice to do the following:

*

*Configure a CI (e.g. Jenkins) job to build projectA and deploy the JAR to your Nexus instance

*Declare projectA as a dependency in projectB

When building projectB, it can download the projectA JAR from your Nexus instance without you having to build projectA yourself.


text:
Q: Delay document closing I have a document based application and when the application is closed, I need to load a url in a web browser. It's working fine, except that the NSDocument closes before this page can be loaded.
I would need it to wait 200 ms and then close the document.
I have found the NSTerminateLater but that is referred to the application, not the document. How can i do this?
this is what i have for now:
- (id)init
{
self = [super init];
if (self) {
    _statssent = NO;

    // Observe NSApplication close notification
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(_sendstats)
                                                 name:NSApplicationWillTerminateNotification
                                               object:nil];
}
return self;
}

- (void)_sendstats
{
if (!_statssent)
{
    _statssent = YES;

    if (hasuploaded == 1)
    {
            [self updatestatsUploads:0 progloads:1];
    }

 }
}

 - (void)close
{
[self _sendstats];

[super close];
}

A: Just before closing your document, you could issue a notification for which your application delegate could register as an observer.
When your application delegate receives the notification (which could convey the URL you need to open), a method on your application delegate could be called to open the URL for you.
You do this through the use of the instance of NSNotificationCenter that comes with every Cocoa application (more accurately, it's a singleton). Your document would issue the notification something like this:
NSDictionary *myUserInfo = [NSDictionary dictionaryWithObjectsAndKeys:@"http://www.apple.com", @"MyURL", nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@"MyNotificationName" object:self userInfo:myUserInfo];

In your application delegate, probably in your -awakeFromNib method, you'd use something like this:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myURLOpenerMethod:) name:@"MyNotificationName" object:nil];

And somewhere in your application delegate, you could define that URL opener like this:
- (void)myURLOpenerMethod:(NSNotification *)notification
{
    NSString *urlString = [[notification userInfo] objectForKey:@"MyURL"];
    // use 'urlString' to open your URL here
}

You do not want to try using delays to get what you want. I promise you: That way madness lies.


text:
Q: how to send this data from local storage to php online using jquery This is my php codes to received and insert the data into the online database. I am very sure i these fabricated codes will not work but with you education and help i will get. thank you. insertdata.php

<?php
include 'connect.php';
include 'function.php';
//Create Object for DB_Functions clas
$db = new DB_Functions();
//Get JSON posted by Android Application
$json = $_POST["usersJSON"];
//Remove Slashes
if (get_magic_quotes_gpc()){
$json = stripslashes($json);
}
//Decode JSON into an Array
$data = json_decode($json);
//Util arrays to create response JSON
$a=array();
$b=array();
//Loop through an Array and insert data read from JSON into MySQL DB
for($i=0; $i<count($data) ; $i++)
{
//Store User into MySQL DB
$res = $db->storedata($data[$i]->callid,$data[$i]->pid,$data[$i]->pname,$data[$i]->medstay_amt,$data[$i]->med_amt,$data[$i]->imv_amt,$data[$i]->othermc_amt,$data[$i]->emtrans_amt,$data[$i]->outpden_am,$data[$i]->otherps_amt,$data[$i]->herb_amt,$data[$i]->medban_amt,$data[$i]->othermp_amt,$data[$i]->assist_amt,$data[$i]->code,$data[$i]->date);
    //Based on inserttion, create JSON response
    if($res){
        $b["id"] = $data[$i]->pid;
        $b["status"] = 'yes';
        array_push($a,$b);
    }else{
        $b["id"] = $data[$i]->pid;
        $b["status"] = 'no';
        array_push($a,$b);
    }
}
//Post JSON response back to Android Application
echo json_encode($a);
?>

A: You can do something like this:
$(document).on("click", ".BTN_Submit_Task", function () {
    var AllTasks = ls.GetAllArr(LocalstorageName);
    var id = $(this).attr("rec_id");
    var result = $.grep(AllTasks, function(e){ return e.rec_id === id; });

    $.ajax({
        url: "url/of/php/file.php",
        type: 'post',
        dataType: 'json',
        data: {usersJSON: [result]},
        done: function(response) {
            console.log(response);
        }
    });
});

And BTW you probably want to make AllTasks variable global and assign it once, then you can call it from both functions.


text:
Q: TabBarController with NavigationBar I am writing an app that uses the UITabBarController at the bottom.
Hierarchy
- Page 1
- - SubPage 1
- - SubPage 2
- - SubPage 3
- Page 2
- Page 3
Page 1 contains a grid with multiple items, when selected the choosen subpage will be displayed.
On the sub pages I replace the Tabs of the TabBarController with all the subpages and want display a back link in the Navigation Bar.
I create the tabBar programmatically.
At the moment I init the navigationController with the tabBarController as rootViewController.
That seems to work, but I cant change anything on the NavigationBar, setting the title has no effect, buttons dont appear.
What I'm doing wrong?
Or is there a better way achieving what I want?
I target iOS5 with ARC (iPad only)

A: You set the title of the parent navigation controller by setting the title of the child. You'd need to set the title of the tabbar-controller:
myTabBarController.title = @"Page 1";

You also set the buttons of the navigationbar inside the child-view, as the contents of the bar depend on the current visible view:
UIBarButtonItem *myItem = [[UIBarButtonItem alloc] initWithTitle:@"back" style:UIBarButtonItemStylePlain target:self action:@selector(myBackAction:)];
myTabBarController.navigationItem.leftBarButtonItem = myItem;

Remember that changing the contents of the tabbar after tapping an item on it is considered bad user experience. There are probably other, better ways to achieve the same effect.


text:
Q: tGiven a propulsion system with constant power, how long does it take to travel a given distance in space? (non-rel. and relativistic) Suppose a space ship of mass $m$ is travelling away from our solar system, starting with "starting speed" $v_{start} > v_{escape\ \odot}$, meaning it will escape sun and have some velocity left over, $v_0$.
On board of the ship, there is a power source from which a constant power $P$ is drawn for propulsion.
The propulsion system works by exhausting relativistic particles at such high speeds (and thus gamma factory) that the kinetic energy drawn from the power source dominates and we do not loose significant rest mass. (the power source itself works by converting the rest mass of little parts of the ship into energy though).
Given a target, i.e. knowing the distance $s$ we have to travel, we want to know the time $t_s$ it takes to get there as well as the speed $v(t)$ and acceleration $a(t)$ over time.
Non-relativistic
First the simplified task: $m$ is considered constant and we assume a start in empty space, ignoring sun.
so to summarize, we have

*

*mass $m$

*starting time $t_0 = 0$

*initial speed $v_0$

*distance $s$

*power $P=const.$ of the propulsion system

and we are looking for

*

*travel time $t_s$

*velocity $v(t)$

*acceleration $a(t)$
In the non-relativistic case for $v_0 = 0$, I think I've got the solution, but not 100% sure it is correct: we start with
$$P=F\cdot v = m\dot vv$$
$$\Rightarrow v(t)\dot v(t)=\frac{P}{m}$$
Integration:
$$\int_0^t{v(t')\dot v(t') dt'}=\frac{v^2(t)}{2}=\frac{P}{m}t$$
which gives us
$$v(t)=\sqrt{2\frac{P}{m}t}$$
and
$$a(t)=\dot v(t)=\sqrt{\frac{P}{2mt}}$$
another integration gives
$$s(t)=\int_0^t{\sqrt{2\frac{P}{m}t'} dt'} = \sqrt{\frac{8}{9}\frac{P}{m}t^3}$$
$$\Rightarrow t_s=\left(\frac{9s^2m}{8P}\right)^{\frac{1}{3}}$$
In all three results the units are correct, which gives me some confidence in the solutions.
Intuitively, I can't grasp this though, as it leads to different changes in speed at different velocities relative to earth although we are in empty space, thrusting forward with constant power. But constant power does not lead to constant force, guess I'll just have to live with that xD
But that's the reason I'm missing $v_0$ here:
Since with constant power, the change in velocity is apparently dependent on the velocity we already have, I don't know hot correctly to integrate a non-zero $v_0$.
Can you help me with that?
Relativistic
Trying the same approach here leads me to some overwhelming equation I can't solve. Starting with the relativstic force
$$F=\gamma^3(v(t))m_0\dot v(t) $$
with rest mass $m_0$ of the ship; I will not write indexes in the following formulas. using the same approach as above, we have
$$P=F\cdot v = m_0\left(1-\frac{v^2}{c^2} \right)^{-\frac{3}{2}} v\dot v$$
$$\Rightarrow\left(\frac{P}{m_0}\right)^2=\frac{v^2\dot v^2}{\left(1-\frac{v^2}{c^2}\right)^3}$$
expanding the binomial
$$\left(\frac{P}{m_0}\right)^2\left(1-3\frac{v^2}{c^2}+3\frac{v^4}{c^4}+\frac{v^6}{c^6}\right)=v^2\dot v^2$$
now I don't know how to solve this for $v$, $\dot v$, or $t$.
One idea was that maybe a substitution $z:=v^2 \rightarrow \dot z = 2v\dot v$ would make things easier. Also, to save some space, let's use $k:=\left(\frac{P}{m_0}\right)^2$
$$\frac{\dot z^2}{2} = \frac{k}{c^4}Z^3 + \frac{3k}{c^2}z^2-\frac{3k}{c^2}z+k$$
but neither am I able to solve this for $z(t)$ to then re-substitute it to get v,
nor do I know if I'm moving in the right direction at all. Or if the results are in the earth or the ship system, for that matter. And of course here, too, $v_0$ is missing.
Happy to hear your solutions. If needed, I can provide more intermediate steps in the calculation.
Bonus
Given $s$ as a single-digit number of light years and the ship has a quite modest propulsion, so that $t_s$ is around $1 000$ years , do the following considerations / changes alter the result significantly?

*

*$v_0$ is not actually the start velocity, but the excess speed above the escape velocity from the sun; we actually start with $v_{start} = v_{escape\ \odot} + v_0$ at $1$ AU from sol (but largely outside of Earth's gravity well).

*the mass is not actually constant. Our power source slowly "eats" the ship by converting is's rest mass into the energy for propulsion. Will it become significant if we don't have 100% efficiency and can only use around $\frac{1}{10}th$ of the power for propulsion? (i.e. "eating" 10 times more rest mass of our ship than we get out in kinetic energy)

Generally, there is a lot of material to be found dealing with constant acceleration or constant force, but not for constant power, oddly enough.

A:
The propulsion system works by exhausting relativistic particles at such high speeds ... that the kinetic energy drawn from the power source dominates and we do not loose significant rest mass.

I don't know what you mean by "the kinetic energy drawn dominates".  The best you can do for limiting mass loss is to make the exhaust as low-mass as possible is for the exhaust to be photons.
The problem is that the lighter the exhaust and the more mass efficient your drive, the less energy efficient it becomes.  Your engine might generate a constant power, but most of that energy goes into the exhaust, not into the ship (at least in a frame where the ship is not moving at high speed).
A constant power draw engine means constant thrust.  Regular rocket engines are this way, just they have run times in the minutes, not years.  And for even very short burns, the mass of the craft is not constant.  For a photon drive, you could consider the mass to be constant for quite some time.
The P in the $P = Fv$ equation you have is the power delivered to the spacecraft.  It is not equal to the power consumed by the engine (since some of the power has to go into accelerating the exhaust).  In your constant-consumption engine, you do not have constant power delivery.  Since you have constant force, you can use those other sources you have found.


text:
Q: Unable to append RDD to a list in scala Hi following i am unable to append values to my List in Scala following is my code:
var cumFrequency =List[Any]
updatedRdd.foreachRDD( rdd => {
  for( item <- rdd.collect()) {
   val newRDD = (item._1,item._2.toString.toDouble/newc)
    cumFrequency +: newRDD
  }

})

I am getting error at cumFrequency +: newRDD of can not resolve symbol. i am not sure why its giving that error when i want to append newRDD to list cumFrequency . am i writing in wrong syntax?

A: Use :+ not +:
Below is the corrected line
cumFrequency :+ newRDD

Initialise you cumFrequency using List.empty[Any] or List[Any]()
var cumFrequency = List[Any]()

or
var cumFrequency =List.empty[Any]

In order to append to list use ::: or ++ or :+
In case of List try this
cumFrequency ::: List(newRDD)

or
cumFrequency ++ List(newRDD)
or if you do not care about order then
newRDD :: cumFrequency

A: To make this work in the context of your program, where the values are added to the list in an imperative style, you need:
cumFrequency = cumFrequency ++ List(newRDD)

or
cumFrequency = newRDD :: cumFrequency

And you should also add brackets after the declaration:
var cumFrequency =List[Any]()

This style is not recommended by most Scala programmers. A better way would be something like:
val cumFrequency = updatedRdd.flatMap( rdd => {
  for( item <- rdd) yield (item._1,item._2.toString.toDouble/2)
})

But that would depend on the RDD data type, which I'm not familiar with.


text:
Q: Checking an IP Address against an CIDR range in redshift I've got a problem i have been trying to work out I have googled a few things that are similar to what i want to do but can't work out exactly how to do it,
I have around 250M ip address's and i want to look that up against the maxmind geolite2 data so that i can tell what country each IP-address originates from,
I have imported all the data into my Redshift cluster with talend,
table a has ID and 'ipaddress' ie 10.0.0.5
table b (maxmind) has country name and IP range as expressed as 10.0.0.0/24

how could i use Redshift SQL to match these two considering the size of my source data source?
edit: heres the link to the geolite2 data https://dev.maxmind.com/geoip/geoip2/geolite2/

A: You could try using Amazon Redshift's ability to Import Custom Python Library Modules to load the netaddr library. Then, you could use the library within a User Defined Function written in Python.
See also: IP Range to CIDR conversion in Python?


text:
Q: Automatically sort Google Sheet by most recently updated row I want to have a sheet which automatically sorts the most recently edited row to the top, in order to surface freshly edited results and not let them be buried by outdated entries.

A: Here's the solution I came up with for a Google Apps Script:

  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();

  var dateColumn = 2; // What column should date be written to
  var headerRows = 2;
  var tableRange = "A3:M101"; // What data to sort.
  var sheetName = 'Sheet name' // Name of the sheet to sort

  if( sheet.getName() == sheetName ) { // Checks that we're on the correct sheet
    var editedCell = sheet.getActiveCell();
    var offset = dateColumn - editedCell.getColumn() // Finds the offset needed to move from edited cell to date column
    if( editedCell.getColumn() != dateColumn && editedCell.getRow() > headerRows) { // Don't overwrite manually set dates or the header row(s)
      var dateCell = editedCell.offset(0, offset); // Go to relevant date cell
      var now = new Date();
      now = Utilities.formatDate(now, "GMT", "yyyy/MM/dd HH:mm:ss"); // Format datetime
      dateCell.setValue(now);
    }

    var range = sheet.getRange(tableRange);

    range.sort( { column : dateColumn, ascending: false } ); // Sort range by date column, newest on top
    // range.setWrapStrategy(SpreadsheetApp.WrapStrategy.WRAP); // Sets text wrapping to wrap if uncommented
  }
}

Plus adding an event trigger on form submission.

A: This could work with an on form submit but not like you think
function onFormSubmit(e) {
  const sh = e.range.getSheet();
  if (sh.getName() == 'Sheet name' && e.range.columnStart != 2 && e.range.rowStart > 3) {
    e.range.offset(0, 2 - e.range.columnStart).setValue(Utilities.formatDate(new Date(), "GMT", "yyyy/MM/dd HH:mm:ss"));
    sh.getRange(3, 1, sh.getLastRow() - 2, 13).sort({ column: 2, ascending: false });
  }
}

columStart will always be one so that will work
row start will work after you get past row 3
and the sheet will always have to be the linked sheet name and resorting the linked sheet seems kind of weird to me it's already sorted by time stamp


text:
Q: How do I prevent a jQuery handler on a button element inside a form from executing when the user presses enter? I have a button element inside a form like this:
<form>
    <input type="text">
    <button>Test</button>
    <input type="submit" value="Submit"/>
</form>

With the following JS:
$('form').submit(function() {
    alert('Form submitted.');
    return false;
});

$('button').click(function() {
    alert('Button clicked.');
});

And the jsFiddle: http://jsfiddle.net/JnnRX/
When the user focuses the text field, types in some text, and presses enter, the button handler will execute first, followed by the form handler. However, I'd like it to just
execute the form handler and ignore the button. Is there any way to get this behavior, or is it best to change my button element to something else?

A: Make the button of type button
<button type="button">Test</button>

If it is that type, the browser won't recognize "enter" submits, unless that button has focus. Typically the first submit button in a form's flow will be the one to get submitted on enter.

A: Here you go: http://jsfiddle.net/JnnRX/17/
Basically you just use e.preventDefault() on keyup() for the form. e represents the keyup event, and e.keyCode represents the key that was pressed. 13 is the enter key's keycode.
EDIT:
Woops, I didn't understand your original request. I've updated the jsfiddle with what you wanted.


text:
Q: OnChange event not firing, function is not out of scope function language(value)
{
    window.alert(value);
}

<select onchange="language(this.val())">
    <option value="Português">Português</option>
    <option value="Inglês">Inglês</option>
</select>

Why is this not working?
The problem is not the function out of scope, I have used this code to test that it's not:
$(document).ready(function(){
   language("testing");
});

A: Why don't you just stick to just jQuery and do this:
$(document).ready(function () {
    $('select').change(function () {
        alert(this.value);
    });
});

And in case you want to use the javascript only, do this:
<select onchange="language(this.value)">   <!-- Not this.val() -->
    <option value="Português">Português</option>
    <option value="Inglês">Inglês</option>
</select>

For testing, you can change the onchange event to onchange="alert(this.value)"

A: Ok so this.val() is not a valid function .val() is a jQuery element function you need $(this).val() in your onchange attribute.
<select onchange="language($(this).val())">
    <option value="Português">Português</option>
    <option value="Inglês">Inglês</option>
</select>

or use this.value like so,
<select onchange="language(this.value)">
    <option value="Português">Português</option>
    <option value="Inglês">Inglês</option>
</select>

If that does not fix the issue, you should use something like the Chrome developer tools or FireBug to catch the exception that is thrown when you change the select. That will give you a very good idea of where to look for the issue.


text:
Q: how to show 500 internal Server error page in laravel 5.2? I want to show the page 500 internal server error Page. when user had syntax error mistake in project can anyone help me? if i do some mistake in syntax i want to show that particular blade.

A: In your resources/views/errors  folder create a file named 500.blade.php.

Laravel makes it easy to display custom error pages for various HTTP
  status codes. For example, if you wish to customize the error page for
  500 HTTP status codes, create a  resources/views/errors/500.blade.php. This file will be served on all 500 errors generated by your application.

The problem is that Laravel will only do this automatic rendering of error pages for exceptions that are instances of HttpException. Unfortunately when your server throws an error (method does not exist, variable undefined, etc) it actually throws a FatalErrorException. As such, it is uncaught, and trickles down to the SymfonyDisplayer() which either gives you the trace (debug true) or ugly one-liner 'Whoops, looks like something went wrong' (debug false).
To solve this you have add this to your render method to app/Exceptions/Handler
# /app/Exceptions/Handler.php

# use Symfony\Component\Debug\Exception\FlattenException;

# public function render($request, Exception $e)

$exception = FlattenException::create($e);
$statusCode = $exception->getStatusCode($exception);

if ($statusCode === 404 or $statusCode === 500) {
    return response()->view('errors.' . $statusCode, [], $statusCode);
}

Docs

A: You need to create handler to catching FatalErrorExceptions in your handler like below code:
Handler
In app/Exceptions/Handler.php
public function render($request, Exception $e)
{

    // 404 page when a model is not found
    if ($e instanceof ModelNotFoundException) {
        return response()->view('errors.404', [], 404);
    }

    // custom error message
    if ($e instanceof \ErrorException) {
        return response()->view('errors.500', [], 500);
    } else {
        return parent::render($request, $e);
    }

    return parent::render($request, $e);
}

View
See resources/views/errors/500.blade.php. If not exist then create it.
You can get more detailed OR other ways from Laravel 5 custom error view for 500

A: My solution is simple, just replace your render() method in Exceptions\Handler.php file with:
/**
 * Render an exception into an HTTP response.
 *
 * @param \Illuminate\Http\Request $request
 * @param \Exception               $exception
 *
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $exception)
{
    if ($request->expectsJson()) {
        return $this->renderJson($request, $exception);
    }

    if ($this->shouldReport($exception) && app()->environment('production')) {
        $exception = new HttpException(500, $exception->getMessage(), $exception);
    }

    return parent::render($request, $exception);
}

It will show 500 page if app in production environment. You will need to have 500.blade.php view in your resources/views/errors folder.

A:     // app/Exceptions/Handler.php

    protected function prepareResponse($request, Exception $e)
    {
        if($this->isHttpException($e) === false && config('app.debug') === false)     {
            $e = new HttpException(500);
        }

        return parent::prepareResponse($request, $e);
    }

Like @Amit said

The problem is that Laravel will only do this automatic rendering of
  error pages for exceptions that are instances of HttpException.

So my solution is to replace whatever exception that is not HttpException by a HttpException.

A: in app\Exceptions\Handler create the following method:
protected function convertExceptionToResponse(Exception $e)
{
        $e = FlattenException::create($e);
        return response()->view('errors.500', ['exception' => $e], $e->getStatusCode(), $e->getHeaders());
}

it will override the one in the parent class (Illuminate\Foundation\Exceptions\Handler) that displays the whoops page.

A: In Laravel 5.4, you could override prepareException function in your app\Exception\Handler.php:
/**
 * @inheridoc
 */
protected function prepareException(Exception $e)
{
    $exception = parent::prepareException($e);

    if(!config('app.debug')) {
        if(!$exception instanceof HttpException && $this->shouldReport($exception)) {
            $exception = new HttpException(500);
        }
    }

    return $exception;
}


text:
Q: Dimension of solutions of EDP I heard that the manifold consisting of solutions of a given PDEs is of infinite dimension.
Is this statement true for all PDEs ?
Could we write a PDE as infinite ODEs and in that case, the statement makes sense ?

Here is a precise context.
We define an optimal control problem as
$$
\underset{u(.)}{ \min } \; C(u),\quad
\dot q = f(q,u), \quad q(t) \in M
$$
in that case $M$ is of finite dimension because we have an ODE but if we replace this ODE to a PDE, $M$ is of infinite dimension.


text:
Q: Get Network Manager name for devices from command line Network Manager has long names for ethernet devices in parentheses: eth0 might be shown as Ethernet Networks (Intel Ethernet Connection I217-LM) in the dropdown menu.
Is there a way to list these names from the command line (using nmcli?)- or even better also show the ifconfig name for them in the same output?
This is using 16.04 with nmcli 1.2.6.

A: The comments above got me far enough to be able to figure out the answer:
$ nmcli -t -f GENERAL.PRODUCT,GENERAL.DEVICE device show
GENERAL.PRODUCT:Ethernet Connection I217-LM
GENERAL.DEVICE:eth0


text:
Q: reference request : Numerical techniques for partial differential equations I want to learn how to solve parabolic,hyperbolic, and elliptic PDE's in any dimension numerically. Can anyone recommend a reference?
I recently read "Partial Differential Equations for Scientists and Engineers," by Stanley J Farlow, it was a good introduction for analytical methods such as Fourier transforming initial conditions in 1d heat flow, but I think it was not good for numerical and multi dimensional problems.


text:
Q: Vagrant unable to connect to docker through ssh I'm trying to connect to docker instance through vagrant.
Here is my Dockerfile:
FROM centos:7
#RUN yum -y update
RUN yum -y install openssh-server wget sudo
EXPOSE 22
RUN mkdir -p /home/vagrant/.ssh
RUN chmod 0700 /home/vagrant/.ssh
RUN useradd --create-home -s /bin/bash vagrant
WORKDIR /home/vagrant
RUN mkdir -p /home/vagrant/.ssh
RUN echo "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6NF8iallvQVp22WDkTkyrtvp9eWW6A8YVr+kz4TjGYe7gHzIw+niNltGEFHzD8+v1I2YJ6oXevct1YeS0o9HZyN1Q9qgCgzUFtdOKLv6IedplqoPkcmF0aYet2PkEDo3MlTBckFXPITAMzF8dJSIFo9D8HfdOV0IAdx4O7PtixWKn5y2hMNG0zQPyUecp4pzC6kivAIhyfHilFR61RGL+GPXQ2MWZWFYbAGjyiYJnAmCP3NOTd0jMZEnDkbUvxhMmBYSdETk1rRgm+R4LOzFUGaHqHDLKLX+FIPKcF96hrucXzcWyLbIbEgE98OHlnVYCzRdK8jlqm8tehUc9c9WhQ== vagrant insecure public key" > /home/vagrant/.ssh/authorized_keys
RUN chmod 0600 /home/vagrant/.ssh/authorized_keys
RUN chown -R vagrant: /home/vagrant/.ssh
RUN mkdir -p /etc/sudoers.d
RUN install -b -m 0440 /dev/null /etc/sudoers.d/vagrant
RUN echo 'vagrant ALL=NOPASSWD: ALL' >> /etc/sudoers.d/vagrant
RUN sed -i 's|#AuthorizedKeysFile|AuthorizedKeysFile|g' /etc/ssh/sshd_config
CMD ["/usr/sbin/sshd", "-D"]

And here is my Vagrantfile:
# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure(2) do |config|
 config.vm.provider "docker" do |d|
    d.build_dir = "."
    d.name = "test"
    d.has_ssh = true
  end
  config.ssh.port = 22
end

And after vagrant up I get this:
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 172.17.0.2:22
    default: SSH username: vagrant
    default: SSH auth method: private key
    default: Warning: Connection refused. Retrying...
    default: Warning: Connection refused. Retrying...
    default: Warning: Connection refused. Retrying...

And it's printing last row many times, unlit I stop it with Ctrl-C.
If I just run docker build -t stacko . && docker run stacko process will stuck here:
Could not load host key: /etc/ssh/ssh_host_rsa_key
Could not load host key: /etc/ssh/ssh_host_ecdsa_key
Could not load host key: /etc/ssh/ssh_host_ed25519_key

What could be wrong?
My Solution
It seems to be that problem was with docker host keys. So I regenerated them
FROM centos:7

ENV container docker

# Stuck at "loaded plugins: fastestmirror" fix
RUN rm -f /var/lib/rpm/__*
RUN rpm --rebuilddb -v -v

RUN yum -y update
RUN yum -y install openssh-server openssh-clients sudo
RUN yum clean all

RUN rm -f /etc/ssh/ssh_host_rsa_key
RUN rm -f /etc/ssh/ssh_host_dsa_key
RUN rm -f /etc/ssh/ssh_host_ecdsa_key
RUN ssh-keygen -q -N "" -t rsa -f /etc/ssh/ssh_host_rsa_key
RUN ssh-keygen -q -N "" -t dsa -f /etc/ssh/ssh_host_dsa_key
RUN ssh-keygen -q -N "" -t ecdsa -f /etc/ssh/ssh_host_ecdsa_key

RUN useradd -s /bin/bash vagrant
RUN echo -n 'vagrant:vagrant' | chpasswd
RUN mkdir -p /home/vagrant/.ssh
RUN chmod 0700 /home/vagrant/.ssh
RUN echo "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6NF8iallvQVp22WDkTkyrtvp9eWW6A8YVr+kz4TjGYe7gHzIw+niNltGEFHzD8+v1I2YJ6oXevct1YeS0o9HZyN1Q9qgCgzUFtdOKLv6IedplqoPkcmF0aYet2PkEDo3MlTBckFXPITAMzF8dJSIFo9D8HfdOV0IAdx4O7PtixWKn5y2hMNG0zQPyUecp4pzC6kivAIhyfHilFR61RGL+GPXQ2MWZWFYbAGjyiYJnAmCP3NOTd0jMZEnDkbUvxhMmBYSdETk1rRgm+R4LOzFUGaHqHDLKLX+FIPKcF96hrucXzcWyLbIbEgE98OHlnVYCzRdK8jlqm8tehUc9c9WhQ== vagrant insecure public key" > /home/vagrant/.ssh/authorized_keys
RUN chmod 0600 /home/vagrant/.ssh/authorized_keys
RUN chown -R vagrant: /home/vagrant/.ssh
RUN mkdir -p /etc/sudoers.d
RUN install -b -m 0440 /dev/null /etc/sudoers.d/vagrant
RUN echo 'vagrant ALL=NOPASSWD: ALL' >> /etc/sudoers.d/vagrant
RUN sed -i 's/Defaults    requiretty/#Defaults    requiretty/g' /etc/sudoers

EXPOSE 22

CMD ["/usr/sbin/sshd", "-D"]

It would be cool, if solmeone could explain me why is this working (what's wrong was with ssh keys)


text:
Q: Capture a frame of video file (.Net core) I spent some time to find a library for .Net Core and use it to capture a frame of video file at some certain point. I know there are some out there, for example i used Mediatoolkit but it is not compatible with .net core.
All of them are compatible for .net framework. Any Help?

A: You can use ffmpeg to extract frames:
https://trac.ffmpeg.org/wiki/Create%20a%20thumbnail%20image%20every%20X%20seconds%20of%20the%20video
You have to know what operating system you are on (Linux or Windows) to provide compatible ffmpeg binaries.
With this API you can invoke ffmpeg from C# with parameters (applies to .NET Core):
https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.start?view=netframework-4.7.2
var process = new Process
{
    StartInfo = new ProcessStartInfo()
    {
        CreateNoWindow = true,
        FileName = "ffmpeg", // or path to the ffmpeg
        WindowStyle = ProcessWindowStyle.Hidden,
        Arguments = "your arguments here"
    }
};

process.Start();
process.WaitForExit(10000); // wait for exit 10000 miliseconds

Now you just need to read the output (image file) from the file system.

A: I used Xabe.FFmpeg.
https://ffmpeg.xabe.net/docs.html
// sudo apt install ffmpeg
FFmpeg.SetExecutablesPath("/usr/bin/");

var conversion = await FFmpeg.Conversions.FromSnippet.Snapshot(newPath1, newPath2, TimeSpan.FromSeconds(0));
var result = await conversion.Start();


text:
Q: How to Click/ Press Bar Button on Navigation Item programmatically I have iPhone as below.

What I want is click Refresh button on clicking the Delete button ** programmatically**.
Note: I have provided tag also to Refresh button.

A: I assume u have delete and refresh actions say
 -(IBAction)deleteAction:(id)sender
 -(IBAction)refreshAction:(id)sender:

Now on delete action call refresh action simply like this:
-(IBAction)deleteAction:(id)sender
{
    [self refreshAction:btnRefresh]; //provide refresh action along with refersh button
    //I mean here act according to refresh method.
}


text:
Q: best practice for communicating between two beans that back the same page We are making the transition to bootstrap pages. As part of this, we are making most of our dialogs into simple include files that get rendered on demand. The include files have their own backing bean to minimize code duplication.
The typical use case is when a user enters a page a datatable shows a list of things. The user selects one or more rows in the table and then clicks a button to perform an action. The page is re-rendered using ajax. The datatable is not displayed but the former dialog is. The user then does whatever bulk operation the former dialog does and clicks execute (or cancel). The page is then re-rendered with the datatable showing and the former dialog box not.
The problem here is simple; how do you set the render flags on the datatable and former dialog box? Each of the beans needs to set the render flag of the other bean. I blithely tried injecting each bean into the other and promptly got a circular injection error at runtime. I've gone to having a callback interface that the datatable beans implement. When the former dialog bean gets injected, the datatable bean sets itself up to be called back. This works but I am not sure it's the best way to do it. Being an old swing programmer, I considered using property change listeners, which are much more robust than the simple interface, but I'm not sure what the implications of using them in a managed bean environment are. I did check out the messaging API but it clearly doesn't apply to this case.
So, what's the best way for two view beans that are backing the same page to talk to each other?


text:
Q: How to calculate the range from mean and SD? Is is possible to calculate or estimate the range of a population if I know the mean, population size and standard deviation?
I am doing a research and the mean age of the population is 29.9 +/- 5.3 SD, the population size is 21. What will be range of the population age?

A: When writing the lower part, I missed that the population size is 21. I somehow thought the question was for general population size. For known population size 21 there should be a mathematical maximum range, not only a minimum one. First now considerations regarding the maximum possible range:
Note that it is possible to have a very small observation if all observations larger than the mean 29.9 are not much larger. Here is how to find the smallest possible observation. Let's say 20 observations have size $29.9+\epsilon$ with $\epsilon>0$ and one observation has size $\delta<29.9$. Then for the mean:
$$ 29.9=\frac{20*(29.9+\epsilon)+\delta}{21}\Rightarrow \delta=29.9-20\epsilon.$$
The variance is $5.3^2=28.9$, so
$$ \frac{20\epsilon^2+(\delta-29.9)^2}{21}=\frac{20\epsilon^2+(20\epsilon)^2}{21}=28.9, $$
thus
$$\frac{420\epsilon^2}{21}=20\epsilon^2=28.9\Rightarrow \epsilon=\sqrt{28.9/20}=1.202$$
and $\delta=29.9-20\epsilon=5.86$, so that's the smallest observation you can have, but only if it is the only observation smaller than the mean and all other observations are larger.
On the other hand, the same argument but assuming $\epsilon<0$ shows what can happen if 20 observations are smaller than the mean and only one is larger. Then we get $\epsilon=-1.202$, and $\delta=29.9-20\epsilon=53.94$, which is the biggest observation you can have, again only if all other observations are smaller than the mean.
Now for unknown population size, this was the original answer:
No, it's not. Technically any mean and SD are compatible with any range larger than a minimum possible range, which I haven't checked or computed, but for a given population size there is a minimum possible range.
But the range can be arbitrarily bigger than that. Note that a Gaussian distribution, which is normally taken as the basis for using mean and sd for estimation, is theoretically unlimited, i.e., it ranges (if infinitely many observations were available) from minus to plus infinity, which already shows that you can have an arbitrarily large range with any given mean and sd.
Obviously there are physical bounds in your real example, however in a general situation nothing can be said apart from that the range is larger or equal to the minimum possible one.

A: Chebyshev's inequality gives bounds for how much probability mass can be more than a certain number of standard deviations from the mean: no more than $\frac 1 {k^2}$ of a distribution's values can be more than $k$ standard deviations away from the mean. So, for instance, there are no distributions with more than 1% of their probability mass more than 10 standard deviations from the mean.  This is an upper bound, and it's possible for there to be less. We cannot, however, say that there is some point at which there is no further probability mass; the normal distribution, for instance, has probability mass arbitrarily far from the mean.


text:
Q: Can i ask what is the difference between Jframe and JPanel and which is primary in coding I wanna know what is the difference between JFrame and Jpanel in simpler way I used to work with Application Form in VS and it's not the same for what I see
I have hard time to figure if I should use Jframe or jpanel and which has the priority in codes
I'm trying my best with java

A: JFrame is the actual frame, the window that pops up.
JPanel is the layout inside the frame, so you can add multiple JComponents to a JPanel and organize them instead of only one component in JFrame.
You can add multiple JPanels in a JFrame.


text:
Q: Disable paste and select all function button from textformfield in flutter I want to disable all the functionality related to copy, paste and select all on the press of textformfield in the flutter. I have a password field which can take keyboard hint and able to paste data by default but when I perform the operation like calling login service then password field gone wrong.
 TextFormField(
      obscureText: true,
      style: styleText,
      textInputAction: TextInputAction.done,
      controller: _passwordController,
      focusNode: _passwordFocus,
      onFieldSubmitted: (term){
        _passwordFocus.unfocus();
      },
      keyboardType: TextInputType.text,
      validator: validatePassword,
      decoration: InputDecoration(
          focusedBorder: border,
          border: border,
          enabledBorder: border,
          hintStyle: styleText,
          hintText: 'Password'),
      onSaved: (String val) {
        _password = val;
      },
    ),

A: You can use the enableinteractiveSelection : false to Disable the copy/paste.
TextFormField(
          enableInteractiveSelection: false,
          obscureText: true,
          style: styleText,
          textInputAction: TextInputAction.done,
          controller: _passwordController,
          focusNode: _passwordFocus,
          onFieldSubmitted: (term){
            _passwordFocus.unfocus();
          },
          keyboardType: TextInputType.text,
          validator: validatePassword,
          decoration: InputDecoration(
              focusedBorder: border,
              border: border,
              enabledBorder: border,
              hintStyle: styleText,
              hintText: 'Password'),
          onSaved: (String val) {
            _password = val;
          },
        ),

A: You can try this to disable any particular option not all the option.
 TextFormField(
      toolbarOptions: ToolbarOptions(
        copy: true,
        cut: true,
        paste: false,
        selectAll: false,
      ),
    ...
    ..
    .


text:
Q: How to find the most recent file containing a particular text in Unix? I've a directory with thousands of files, many of them containing the text I'm looking for. I've to search only in a single directory. I need to find the most recently created file in the directory that contains a particular text, say "check".
I've tried grep, find and ls, but I can either find a list of files containing the text e.g.
 find . -type f -exec grep -l check {} +

or, the latest file in a directory using:
ls -t1 |  head -n 1

How can I combine both to get the latest file containing a particular text?

A: I tweeked my initial command to get the desired results. I'm posting here for future searches:
find . -type f | xargs grep -l "text to find" | xargs ls -rt | tail -1

A: This is a simple way to do this:
find . -type f -exec grep -l check {} + | xargs ls -latr

A: Here's a decent way to do it:
grep -Pl '<PATTERN>' <DIR> -R \
  | xargs stat \
  | grep '(Change:|File:)' -P \
  | sed -r 's/^\s*//; s/File:.*\s(.*)`/\1/; '"s/'$//;"'s/Change:(.*)$/\1*/' \
  | tr -d '\n' \
  | tr '*' '\n' \
  | awk '{printf "%s %s %s\n", $3, $2, $1; }' \
  | sort -unr

Where <PATTERN> is the text you want to find and <DIR> is the path you want to look in.
Step-by-Step

*

*Grep

*

*-R search recursively and follow symlinks.

*-P PATTERN can be a perl regexp.

*-l only print the names of files containing a match

*Xargs

*

*xargs will run stat against each line of input coming from STDIN, which is the output from grep.

*Grep

*

*-P allow perl regexp in PATTERN.

*

*'(Change:|File:)'
We only want the filename and modification time from stat.

*Sed

*

*-r enables support for extended regular expressions

*

*s/^\s*//
Deletes all whitespace from the start of each line.

*s/File:.*\s(.*)/\1/
Replace File:, any immediate whitespace, and ` with the contents of group 1 (.*)

*s/'$//
Delete the single-quote from lines ending with one.

*s/Change:(.*)$/\1*/

Delete Change: and add a *† at the end of each line.

*Tr

*

*-d delete the character instead of replacing it.

*

*'\n'
Delete newlines

*'*' '\n'
Replace asterisks with newlines.

*Awk

*

*Print output like so HH:MM:SS.MS DATE FILE

*Sort

*

*-u discard duplicate lines
We only want each file to appear once--we don't care how many times the pattern has appeared in the files.

*-n compare according to string numerical value
We're comparing timestamps.

*-r reverse the result of comparisons
So the most recent file is at the top instead.

† I use * here because none of the files in my use-case had an asterisk in their name.  You can use whatever character you like, so long as it doesn't appear in any of the filenames or in the output from stat.

A: May be a late response, hope this helps someone later.
I am not a pro in Shell, but found below one works for me and this is very simple to use and understand.
grep '<Search String>' $(ls -t1 |  head -n 1)


text:
Q: Datetime format in SQL Server query I need to show a datetime column in the following fromat 04/11/2016 01:38:03 PM, but it is showing in the format 4/11/2016 1:38:03 PM.
Is there any specific function or syntax to get that desired format?

A: I suppose function FORMAT should help you:
select
   FORMAT(GETDATE(), 'dd/MM/yyyy hh:mm:ss tt');

More details about format you can found in official documentation:
https://msdn.microsoft.com/en-us/library/ee634398.aspx

A: This query will give you output in exact same format(04/11/2016 01:38:03 PM) :
select FORMAT(GETDATE(), 'MM/dd/yyyy hh:mm:ss tt');

See the output:enter image description here

A: You need to try this..
select FORMAT(GETDATE(), 'mm/dd/yyyy hh:mm:ss tt');


text:
Q: Minimum Page Table Size for Process? I was learning about Page Table and Virtual Memory, My professor showed the following image:

and asked what's the minimum size for the page table where L1=L2=256
I answered it's 256 since L1 is always allocated (A register is pointing to it) and all the pointers inside of it can be NULL.
He said this isn't correct and it should be 512 where L1 is allocated and at least one of the pointers isn't NULL.
I didn't get that, why one of them MUST be pointing to some page table?


text:
Q: MS Access: Action "onchange" event after a delay? Good morning!
I have a "fancy" search function in Microsoft Access where the list of possible options shrinks as you type in the search field. Unfortunately the computer and server can't keep up with these rapid requeries of the data.
Currently the command to requery with the field in the 'onchange' function of the search box. I'd like to add a delay so it only runs the requery when the search box has not changed for a second. Thus if someone types in a 8 letter word, it isn't running 8 requeries.
The current idea I have for it, which I know there must be something better, is..
"On change, set search box value to X and wait 1 second. After 1 second, if X = search box value, run the requery. An issue is that it would be rapidly rewriting the X value and have a 'wait' command floating for each letter.
Hopefully there's a way to write an event trigger of "When field X has changed, but not changed for the past second."
Thank you!
As requested, here is my current code
'Create a string (text) variable
    Dim vSearchString As String
'Populate the string variable with the text entered in the Text Box SearchFor
    vSearchString = SearchFor.Text
'Pass the value contained in the string variable to the hidden text box SrchText,
'that is used as the sear4ch criteria for the Query QRY_SearchAll
    SrchText = vSearchString
'Requery the List Box to show the latest results for the text entered in Text Box SearchFor
    Me.SearchResults.Requery
    Me.SearchResults2.Requery
'Tests for a trailing space and exits the sub routine at this point
'so as to preserve the trailing space, which would be lost if focus was shifted from Text Box SearchFor
    If Len(Me.SrchText) <> 0 And InStr(Len(SrchText), SrchText, " ", vbTextCompare) Then
        'Set the focus on the first item in the list box
            Me.SearchResults = Me.SearchResults.ItemData(1)
            Me.SearchResults.SetFocus
        'Requery the form to refresh the content of any unbound text box that might be feeding off the record source of  the List Box
            DoCmd.Requery
        'Returns the cursor to the the end of the text in Text Box SearchFor,
        'and restores trailing space lost when focus is shifted to the list box
            Me.SearchFor = vSearchString
            Me.SearchFor.SetFocus
            Me.SearchFor.SelStart = Me.SearchFor.SelLength
            Exit Sub
    End If
'Set the focus on the first item in the list box
'    Me.SearchResults = Me.SearchResults.ItemData(1)
    Me.SearchResults.SetFocus
'Requery the form to refresh the content of any unbound text box that might be feeding off the record source of  the List Box
    DoCmd.Requery
'Returns the cursor to the the end of the text in Text Box SearchFor
    Me.SearchFor.SetFocus
    If Not IsNull(Len(Me.SearchFor)) Then
        Me.SearchFor.SelStart = Len(Me.SearchFor)
    End If

Obviously this is not MY code, it's from somewhere on the interweb. It works fantastic for databases stored locally, but everything is moving to our Sharepoint server which is running on a 386 in a moldy basement powered by a narcoleptic gerbil.

A: You can simply use the Timer of the current form. No need for a separate form or anything.
Private Sub DoSearch()

    ' Your current code
    ' but you should look into removing as many "Requery" from there as possible!

End Sub

Private Sub SearchFor_Change()

    ' Wait for x Milliseconds until the search is started.
    ' Each new change restarts the timer interval.
    ' Use 1000 (1 s) for slow typists or a really slow server
    ' 200 ms feels right for a normal typist
    Me.TimerInterval = 200

End Sub

Private Sub Form_Timer()

    ' Disable timer (will be enabled by the next SearchFor_Change)
    Me.TimerInterval = 0
    ' Now run the search
    DoSearch

End Sub

Note: you may need to move some of the cursor-handling code from DoSearch() to SearchFor_Change(), specifically:
Me.SearchFor.SelStart = Len(Me.SearchFor)

A: Assign a shortcut key like (Ctrl+ J) to the logic in on change event and call it on demand once you have finished typing search keyword.

*

*Remove on change event.

*Create other procedure which has the logic of on change event and assign a shortcut key

*Press shortcut to get search suggestion

Other approach
Add below validation to Change event which will check for length of string and will trigger only if length of string is >=8
Private Sub txtSearch_Change()

    If Len(Nz(txtSearch.Text, 0)) >= 8 Then

    End If

End Sub

A: I'm going a little outside my comfort area, since I hardly use MS Access forms, but why are you bothering the Server/Database so much?  In my experience, each query costs the same amount of time, whether it returns 1 record or 100,000 records.
So even before the user types anything, why don't you just do a single query to return a sorted list.  After that, it takes almost no time to use VBA to process the results and find everything in the list that starts with whatever the user types in (it's sorted after all).
Except for the initial load, users who are local to the database or on the other side of the world will experience the same snappy response from your interface.
----------
Like I said, I haven't messed with Access Forms a lot, so this is more of a strict VBA solution.  Maybe there is a better way to do it without going outside the Access Forms box that someone could enlighten us with.
You should basically just call LoadItemList when you load the form, or whenever you need to.
Public dbConn As ADODB.Connection
Private ItemList As Variant
Private RecordCount As Long

Sub LoadItemList()
Dim SQL As String
Dim RS As New ADODB.Recordset

    SQL = "SELECT T.Name FROM Table T"
    Set RS = dbConn.Execute(SQL)
    If Not RS.EOF Then
        ItemList = RS.GetRows
        RecordCount = UBound(ItemList, 2) - LBound(ItemList, 2) + 1
    End If
End Sub

Then replace DoCmd.Requery with AddItemtoCombobox SearchResults, SearchFor.Text
Sub AddItemtoCombobox(Control As ComboBox, Filter As String)
Dim Index As Long
    Control.Clear
    If Not IsEmpty(ItemList) Then
        For Index = 0 To RecordCount - 1
            If ItemList(Index) Like Filter Then Control.AddItem ItemList(Index)
        Next
    End If
End Sub

Again, maybe there is a better way that is built into Access...

A: The technical term that you're looking for is debounce.
What you can do is on your on change event, keep track of the current search string
in terms of pseudocode.
sub onChange()
   Form.timerinterval = 0
   setSearchString
   form.timerinterval = delay

So in terms of the explanation, if your on change is called, disable the timer. Update your search string, then reset the timer to fire after a certain amount of time. The form should be a hidden form that contains the code that you want to execute


text:
Q: Character encoding issue in Oracle PL/SQL I'm facing a character discrepancy issue while extracting data from db tables.
I've written a PL/SQL code to spool some data to .txt file from my db tables and running this sql using unix shell but when I'm getting the spooled file, the result set is a changed one from the one at back end.
For example:
At back end: SADETTÝN

In Spooled txt file :  SADETTŸN

If you look at the Y character, it is a changed one. I want to preserve all the characters the way they are at back end.
My db's character set:
SELECT * FROM v$nls_parameters WHERE parameter LIKE 'NLS%CHARACTERSET'
PARAMETER              VALUE
NLS_CHARACTERSET       WE8ISO8859P1
NLS_NCHAR_CHARACTERSET WE8ISO8859P1

And Unix NLS_LANG parameter :
$ echo $NLS_LANG
AMERICAN_AMERICA.WE8ISO8859P1

I tried changing NLS_LANG parameter to WE8ISO8859P9(Trukish characterset) but no help!
Could anyone let me know the solution to this problem?

A: I presume that you are trying to visualize your file with "vi" or something similar.NLS_LANG parameter is used only by your database to export to your file.For your editor(vi), you need to set the LANG parameter to the corresponding value to your NLS_LANG.
   Exemple : For ISO8859P1 american english you have to do
             export LANG=en_US.ISO8859-1
In other words your file is just fine it's your editor who doesn't know what to do with your Turkish characters.

A: You should use NCHAR data types. More information is available at Oracle Documentation - SQL and PL/SQL Programming with Unicode
For spooling from SQL*Plus, you need to set the NLS_LANG environment variable correctly. Here is a similar question in stackoverflow.


text:
Q: How do I check if I am using GPU on AWS? I am training a NN using keras in a deep learning AMI (ubuntu 12) in AWS.
How do I ensure that my script in Jupyter Notebook is using GPU?

A: Before running the session in tensorflow you could add this line of code to check:
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

For further detail of using GPU with tensorflow, you could check it out on tensorflow official website: https://www.tensorflow.org/guide/using_gpu


text:
Q: How do template instantiations get compiled by Clang? I am using Clang as a library to compile some templated code:
template<typename T>
T getSevenTemplated() {
  return 7;
}

int getSeven() {
  return getSevenTemplated<int>();
}

Unfortunately, the compiled LLVM IR does not actually contain the implementation of getSevenTemplated<int>:
; ModuleID = './test.cpp'
source_filename = "./test.cpp"
target datalayout = "e-m:o-i64:64-f80:128-n8:16:32:64-S128"
target triple = "x86_64-apple-macosx10.12.0"

; Function Attrs: ssp uwtable
define i32 @_Z8getSevenv() #0 {
entry:
  %call = call i32 @_Z17getSevenTemplatedIiET_v()
  ret i32 %call
}

declare i32 @_Z17getSevenTemplatedIiET_v() #1

attributes #0 = { ssp uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="penryn" "target-features"="+cx16,+fxsr,+mmx,+sse,+sse2,+sse3,+sse4.1,+ssse3,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
attributes #1 = { "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="penryn" "target-features"="+cx16,+fxsr,+mmx,+sse,+sse2,+sse3,+sse4.1,+ssse3,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }

!llvm.module.flags = !{!0}
!llvm.ident = !{!1}

!0 = !{i32 1, !"PIC Level", i32 2}
!1 = !{!"clang version 5.0.0 (trunk 292778)"}

Here is the code I am using to generate the LLVM module:
auto* context = new llvm::LLVMContext(); // TODO: Fix leak

auto codeGenerator =
  std::shared_ptr<clang::CodeGenerator>(
    clang::CreateLLVMCodeGen(
      compilerInstance.getDiagnostics(),
      filePath,
      compilerInstance.getHeaderSearchOpts(),
      preprocessor.getPreprocessorOpts(),
      compilerInstance.getCodeGenOpts(),
      *context,
      nullptr));

codeGenerator->Initialize(compilerInstance.getASTContext());

// declGroups are found by calling ParseAST with a special ASTConsumer earlier
for (auto declGroup : declGroups) {
  codeGenerator->HandleTopLevelDecl(declGroup);
}

codeGenerator->HandleTranslationUnit(compilerInstance.getASTContext());

To investigate why, I looked through the source-code and I found that the CodeGenerator has specific logic for handling templates: it seems to skip function template instantiations! I presume that it handles the generated functions instead, but I don't know how it really works.
My questions are:

*

*At a high level, how does Clang go about instantiating templates and passing them to the ASTConsumer for code generation?

*Are there any special tricks for enabling the generation of function bodies for instantiated templates? What am I missing from the code above?

A: The problem was that I had incremental parsing turned on. With this setting enabled, the ParseAST function does not call clang::Sema::ActOnEndOfTranslationUnit, which triggers the instantiation of templates.
The trick is to add this call after processing your decls:
// This triggers the instantiation of templated functions
sema.ActOnEndOfTranslationUnit();


text:
Q: How to draw Matrix Code with PdfSharp? I need to make a PDF report via PdfSharp. The report must include a QRCode, or data matrix code, but I can't seem to be able to draw it on the page.
The values it's asking for are value as String and length as Integer so here's what I'm doing:
Dim myNewCode As New PdfSharp.Drawing.BarCodes.CodeDataMatrix("1234567890", 10)

Then I try to draw it:
gfx.DrawMatrixCode(myNewCode, myXPoint)

It asks for an XPoint location so I set it to this:
Dim myXPoint As New XPoint(500,500)

Which only needs values for x and y.
It compiles OK but when I try to open the file I get the next error
An error exists on this page. Acrobat may not display the page correctly. Please contact the person who created the PDF document to correct the problem

My Acrobat version is 11.0.5, and there is no problem opening other PDF files which already contain these kind of codes.

A: Specify the size to get a correct PDF file:
var myXSize = new XSize(100, 100);
var myNewCode = new PdfSharp.Drawing.BarCodes.CodeDataMatrix("1234567890", 10, myXSize);
var myXPoint = new XPoint(200, 300);
gfx.DrawMatrixCode(myNewCode, myXPoint);

Please note that due to legal reasons, the open source version of PDFsharp does not include the implementation of the Data Matrix Code and shows dummy images instead.

A: Another option would be to use a 3rd party library (ZXing) to generate the QR Code bitmap and draw it as a bitmap with DrawImage() on the PDF.


text:
Q: std::bad_alloc error in DBSCAN I am getting the error,

std::bad_alloc error

when I try to use DBSCAN algorithm of fpc package. Data set is large( 50k spatial coordinates). I am not getting how to resolve this .I am working in R studio.

A: Add more memory to your computer.
fpc computes all pairwise distances. For 50k objects that requires about 10 GB of RAM.
Consider using DBSCAN in ELKI, with the cover tree and great-circle distance.
This does not require a distance matrix and is thus much faster and needs much less memory.


text:
Q: What does a Type-Import-on-Demand Declaration import? In Java, there are two valid forms of the import declaration:

*

*import java.lang.Math;

*import java.lang.Math.*;
In the latter, a wildcard is used. This form is known as a Type-Import-on-Demand declaration, but how is it different from the former? Does it also import the subpackages of java.lang.Math?
What if Math were a Type (e.g., a class)—would all of its inner classes be imported?

A: The documentation states:

Note: Another, less common form of import allows you to import the public nested classes of an enclosing class. For example, if the graphics.Rectangle class contained useful nested classes, such as Rectangle.DoubleWide and Rectangle.Square, you could import Rectangle and its nested classes by using the following two statements.
import graphics.Rectangle;

import graphics.Rectangle.*;

Be aware that the second import statement will not import Rectangle.

So importing import  java.lang.Math.*; will not import the Math class.
NOTE: You may also want to see Why is using a wild card with a Java import statement bad?

A: import  java.lang.Math.*;
This will import all nested classes declared in the Math class in the java.lang package. References to nested classes could be given without the outer class (e.g., Foo for java.lang.Math.Foo).
import  java.lang.Math;
This will import the Math class in the java.lang package. References to nested classes would have to be given with the outer class (e.g., Math.Foo).

A: Only immediately-nested types are imported. The declaration is not recursive.
This does work with types for importing inner classes.This also works with static import (for importing methods).
import static a.b.c.FooBar.*;

A: The statement
import java.util.ArrayList.*;

imports all nested classes of ArrayList, but not ArrayList itself. Since ArrayList does not have any (public) nested classes, the statement actually does nothing.
However, consider the interface Map, which defines the nested class Map.Entry. If we write
import java.util.Map.*;

at the start of the Java file, we can then write Entry<A,B> instead of Map.Entry<A,B> to refer to this nested class.
Importing members of classes usually makes the most sense if you are using static imports. Then you don't import nested classes, but static methods and variables. For example,
import static java.Math.*;

will import all static constants and methods from the Math class. Then you can use the static methods of the Math class by writing, e.g. sin(x) instead of Math.sin(x).

A: With the statement import java.util.ArrayList.*; you will import all nested classes declared into ArrayList class.
If you also want to import methods and const, for example, declares:
import static java.lang.Math.*;

Then you can use the constant PI in your code, instead of referencing it through Math.PI, and the method cos() instead of Math.cos(). So, for example, you can write:
double r = cos(PI * theta);

A: Basically Math is a final class, and it does not have further sub classes. There is no difference between import  java.lang.Math.* and import java.lang.Math Both are one and the same. So I really dont see the need here to use the first kind of import.


text:
Q: What's the fastest way to identify the 'name' of a dictionary that contains a specific key-value pair? I'd like to identify the dictionary within the following list that contains the key-value pair 'Keya':'123a', which is ID1 in this case.
lst = {ID1:{'Keya':'123a','Keyb':456,'Keyc':789},ID2:{'Keya':'132a','Keyb':654,'Keyc':987},ID3:{'Keya':'5433a','Keyb':222,'Keyc':333},ID4:{'Keya':'444a','Keyb':777,'Keyc':666}}

It's safe to assume all dictionaries have the same key's, but have different values.
I currently have the following to identify which dictionary has the value '123a' for the key 'Keya', but is there a shorter and faster way?
    DictionaryNames = map(lambda Dict: str(Dict),lst)
    Dictionaries = [i[1] for i in lst.items()]
    Dictionaries = map(lambda Dict: str(Dict),Dictionaries)

    Dict = filter(lambda item:'123a' in item,Dictionaries)
    val = DictionaryNames[Dictionaries.index(Dict[0])]
    return val

A: If you actually had a list of dictionaries, this would be:
next(d for d in list_o_dicts if d[key]==value)

Since you actually have a dictionary of dictionaries, and you want the key associated with the dictionary, it's:
next(k for k, d in dict_o_dicts.items() if d[key]==value)

This returns the first matching value. If you're absolutely sure there is exactly one, or if you don't care which you get if there are more than one, and if you're happy with a StopIteration exception if you were wrong and there isn't one, that's exactly what you want.
If you need all matching values, just do the same with a list comprehension:
[k for k, d in dict_o_dicts.items() if d[key]==value]

That list can of course have 0, 1, or 17 values.

A: You can just do [name for name, d in lst.iteritems() if d['Keya']=='123a'] to get a list of all the dictionaries in lst that have that value for that key.  If you know there is only one, you can get it with [name for name, d in lst.iteritems() if d['Keya']=='123a'][0].  (As Andy mentions in a comment, your name lst is misleading, since lst is actually a dictionary of dictionaries, not a list.)

A: Å different way to do this is to use the appropriate data structure: Keep a "reverse map" of key-value pairs to names. If your dictionary of dictionaries is static after being built, you can build the reverse dictionary like this:
revdict = {(key, value): name
           for name, subdict in dictodicts.items()
           for key, value in subdict.items()}

If not, you just need to add revdict[key, value] = name for each d[name][key] = value statement and build them up in parallel.
Either way, to find the name of the dict that maps key to value, it's just:
revdict[key, value]

For (a whole lot) more information (than you actually want), and some sample code for wrapping things up in different ways… I dug up an unfinished blog post, considered editing it, and decided to not bother and just clicked Publish instead, so: Reverse dictionary lookup and more, on beyond z.

A: Since you want the fastest, you should short-cut your search as soon as you find the data you are after. Iterating through the whole list is not necessary, nor is producing any temporary dictionary:
for key,data in lst.iteritems():
    if data['Keya']=='132a':
        return key   #or break is not in a function


text:
Q: Oracle "connect by prior" along with "max() over partition by" to remove duplicate subtree I am trying to remove duplicate subtree returned by "connect by prior" clause. I wish to check top level node of tree hierarchy, where user can enter child IDs which are already part of subtree. Take a look at following example:
SELECT * FROM (
With test_hierarchy as(
       SELECT 'a' parent, 'b' child FROM dual UNION ALL
       SELECT 'b','c' FROM dual UNION ALL
       SELECT 'd','e' FROM dual UNION ALL
       SELECT 'e','f' FROM dual UNION ALL
       SELECT 'f','g' FROM dual UNION ALL
       SELECT 'f','h' FROM dual)
SELECT
    parent,
    child,
    CONNECT_BY_ROOT child AS init_child,
    LEVEL,
    CONNECT_BY_ISLEAF,
    MAX(LEVEL) OVER(
        PARTITION BY parent
    ) AS max_level
FROM
    test_hierarchy
WHERE
    CONNECT_BY_ISLEAF = 1
START WITH
    child IN (
        'c', 'b', 'e', 'f', 'h', 'g'
    )
CONNECT BY
    PRIOR parent = child);

This query returns result as:
P C I      LEVEL CONNECT_BY_ISLEAF  MAX_LEVEL
- - - ---------- ----------------- ----------
a b b          1                 1          2
a b c          2                 1          2
d e g          3                 1          3
d e f          2                 1          3
d e h          3                 1          3
d e e          1                 1          3

I wish to return only those top level nodes with level = max_level. I.e. my query should return result as:
P C I      LEVEL CONNECT_BY_ISLEAF  MAX_LEVEL
- - - ---------- ----------------- ----------
a b c          2                 1          2
d e g          3                 1          3
d e h          3                 1          3

If I try to filter out results using WHERE clause as "WHERE level = max_level", Oracle complains:
ORA-01788: CONNECT BY clause required in this query block
01788. 00000 -  "CONNECT BY clause required in this query block"

Please let me know if you have an idea on how to do it.
Thanks,

A: Wrap your recursive query in another CTE and filter on that:
WITH
  test_hierarchy AS (
    SELECT 'a' parent, 'b' child FROM dual UNION ALL
    SELECT 'b','c' FROM dual UNION ALL
    SELECT 'd','e' FROM dual UNION ALL
    SELECT 'e','f' FROM dual UNION ALL
    SELECT 'f','g' FROM dual UNION ALL
    SELECT 'f','h' FROM dual
  ),
  recursion AS (
    SELECT
      parent,
      child,
      CONNECT_BY_ROOT child AS init_child,
      LEVEL AS lvl,
      CONNECT_BY_ISLEAF AS isleaf,
      MAX(LEVEL) OVER(
        PARTITION BY parent
      ) AS max_level
    FROM
      test_hierarchy
    START WITH child IN ('c', 'b', 'e', 'f', 'h', 'g')
    CONNECT BY PRIOR parent = child
  )
SELECT *
FROM recursion
WHERE isleaf = 1 AND lvl = max_level

A: Your logik works, but is sort of brute force approach, i.e. examine all possibilities and select the valid only.
One alternative is simple to limit your START WITH to consider the leave nodes only.
This can be done by excluding all nodes that are   parent nodes:
START WITH
    child IN ( 'c', 'b', 'e', 'f', 'h', 'g') and
    child not in (select parent from test_hierarchy)

The final query have better performance because of limited START list and you need no WINDOWS SORT to get max level:
With test_hierarchy as(
       SELECT 'a' parent, 'b' child FROM dual UNION ALL
       SELECT 'b','c' FROM dual UNION ALL
       SELECT 'd','e' FROM dual UNION ALL
       SELECT 'e','f' FROM dual UNION ALL
       SELECT 'f','g' FROM dual UNION ALL
       SELECT 'f','h' FROM dual)
SELECT
    parent,
    child,
    CONNECT_BY_ROOT child AS init_child,
    LEVEL,
    CONNECT_BY_ISLEAF
FROM
    test_hierarchy
WHERE
    CONNECT_BY_ISLEAF = 1
START WITH
    child IN ( 'c', 'b', 'e', 'f', 'h', 'g') and
    child not in (select parent from test_hierarchy)
CONNECT BY
    PRIOR parent = child;

P C I      LEVEL CONNECT_BY_ISLEAF
- - - ---------- -----------------
a b c          2                 1
d e g          3                 1
d e h          3                 1


text:
Q: Privilege Notifications I'm new to Stack Overflow and just received new privileges this morning.
Now I received three new notifications about additional privileges that I received, even though I don't think I've reached the reputation points level for them. At the moment I have 13 reputation points, and I recieved notifications for the following privileges:

*

*Vote up

*Flag Posts

*Talk in chat

I tried voting up and it doesn't work (since I don't have the reputation points for it). What's going on?

A: You most likely received some points that were retracted again. You briefly did receive the required reputation points, then lost them again. This can happen when someone upvotes one of your posts, then retracts that vote within the grace period. The 10 points for an answer vote would have been sufficient to see the behaviour you described.
Another possibility is that another post of yours was deleted after you received enough points to cross the 20 point line (the talk in chat permission), and you dropped back down to 13 points. You can see if any posts were deleted by checking the show removed posts checkbox on your reputation tab.
Either way, this is status-bydesign; privileges are tied tightly to your reputation points. If you drop below the required level, you lose them again.


text:
Q: How do I insert rows into a spatial table within a geopackage file via a SQL INSERT statement? I am attempting to insert rows into a spatial table within a geopackage file using DBeaver 5.1.1.
I receive an error from the triggers, referencing functions that don't exist: ST_IsEmpty.  Do I need to load these functions via a similar means to the spatialite load_extension? And does a library extension exist for geopackages?
SQL Error [1]: [SQLITE_ERROR] SQL error or missing database (no such function: ST_IsEmpty)
  [SQLITE_ERROR] SQL error or missing database (no such function: ST_IsEmpty)
  [SQLITE_ERROR] SQL error or missing database (no such function: ST_IsEmpty)

A: I sort of answered my own question in the question.  I issued a
SELECT load_extension('mod_spatialite.dll');
statement (files are already in my path).  And I was able insert my rows.  While it works, there may be a more correct way to do it? Like using a geopackage specific extension?
Also for DBeaver, I had to enable_load_extension on the driver properties.


text:
Q: Database Health - SQL Server If someone asks me to check the database health in a particular SQL Server database, which has been running for couple of years, what are the possible areas that I need to check? Do we have any tools to support for that?
Kindly provide some recommended links also to refer.

A: You need to do two things (at a bare minimum):

*

*Make sure that backups are being taken on a regular basis and that at least once a full restore was done from the backups and that the restore was verified to contain valid, up to date, data.
https://msdn.microsoft.com/en-us/library/ms187510.aspx

*Run 'DBCC checkdb' on the instance. It will take a while and can be a resource hog (you may want to run it at night or over a weekend.) Be very careful in reading the results and figuring out what to do if it detects errors.
https://msdn.microsoft.com/en-us/library/ms176064.aspx
http://www.sqlskills.com/blogs/paul/category/checkdb-from-every-angle/

*If you do the above you may be held responsible for any, and all, issues that will ever occur to SQL Server including data entry errors.


text:
Q: filesize(): stat failed for file.zip I am creating a zip file combining 2 files but showing error while opening it.But when i open it with a code editor it shows some error.
My main code is:
<?php
    $files = array(
                'localhost/apache_pb2_ani.gif',
                'localhost/apache_pb2.png');
                $zipname = 'file.zip';
                $zip = new ZipArchive;
                $zip->open($zipname, ZipArchive::CREATE);
                foreach ($files as $file) {
                  $zip->addFile($file);
                }
                $zip->close();
            //if true, good; if false, zip creation failed
            header('Content-Type: application/zip');
            header('Content-disposition: attachment; filename='.$zipname);
            header('Content-Length: ' . filesize($zipname));
            readfile($zipname);
    ?>

And the errors are :
Warning:filesize(): stat failed for file.zip in C:\xampp\htdocs\download.php on line 19
Warning:  readfile(file.zip): failed to open stream: No such file or directory in <b>C:\xampp\htdocs\download.php on line 20
What seems to be error?

A: I can reproduce the warnings if the paths to the files I use in the $files array are not correct.
Are you sure that the paths (with the 'localhost/') to your images are correct?
$files = array(
    'localhost/apache_pb2_ani.gif',
    'localhost/apache_pb2.png'
);


text:
Q: Monitoring the LMAX Disruptor How to monitor the LMAX Disruptor? Say I have 3 ringbuffers and wish to provide a ui that will give me information of the ringbuffers.

A: The most important property you probably want to monitor is the remaining capacity so that you can tell if the consumers are keeping up.
The simplest way to expose that would be to create a bean which can read the RingBuffer.remainingCapacity() and expose that via JMX. That way you can get remote monitor GUI's e.g. JConsole, JVisualvm, stats logging/monitoring via graphite, openNMS or nagios


text:
Q: asp.net mvc, generate url by custom route i have created application, where url generates depends on database values.
i parse these urls without any problem and get controller and action from database in my route handler.
but when i try to generate url, i get troubles.
in my case, it seems like:
view
@Html.ActionLink("more", MVC.Blog.Post(item.Alias)) // i use T4MVC

MyRouteConstraint
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
    if (routeDirection == RouteDirection.UrlGeneration)
    {
        var data = GetDataFromDbByControllerActionAndParameters(values);
        if (data == null)
            return false;
        var valuesToRemove = new List<string>();
        var path = GenerateUrlByData(data, valuesToRemove);
        values.Remove("controller");
        values.Remove("action");
        valuesToRemove.ForEach(v => values.Remove(v)); // remove values that is already used in path
        values.Add("all", path) // path = "blog/post/postalias"
        return true;
    }
    //  skipped code
}

route rule
routes.MapRoute("Locations", "{*all}",
    constraints: new { all = new LocationConstraints() },
    defaults: new { },
    namespaces: new []{typeof(BaseController).Namespace}).RouteHandler = new LocationRouteHandler();

and as result i got url like this
localhost:8553/?Controller=Blog&Action=Post&alias=postalias

but expect like this
localhost:8553/blog/post/postalias

how can I generate url? where it should be? i think not in the constrant, but why it is invoked in this case?

A: In my MVC application the closest route that matches the one you have is the one below:
routes.MapRoute(
    name: "MyRouteName",
    url: "{SomeFolder}/{SomePageName}",
    defaults: new { controller = "MyController", action = "Index" },
    constraints: new { routeConstraint = new MyRouteConstraint() }
);

SomeFolder can be fixed or changed from the database while SomePageName will be changed to a different value from database. The url should be whatever URL you want to match with this route and the one that will be replaced by the value from the database. The defaults address the Controller and Action that will render the page in the end of the MVC cycle. The constraints will lead to your Match method described.
With this configuration I have URLs like www.project.com/SomeFolder/SomePageNameFromDatabase.


text:
Q: Rehydrating state with no initial object store Title pretty much explains my issue, I'm persisting state else where in my component that stores an object in localforage. The object gets stored fine later in the component, but IF I'm coming in the component/page for the first time there is no store available to retrieve from localforage.
I'm rehydrating in componentDidMount but if there's no store to update a state value with it throws an error and the component crashes.
  async componentDidMount() {
    localforage
      .getItem("uriStore")
      .then(localforageStore => {
        // This code runs once the value has been loaded
        // from the offline store.
        console.log("localforage store in cDM ---> ", localforageStore);
        this.setState({
          Uris: localforageStore
        });
      })
      .catch(error => console.log("Error -->", error)
  }

So how can I handle the case when there's no data in the store?


text:
Q: How to control static content cache configuration in Tomcat 7 + Struts 1.2 My static content is being cached by the browsers and i want to control it.
But I can't find any related configuration.
The browsers cache the static content only when it accessed through struts action. When I request an image with direct link it is not taken from cache (304).
And oddly, the cached content is received (at first time) without "expire" or "cache-control" headers. The sole relevant included header is "Etag".
Can someone explain this?


text:
Q: Location of local files in cordova I'm using a video player which accepts an absolute path as parameter. If I put my video in the www folder, and use this code:
var path = cordova.file.applicationDirectory + 'www/myvideo.mp4';
GoogleVRPlayer.playVideo(path);

the video starts to play. The logs tell me the video is in:
file:///var/containers/Bundle/Application/F4D23EDE-...-...-...-.../appname.app/www/myvideo.mp4

However, I don't want my video to be "baked in" the app: I want users to download it first. For the download, I use cordova-plugin-file-transfer:
download()
    {
        this.fileTransfer.download(
            this.uri,
            'cdvfile://localhost/persistent/path/to/downloads/',
            function(entry) {
                console.log("download complete: " + entry.toURL());
            },
            function(error) {
                console.log("download error source " + error.source);
                console.log("download error target " + error.target);
                console.log("download error code" + error.code);
            },
            false,
            {
                headers: {
                    "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
                }
            }
        );
    }

This works fine too. The video downloads, and the log tells me the video is stored in
file:///var/mobile/Containers/Data/Application/785BC9AF-...-...-...-.../Documents/path/to/downloads

Notice that the ID after "Application" is different for both files. Also, appname.app is not present in the URL of the downloaded file. But the video must be part of the app, because the app size increases after downloading the video...
How can I make the plugin download the file in the www folder, so I can play it? Or, which path should I use in the player so I can play the video downloaded in path/to/downloads?
Update 1: added extra info
Update 2:
I've changed the first path to
cordova.file.documentsDirectory + 'path/to/downloads/myvideo.mp4';.
Console tells me the video is stored in:
file:///var/mobile/Containers/Data/Application/A9B73639-...-...-...-.../Documents/path/to/downloads
and the video it's trying to play is:
file:///var/mobile/Containers/Data/Application/A9B73639-...-...-...-.../Documents/path/to/downloads/myvideo.mp4
However, the player doesn't play the file: Failed to load video: The operation could not be completed

A: Edit 2:
The user fixed the issue.
It was a path error. Setting the name of the downloaded file as an argument in the fileTransfer function corrected the issue.
Edit:
I see you are using the VR player plugin. Looking at the documentation it uses Google's VR player as a basis for the plugin. Are you able to play the video in a web browser by filling the the guide here:
https://developers.google.com/vr/concepts/vrview-web
This will confirm that the video is compatible with the player that the plugin uses.
Original Answer:
If you want to store the file you download it is probably best to use the Cordova file plugin.
cordova plugin add cordova-plugin-file

Using this in conjunction with the file transfer plugin
cordova plugin add cordova-plugin-file-transfer

The problem is that, according to the file plugin documentation the /www folder is read only once the app is installed so you cannot download and store files there.
Documentation here.
https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/


text:
Q: Why do injective holomorphic functions have nonzero derivative For some open sets $U$, $V$ in the complex plane, let $f:U\rightarrow V$ be an injective holomorphic function. Then $f'(z) \ne 0$ for $z \in U$.
Now I don't understand the proof, but here it is from my text. My comments are in italics.
Suppose $f(z_0) = 0$ for some $z_0 \in U$.
$f(z) - f(z_0) = a(z - z_0)^k + G(z)$ for all $z$ near $z_0$, with $a \ne 0, k \ge 2.$
Also, $G$ vanishes to order $k+1$ at $z_0$.
I'm not clear on what this "vanishing" thing means. Maybe it means that $G$ can be expressed as a power series of order $k+1$ around $z_0$.
For sufficiently small $w$ we can write $f(z) - f(z_0) - w = F(z) + G(z)$, where $F(z) = a(z - z_0)^k - w$.
I'm not sure why we need to have $w$ small. This equation will work for any $w$.
Since $|G(z)| \lt |F(z)|$ on a small circle centered at $z_0$, and $F$ has at least two zeros inside that circle, Rouche's theorem implies that $f(z) - f(z_0) - w$ has a least two zeros there.
Now I think that $|G(z)| \lt |F(z)|$ can follow simply from the fact that $F$ is a polynomial of degree $k$ while $G$ has degree $k+1$. And the remark about the two zeros can follow from the fact that $F$ must have $k$ zeros in the complex plane. But the first part requires that we consider $z$ only on a small circle. The second part requires that our circle be big enough to capture two zeros. How do we know that we can satisfy both?
Since $f'(z) \ne 0$ for for all $z \ne z_0$ sufficiently close to $z_0$, the roots of $f(z) - f(z_0) - w$ are distinct, so $f$ is not injective - a contradiction.
I think that the derivative is never zero for values of $z$ other than $z_0$ because otherwise we would have a sequence of zeros limiting towards $z_0$ which would cause our function to be constant which is a contradiction. But again we have the same problem - we can only consider a small circle. The roots of $f$ may lie outside this circle.

A: First comment: Yes. I prefer to write $(z-z_0)^k\cdot(a+(z-z_0)H(z))$ in such proofs.
Second comment: $w$ small is not needed immediately, but we can only use a small circle (as guaranted by openness of $U$) and want to have $(z-z_0)^k=w$ at least once (end hence $k$ times) inside that circle. This is what forces $w$ to be small.
Third comment: We make our circle even smaller (and may revise our choice of $w$) in order to make $|G|<| F|$. By the vanishing order of $G$, we have $G(z)\le c\cdot |z-z_0|^{k+1}$ for some $c$ as long as $z\approx z_0$ (with my notation above, you can take any $c>|H(z_0)|$). Then what we need here for $|G(z)|<|F(z)|$ if $|z-z_0|=r$ is to chose $r\le \frac ac$. The very simple polynomial $F$ has $k$ zeroes in the circle because we choose our $w$ small enough (smaller than $ar^k$ if $r$ is the radius of our small circle).
Fourth comment: The zeroes of a holomorphic function are isolated unless the function is (locally) constant. If $f$ is constant on a small open disk, it is already far from injective.

A: I guess the text you were using was Stein and Shakarchi's Complex Analysis.
Actually, the proof is a bit problematic and should be modified in the following way.
We can first choose a small circle C centered at $z_0$ such that $|a(z-z_0)^k| > |G(z)|$ for any $z$ on this circle. This can be done simply because $G(z)$ is of order $k+1$ or higher.
Now we can choose a $w < \inf_{z\in C} \left(|G(z)| - |a(z-z_0)^k|\right) $. This guarantees that $|F(z)| = |a(z-z_0)^k-w| > |G(z)|$ on the circle.
Of course you can also require $w$ to be small enough to make sure the roots of $a(z-z_0)^k - w$ are inside the circle. (In fact, all those roots are on a circle centered at $z_0$ of radius $ {|w/a|}^{1/k}$.)


text:
Q: How do I implement a unary operator overload for a forward declared type in C++? The following code does not compile in Visual Studio 2008. How do I get it to allow a unary operator in the Foo1 class that converts it to a Bar, when Foo1 is defined before Bar?
class Foo1
{
public:
    int val;

    operator struct Bar() const;
};

struct Bar
{
    int val;
};

// This does not compile
Foo1::operator Bar() const
{
    Bar x;
    x.val = val;
    return x;
}

A: Or you could:
//forward declaration of Bar
struct Bar;

class Foo1
{
public:
    int val;

    operator Bar() const;
};

struct Bar
{
    int val;
};

//Now it should compile
Foo1::operator Bar() const
{
    Bar x;
    x.val = val;
    return x;
}

A: I figured out the answer. There are two solutions:
struct Bar;

class Foo1
{
public:
    int val;

    operator struct Bar() const;
};

Or:
class Foo1
{
    typedef struct Bar MyBar;
public:
    int val;

    operator MyBar() const;
};

(The operator::Bar() implementation remains unchanged)