text:
Q: JdbcTemplate's update method does not update without PreparedStatementCreator I have the following table
CREATE TABLE user_use_case_control (
id integer GENERATED BY DEFAULT AS IDENTITY (START WITH 10, INCREMENT BY 1) not null,
name varchar(20) not null,
start_date timestamp not null,
end_date timestamp null,
duration timestamp null,
status varchar(20) null,
user_id varchar(20) not null );

I am working with Spring Framework 4.0.5, with JdbcTemplate,  and I have the following insertion method (part of the method)
Alpha
this.jdbcTemplate.update(

        new PreparedStatementCreator()  {

            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {

                PreparedStatement ps = connection.prepareStatement(sql,
                Statement.RETURN_GENERATED_KEYS);

                ps.setString(1, userControl.getName());
                ps.setTimestamp(2, new Timestamp( userControl.getStartDate().getTime() ));
                ps.setTimestamp(3, new Timestamp( userControl.getEndDate().getTime() ));
                ps.setTimestamp(4, new Timestamp( userControl.getDuration().getTime() ));
                ps.setString(5, userControl.getStatus());
                ps.setString(6, userControl.getUserId());

           return ps;
          }
    }, keyHolder);

Observe:

*

*I am using PreparedStatementCreator to get the generated key.

*I am using ps.setTimestamp and new Timestamp
The insertion method works fine.
The problem is for the update.
I have the following:
Beta
@Override
public UserControl update(UserControl userControl) {

    logger.info("UserControlJdbcRepository - update {}", userControl.toString());

    String sql = "UPDATE user_use_case_control uucc " +
                 "SET uucc.name=?, uucc.start_date=?, uucc.end_date=?, uucc.duration=?, uucc.status=? " +
                 "WHERE uucc.id=?";

    int result = this.jdbcTemplate.update(sql,
                    userControl.getName(),
                    new Timestamp( userControl.getStartDate().getTime() ),
                    new Timestamp( userControl.getEndDate().getTime() ),
                    new Timestamp( userControl.getDuration().getTime() ),
                    userControl.getStatus(),
                    userControl.getUserId());

    logger.info("result {}", result);
…

*

*with logger I can see the object and all their variables are not null

The problem is: the jdbcTemplate.update does not update nothing!
Same situation if I use
int result = this.jdbcTemplate.update(sql,
                 userControl.getName(),
                 userControl.getStartDate(),
                 userControl.getEndDate(),
                 userControl.getDuration(),
                 userControl.getStatus(),
                 userControl.getUserId());

If I do a debug and logger with DEBUG level, I can see the following:
Executing prepared SQL update
Executing prepared SQL statement [UPDATE user_use_case_control uucc SET uucc.name=?, uucc.start_date=?, uucc.end_date=?, uucc.duration=?, uucc.status=? WHERE uucc.id=?]
SQL update affected 0 rows
SQLWarning ignored: SQL state '02000', error code '-1100', message [no data]

I dont understand why happens this.
If the logger has INFO level none error appears, I mean some exception does not arise.
If I change the method with the following:
Omicron
int result = this.jdbcTemplate.update(

        new PreparedStatementCreator()  {

            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {

                PreparedStatement ps = connection.prepareStatement(sql);

                ps.setString(1, userControl.getName());
                ps.setTimestamp(2, new Timestamp( userControl.getStartDate().getTime() ));
                ps.setTimestamp(3, new Timestamp( userControl.getEndDate().getTime() ));
                ps.setTimestamp(4, new Timestamp( userControl.getDuration().getTime() ));
                ps.setString(5, userControl.getStatus());
                ps.setInt(6, userControl.getId());

                return ps;
            }

        });

logger.info("result {}", result);

Just then: It works totally fine.
Observe:

*

*Alpha, Beta and Omicron uses ps.setTimestamp and new Timestamp
Questions:

*

*Why Beta fails? (message [no data])

*Why only works the updating with PreparedStatementCreator?

Note: I have other Repositories and the update methods based on Beta, working without PreparedStatementCreator, work fine.
Just to highlight about the other repositories:

*

*some of them have no a timestamp field, just have date in the db table schema.

*some of them neither have a timestamp field nor a date field in the db table schema.

Therefore this weird behaviour only appears for update when the timestamp field is involved.
Thanks in advance.


text:
Q: What is /usr/bin/parity? While trying to free some disk-space, I found the following file in my /usr/bin:
-rwxr-xr-x 1 root root 29082328 May 17  2017 /usr/bin/parity

What is this application? Is it safe to remove it? And how do I remove it? (I tried sudo apt remove parity but it said "After this operation, 0 B of additional disk space will be used.")

A: If you've been experimenting with Ethereum clients on your system it might be a part of Parity Wallet. If you can verify that Parity Wallet is what you have installed, it's safe to uninstall as it's not a part of your system. Depending on how it was installed, Parity might be running as a snap.

You can try the following to uninstall it if it's running as a snap:
sudo snap remove parity or sudo snap remove parity --edge
If it's a deb then try this:
sudo apt purge parity
Edit: Removed note because now we know that's what was installed

redpajama_set_name: RedPajamaStackExchange


text:
Q: Raspberry Pi: authentication to OneDrive via SSH terminal I'm looking for an easy solution or work-around for the following.  I am working remotely on my Raspberry Pi by using SSH (Putty) for code execution and WinSCP for file transfers to the Pi.  My project consists of a motion detection system and the Raspberry camera to detect movement and take a sequence of snapshot pictures, that will be instantly uploaded to OneDrive.
I'm using this textbook code for the OneDrive authorization and authentication:
import onedrivesdk
from onedrivesdk.helpers import GetAuthCodeServer

redirect_uri = 'http://localhost:8080/'
client_id = 'd5cXXXX-XXXXX-XXXX-XXXXXX89b8'
client_secret = 'eXXXXXXXXXXXXXXXt9L'

scopes = ['wl.signin', 'wl.offline_access', 'onedrive.readwrite']

client = onedrivesdk.get_default_client(client_id = client_id, scopes = scopes)

auth_url = client.auth_provider.get_auth_url(redirect_uri)

# After successful authorization, the authentication code is fetched from the server:
code = GetAuthCodeServer.get_auth_code(auth_url, redirect_uri)

client.auth_provider.authenticate(code, redirect_uri, client_secret)

This part works fine when working directly on the Raspberry Pi, i.e.: the web browser is launched and log-in is requested, after which the redirect uri is called and the authentication code is fetched.
What I am after is to find a way to be able to run the code directly via the SSH terminal without the browser interaction.  If possible, I'd like the authorization to be done in textual format, and suppress the web browser from opening, because that results in "stuck" code on the SSH terminal...


text:
Q: How to pass parameters to callbacks in flutter? class ExtractArgumentsScreen extends StatelessWidget {
  static const routeName = '/extractArguments';

  double price = 0;

  _changeprice(num){
      setState(){
        price+ = num;
      }
    }

  @override
  Widget build(BuildContext context) {
    final MealArguments args = ModalRoute.of(context).settings.arguments;

    return Scaffold(
      appBar: AppBar(
        title: Text('MyApp'),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          SizedBox(height: 20,),

          ViewCard(args.combo,_changeprice()),
        ]));

This is the parent class. I passed the function _changePrice() to ViewCard so that I can change the value of the price later.
This is giving me an

error "1 required argument(s) expected, but 0 found"

but I can't pass an argument to _changePrice as that defeats the whole purpose of using this callback.
What I'm trying to implement is similar to what was suggested in Emit the data to parent Widget in Flutter.
The child class ViewCard passed this callback to another child called OneItem.
class OneItem extends StatefulWidget {
  OneItem(this.combo, this.index, this.changePrice);
  final Combo combo;
  final int index;
  final VoidCallback changePrice;

  @override
  State<StatefulWidget> createState() => OneItemState();
}

class OneItemState extends State<OneItem> {
  List<bool> Vals = new List();

  @override
  void initState() {
    super.initState();

    int count = widget.combo.items.length;

    Vals = List<bool>.generate(count, (_) => false);
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Align(
          child: Text(widget.combo.items[widget.index].item),
          alignment: Alignment(-1, 0),
        ),
        Align(
            child: Text(widget.combo.items[widget.index].price),
            alignment: Alignment(0.1, 0)),
        Align(
            child: Checkbox(
              value: Vals[widget.index],
              onChanged: (bool value) {
                setState(() {
                  Vals[widget.index] = value;
                  if(value == true){double childPrice = double.parse(widget.combo.items[widget.index].price); }
                  else{double val = double.parse(widget.combo.items[widget.index].price);
                        double childPrice = -1*val;}
                  widget.changePrice(childPrice);
                  //widget.changePrice();
                });
              },
            ),
            alignment: Alignment(0.6, 0)),
      ],
    );
  }
}

A: You could declare a Function callback, like this:
final void Function(double price) changePrice;

Here another example to understand it better:
final bool Function(String id, double price) updateItem;

bool isPriceUpdated = widget.updateItem("item1", 7.5);

A: You call widget.changePrice(childPrice); from OneItemState, so changePrice can't be VoidCallback
typedef IntCallback = Function(int num);

/* ... */

class OneItem extends StatefulWidget {
  OneItem(this.combo, this.index, this.changePrice);
  final Combo combo;
  final int index;
  final IntCallback changePrice;

  @override
  State<StatefulWidget> createState() => OneItemState();
}

/* ... */

ViewCard(args.combo, _changeprice) // function name without braces

I would do it like this


text:
Q: Angular UI Router - functions inside template not working I am learning to use Angular UI Router to control the different parts of the application.
Take a look at this plunkr (http://plnkr.co/edit/KH7lgNOG7iCAEDS2D3C1?p=preview)
Things not working:

*

*When the view is loaded the {{ logger }} value in not being updated though I have initialized it in the Homecontroller.

*Login and logout buttons dont work as expected.
Help much appreciated.

A: Turned out to be quite a complicated problem.  To apply a controller to multiple views, you'll need to apply the controller directly to the html using ng-controller (e.g. ng-controller="HomeController".  From there, you apply individual controllers to each view.
So, to fix things up, add controller: 'LoginController' to the views.navbar object, then you'll need the following two controllers instead.
.controller('LoginController',
  ['$scope','userInfo',function($scope,userInfo){
    $scope.login = function(){
      $scope.model.logger += "Logged in \n";
      $scope.model.user = userInfo;
    }

    $scope.logout = function(){
      $scope.logger += "logged out \n";
      $scope.user = false ;
    }
  }])
.controller('HomeController',
  ['$scope',function($scope){
    $scope.model = {
      user: null,
      logger: 'Nothin to log yet :'
    };
  }]);

Here's the updated plnkr which should now work as expected.


text:
Q: java zk mvvm clear datebox and do @command I'm trying to make a filter with a datebox.
When no date is inserted, this will not be added to the query.
When date is inserted, he counts from this date on.
This works all very good, the only stupid little problem I have is that I have a button for clearing the date.
Or I do with @command(...) and set mine queryObject.date to null, witch will renew mine search correct BUT the date is still in the datebox. (I don't want to use autowired for the datebox)
Or I do searchBeginDate.setText(null) and the text is gone but mine list doesn't refresh.
What option I have to do the both?
edit : sample code of project.
 <datebox id="searchBeginDate" value="@bind(vm.loggingVmQueryObject.beginDate)" onOK="@command('filter')" />
 <button onClick="searchBeginDate.setText(null);vm.loggingVmQueryObject.setBeginDate(null)"  image="/img/delete.PNG" />

This do the whiping of the datebox but the list isn't refreshed.
<datebox id="searchBeginDate" value="@bind(vm.loggingVmQueryObject.beginDate)" onOK="@command('filter')" />
<button onClick="@command('clearBeginDate')"  image="/img/delete.PNG" />

This refresh the list correct, in code the loggingVmQueryObject.beginDate is set to null but the datebox is still showing last date set.
Greetz chill.

A: You show me the code, I show a solution ;)
in zul
<datebox id="searchBeginDate" value="@bind(vm.loggingVmQueryObject.beginDate)" onOK="@command('filter')" />
<button onClick="@command('clearBeginDate', date = searchBeginDate)"  image="/img/delete.PNG" />

in java
public void clearBeginDate(@BindingParam("date")Datebox date){
//your other code here
date.setText(null);

}


text:
Q: The code in my Java project isn't finding the imports from a referenced library I'm writing a project that uses two classes generated by a different program. I copied the code and pasted it into two empty Java classes. These classes import various classes from the weka.jar file I have added to the project's build path, but all the import lines come up with "Import X cannot be resolved" errors (X being the imported class).
I have two versions of the project:

*

*one where weka.jar is in a "lib" folder (at the same level as the "src" folder containing the two classes) which I right-clicked on in the package navigator of eclipse and selected Build Path->Add to build path

*the other where I right-clicked on the project and selected Build Path->Add External Archives, and navigated to and selected the weka.jar file (in its original location, the program files of the Weka software) as prompted.

I've done this before in the past with success, and I'm not sure why it's not working now?

A: Answering my own question because I found the answer: my jar file was in my User folder (C:\Users[myname]) which Windows apparently limits access to. I moved it into the C drive and the imports worked :)
I still get the error

java.lang.reflect.InaccessibleObjectException: Unable to make
protected final java.lang.Class
java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)
throws java.lang.ClassFormatError accessible: module java.base does
not "opens java.lang" to module weka

at multiple places in

java.base/java.lang.reflect
weka/weka.core.WekaPackageClassLoaderManager
weka/weka.core.ResourceUtils
weka/weka.classifiers.trees.J48

And once in my own code.
I also have multiple warnings (probably the reason for the errors), but my program runs as it should (bar the error message output).


text:
Q: Immediate e-mail alerting for error 229 (permission denied) For a few reasons, I'd like to have all permission denied errors (number 229) emailed to me. Checking master.sys.messages shows that is_event_logged for this error is 0. Thus that rules out using SQL Server Agent error alerts, which rely on the SQL Server error log (I've tested this - I get no alert).
I figured I'd peek in mssqlsystemresource and look at the view definition for sys.messages, thinking maybe I could update is_event_logged for the message in question. But this view gets the system error message from OpenRowset(TABLE SYSERRORS), so that's a no-go.
Is there a reasonably simple way I can get all 229 errors emailed to me immediately (or within maybe 30 seconds) without harming server performance? A 60-second cool-down between emails would probably be a good idea too.

A: Oh, damn it, not 30 seconds after I post this, I stumble across sp_altermessage (naturally, after spending a significant amount of time trying to figure out if I could do this with extended events). So if anybody else is wondering how to do this:
EXEC sp_altermessage 229, 'WITH_LOG', 'true'


text:
Q: Tool to validate regex My goal is to validate regex for wildcard in domain addresses;
I've tried to do it through java.util.regex.Pattern, but some cases confuse me.
Can someone explain, why it considered as valid pattern:
Pattern.compile("h]cat")

And this one as not valid:
Pattern.compile("h[cat")

A: *

*h]cat in this string ] means a literal ] symbol.

*h[cat in this string, a character class is started [ but without termination. So it's not valid. [ considered as start of char class.

A: It's a syntax thing. { and } can exist on themselves as literal, and so does ] when it's alone. An unclosed [ however, is syntax error.


text:
Q: DB Work on Timer Tick Event and displaying result on page ever x Seconds I am working on a Timer control for my website, and the page my have up to 100 timers on it. Each timer needs to have a Tick event that POSTs to a *.cshtml page to do some DB work and retrieve some info to be displayed beneath the timer on the page.
I really didn't want to ask this question but I'm afraid I have to, I have been at this for weeks and just don't know how to go about it. I have looked up several timers on Google but haven't found anything that was of any help in this situation.
I'd really appreciate any help at all.
Thank you


text:
Q: Couchbase - bidirectional replication I'm trying to figure out if the community edition of Couchbase supports bidirectional replication btwn data centers?
I'm reading this: https://www.couchbase.com/products/editions
but I can't see any clear comments about it.
What I'm trying to test / achieve is what's described in the following documentation under the "bidirectional" section.
https://docs.couchbase.com/server/6.0/learn/clusters-and-availability/xdcr-overview.html
Thanks.

A: Bidirectional replication just means you have XDCR going from cluster A to B, and another XDCR going from cluster B to A. Since Community Edition includes XDCR, it includes bidirectional replication.


text:
Q: How do I modify web.config to not rewrite a certain url? I am running a node.js application under iisnode (an extension for IIS that allows node.js to manage requests through IIS). By default iisnode gives access to a debugging tool at http://myapp.com/debug. However Windows Azure Websites overrides this (probably by accident) with a urlrewrite in web.config.
<system.webServer>
    <handlers>
        <add name="iisnode" path="app.js" verb="*" modules="iisnode"/>
    </handlers>
    <rewrite>
        <rules>
            <rule name="StaticContent">
                <action type="Rewrite" url="public{REQUEST_URI}"/>
            </rule>
            <rule name="DynamicContent">
                <conditions>
                    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/>
                </conditions>
                <action type="Rewrite" url="app.js"/>
            </rule>
        </rules>
    </rewrite>
    <iisnode
        debuggingEnabled="true"
        devErrorsEnabled="true"
        debuggerPathSegment="debug"
        nodeProcessCommandLine=""%programfiles(x86)%\nodejs\node.exe""
        logDirectory="..\..\LogFiles\nodejs"
        watchedFiles="*.js;iisnode.yml;node_modules\*;views\*.jade;views\*.ejb;routes\*.js" />
</system.webServer>

I don't know much about web.config rewrite but it looks to me like <action type="Rewrite" url="app.js"/> is routing all requests to app.js (my main application file) as long as the request does not match an actual static file on the server. This is great except I don't want /debug to be routed to app.js, I want to let iisnode handle that request by default like it is supposed to. If I remove the <action /> rewrite /debug does indeed pull up the iisnode debugger, but then nothing else works of course :P
How can I modify this url rewrite to avoid /debug?

A: It turns out that the iisnode debugger is not available on Windows Azure Websites for technical reasons and no amount of web.config modification will cause it to work correctly.
https://github.com/tjanczuk/iisnode/issues/262


text:
Q: How do I detect when a specific item reaches top of a RecyclerView in Android? I'm creating an app with a list of questions in a RecyclerView. In the same parent layout, I have a static TextView above the RecyclerView that displays instruction for a set of questions. What I want is to change the text in the TextView whenever a specific question reaches the top of the RecyclerView when scrolled. How can I accomplish this?

A: You would need to listen to the scrolling of your RecyclerView and get the first item displayed onto the screen.
Thanksfully, Android let us set a custom ScrollListener to a RecyclerView and with your LayoutManager you are able to know which item is shown first :
// initialize your RecyclerView and your LayoutManager
mLinearLayoutManager = new LinearLayoutManager(getContext());
mRecyclerView.setLayoutManager(mLinearLayoutManager);

// set a custom ScrollListner to your RecyclerView
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
           // Get the first visible item
           int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition();

           //Now you can use this index to manipulate your TextView

        }
    });

EDIT : added Mateus Gondim clearance about the LayoutManager

A: You should override the default Recycler.OnScrollListener.
Have a look at this Code : https://gist.github.com/mipreamble/b6d4b3d65b0b4775a22e


text:
Q: How to handle multiple awaits in async function I have multiple API calls to be made which fetch via an API, write data to DB via API, send output to front end via another API.
I have written async function with await like below.
The first two should run one after another but the third one can run independently and doesn't need to wait for the first two fetch statements to complete.
let getToken= await fetch(url_for_getToken);
let getTokenData = await getToken.json();

let writeToDB = await fetch(url_for_writeToDB);
let writeToDBData = await writeToDB.json();

let frontEnd = await fetch(url_for_frontEnd);
let frontEndData = await frontEnd.json();

What is the best way to handle such multiple fetch statements ?

A: It's easier if you work with promise "creators" (= function that return promises) rather than raw promises. First, define:
const fetchJson = (url, opts) => () => fetch(url, opts).then(r => r.json())

which returns such a "creator". Now, here are two utilities for serial and parallel chaining, which accept both raw promises and "creators":
const call = f => typeof f === 'function' ? f() : f;

const parallel = (...fns)  => Promise.all(fns.map(call));

async function series(...fns) {
    let res = [];

    for (let f of fns)
        res.push(await call(f));

    return res;
}

Then, the main code can be written like this:
let [[getTokenData, writeToDBData], frontEndData] = await parallel(
    series(
        fetchJson(url_for_getToken),
        fetchJson(url_for_writeToDB),
    ),
    fetchJson(url_for_frontEnd),
)

If you don't like the dedicated "creator" wrapper, you can define fetchJson normally
const fetchJson = (url, opts) => fetch(url, opts).then(r => r.json())

and use inline continuations right where series or parallel are called:
let [[getTokenData, writeToDBData], frontEndData] = await parallel(
    series(
        () => fetchJson('getToken'),
        () => fetchJson('writeToDB'),
    ),
    () => fetchJson('frontEnd'), // continuation not necessary, but looks nicer
)

To bring the idea further, we can  make series and parallel return "creators" as well rather than promises. This way, we can build arbitrary nested "circuits" of serial and parallel promises and get the results in order. Complete working example:

const call = f => typeof f === 'function' ? f() : f;

const parallel = (...fns)  => () => Promise.all(fns.map(call));

const series = (...fns) => async () => {
    let res = [];

    for (let f of fns)
        res.push(await call(f));

    return res;
};

//

const request = (x, time) => () => new Promise(resolve => {
    console.log('start', x);
    setTimeout(() => {
        console.log('end', x)
        resolve(x)
    }, time)
});

async function main() {
    let chain = series(
        parallel(
            series(
                request('A1', 500),
                request('A2', 200),
            ),
            series(
                request('B1', 900),
                request('B2', 400),
                request('B3', 400),
            ),
        ),
        parallel(
            request('C1', 800),
            series(
                request('C2', 100),
                request('C3', 100),
            )
        ),
    );

    let results = await chain();

    console.log(JSON.stringify(results))
}

main()
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: There are many ways but the most universal is to wrap each async code path in an async function. This gives you flexibility of mix & matching async return values as you please. In your example you can even inline code with async iife's:
await Promise.all([
  (async() => {
    let getToken = await fetch(url_for_getToken);
    let getTokenData = await getToken.json();

    let writeToDB = await fetch(url_for_writeToDB);
    let writeToDBData = await writeToDB.json();
  })(),
  (async() => {
    let frontEnd = await fetch(url_for_frontEnd);
    let frontEndData = await frontEnd.json();
  })()
]);

A: You can use .then(), rather than await:
fetch(url_for_getToken)
  .then(getToken => getToken.json())
  .then(async getTokenData => {
    let writeToDB = await fetch(url_for_writeToDB);
    let writeToDBData = await writeToDB.json();
    // Carry on
  })

fetch(url_for_frontEnd)
  .then(frontEnd => frontEnd.json())
  .then(frontEndData => {
    // Carry on
  })

A: Run independent request (writeToDB) at the beginning and without await

let writeToDB = fetch(url_for_writeToDB);

let getToken = await fetch(url_for_getToken);
let getTokenData = await getToken.json();

// ...


text:
Q: Cocoa Swift - Pass data from two ViewControllers I am using protocols and delegates to pass data from one viewController to another, but when I click send it only changes the viewController but does not pass the data.
Anyone know how to return data from ViewController B to ViewController A?
It compiles and works fine, but nothing is logged, so I don't know if it works.
//  FirstViewController.swift

import Cocoa

class FirstViewController: NSViewController, DataEnteredDelegate {

    @IBOutlet weak var buttonPasswordState: NSView!

    @IBOutlet weak var label: NSTextField!

    override func viewDidLoad() {
        super.viewDidLoad()

   }

@IBAction func buttonPasswordState(_ sender: Any) {

        if let controller = self.storyboard?.instantiateController(withIdentifier: "SecondViewController") as? SecondViewController {
        self.view.window?.contentViewController = controller
        }

    }

    func userDidEnterInformation(info: String) {
            label.stringValue = info
        }

}

//  SecondViewController.swift

import Cocoa

class SecondViewController: NSViewController {

    @IBOutlet weak var buttonContinue: NSButton!

    weak var delegate: DataEnteredDelegate? = nil

    @IBOutlet weak var textField: NSTextField!

    override func viewDidLoad() {
        super.viewDidLoad()

    }

@IBAction func buttonContinue(_ sender: Any) {

        if let controller = self.storyboard?.instantiateController(withIdentifier: "FirstViewController") as? FirstViewController {
        self.view.window?.contentViewController = controller

            delegate?.userDidEnterInformation(info: textField.stringValue)
        }

    }

}

protocol DataEnteredDelegate: class {
    func userDidEnterInformation(info: String)
}

A: You're creating a brand new instance of SecondViewController here, that's not configured or changed before you show it:
    if let controller = self.storyboard?.instantiateController(withIdentifier: "SecondViewController") as? SecondViewController {
    // TODO something like controller.configureWith(dataFromFirstVC)... e.g. controller.delegate = self
    self.view.window?.contentViewController = controller
    }

and when you want to go back to your FirstViewController, again you new up a brand new instance of FirstViewController, you're not calling back to the same instance - that is your delegate:
    if let controller = self.storyboard?.instantiateController(withIdentifier: "FirstViewController") as? FirstViewController {
    self.view.window?.contentViewController = controller
        // controller is not the same object as delegate

        delegate?.userDidEnterInformation(info: textField.stringValue)
    }

A: I think this will help you.
class FirstViewController: UIViewController, DataPassProtocol {

    override func viewDidLoad() {
        super.viewDidLoad()

        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
            self.fireSecondViewController()
        }

    }

    func fireSecondViewController() {
        let secondViewController = SecondViewController()
        secondViewController.delegateFirstViewController = self
    }

    // MARK: - protocol methods
    func dataCaptured(with value: SampleData) {
        // we captured data from secondViewController
        print("data : \(value.temp)")
    }
}

class SecondViewController: UIViewController {

    weak var delegateFirstViewController: DataPassProtocol?

    override func viewDidLoad() {
        super.viewDidLoad()

        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
            self.sendSomeDataToFirstViewController()
        }

    }

    func sendSomeDataToFirstViewController() {
        delegateFirstViewController?.dataCaptured(with: SampleData(temp: "Tadaaaaaaa"))
    }
}

struct SampleData {
    let temp: String
}

protocol DataPassProtocol: AnyObject {
    func dataCaptured(with value: SampleData)
}


text:
Q: How can I have shared scope and pass data in angular directive In the angular directive I have this
app.directive('myDir', function () {
  return {
    restrict: 'E',
    scope: true,
    template:'
{{myindex}}
',
    link: function(scope, element, attrs){
      console.log('test', scope.myindex)
    },
   controller: 'myDirController'
  };
})

I use like this
<my-dir> </my-dir>
Now as I want to use it in different templates, I have one function which I want to call like this
// this is inside myDirController
test: function($scope){
          $scope.myFunction();
        }

Now basically I want to call  $scope.myFunction();
This works fine if I have  $scope.myFunction(); defined in parent controller.
Buy it's not reusable as in my other controller I want to call  $scope.myFunction2();.
So I want something so that I can pass the function name in directive
<my-dir fname="myFunction"> </my-dir>
and that gets called in my directive
The thing is I can't use isolated scope as I need to have access to parent $scope

A:
i want to call  $scope.myFunction();
[my directive is] not reusable as in my other controller i want to call  $scope.myFunction2();
SO i want something so that i can pass the function name in directive:
<my-dir fname="myFunction"> </my-dir>

1) The attributes in your custom tag are available in the link function, so you can save the value of the fname attribute for future use:
link: function(scope, element, attrs){
  scope.data = {fname: attrs.fname};
},

2) An object's properties can be retrieved using dot notation, e.g. $scope.fname, but the properties can also be retrieved using array notation, e.g. $scope[fname], where fname is a string. And if $scope[fname] is a function, you can execute it by writing $scope[fname]():
app.controller('MyDirCtrl', function($scope) {
  $scope.test = function() {
    var fname = $scope.data.fname;
    $scope[fname]();  //fname property not found in current scope, so parent scope is searched
  };
});

....

    <my-dir fname="funcInCtrl1"></my-dir>

    <my-dir fname="funcInCtrl2"></my-dir>

...
var app = angular.module('myApp',[]);

app.controller('Ctrl1', ['$scope', function($scope) {
  $scope.funcInCtrl1 = function() {
    console.log('funcInCtrl1 called...');
  };
}]);

app.controller('Ctrl2', ['$scope', function($scope) {
  $scope.funcInCtrl2 = function() {
    console.log('funcInCtrl2 called...');
  };
}]);

app.controller('MyDirCtrl', ['$scope', function($scope) {
  $scope.test = function() {
    var fname = $scope.data.fname;
    $scope[fname]();
  };
}]);

app.directive('myDir', function () {
  return {
    restrict: 'E',
    scope: true,
    template:'
click me
',

    link: function(scope, element, attrs){
      scope.data = {fname: attrs.fname};
    },

    controller: 'MyDirCtrl',
  }
})

And, here it is with Controller as syntax:

    <my-dir fname="ctrl1.funcInCtrl1"></my-dir>

    <my-dir fname="ctrl2.funcInCtrl2"></my-dir>

...
var app = angular.module('myApp',[]);

app.controller('Ctrl1', function() {
  this.funcInCtrl1 = function() {
    console.log('funcInCtrl1 called...');
  };
});

app.controller('Ctrl2', function() {
  this.funcInCtrl2 = function() {
    console.log('funcInCtrl2 called...');
  };
});

app.controller('MyDirCtrl', ['$scope', function($scope) {
  this.test = function() {
    var fnames = $scope.data.fname.split('.');
    var ctrl_name = fnames[0];
    var func_name = fnames[1];
    $scope[ctrl_name][func_name]();
  };
}]);

app.directive('myDir', function () {
  return {
    restrict: 'E',
    scope: true,
    template:'
click me
',

    link: function(scope, element, attrs){
      scope.data = {fname: attrs.fname};
    },

    controller: 'MyDirCtrl',
    controllerAs: 'mydirCtrl'
  }
})

A: You could use a factory and create different directives with this factory that use your specific function.
module.service('DirectiveFactory', function() {
  this.create = function(fn) {
    return {
      restrict: 'E',
      scope: true,
      template:'
{{myindex}}
',
      link: function(scope, element, attrs){
        console.log('test', scope.myindex)
      },
     controller: function($scope) {
       // your specific function
       fn();
     }
    };
  };
});

module.directive('my-dir-1', function(DirectiveFactory) {
  function fn1() {
    console.log('my special function call1');
  }
  return DirectiveFactory.create(fn1);
});

module.directive('my-dir-2', function(DirectiveFactory) {
  function fn1() {
    console.log('my special function call2');
  }
  return DirectiveFactory.create(fn2);
});

In your template you'd use:
<my-dir-1></my-dir1>

<my-dir-2></my-dir2>


text:
Q: Maths in stretched cells Here is a minimal working example of my table :
\documentclass[10pt,a4paper]{article}
\usepackage{color}
\usepackage{amsmath}
\usepackage{colortbl}
\usepackage{array}

\definecolor{myblue}{rgb}{0.866,0.894,0.996}

\newcolumntype{B}[1]{>{\centering\arraybackslash\columncolor{myblue}}p{#1}}

\renewcommand{\arraystretch}{2}

\begin{document}

\begin{table}[!htb]
\begin{tabular}{ B{0.2\textwidth} | B{0.2\textwidth} }
title column 1 & title column 2 \\ \hline
content & content with binomial coefficient $\begin{pmatrix} n \\ k \end{pmatrix}$ \\
\end{tabular}
\end{table}

\end{document}

I have used \arraystretch to increase the height of the rows of my table. The problem is that, when I write a binomial coefficient in a cell using \begin{pmatrix}...\end{pmatrix}, the parenthesis are too large. The command \arraystretch seems to affect the environment pmatrix. How can I keep the row height and have a binomial coefficient which looks nice ?
Moreover, \arraystretch modifies the space between and after the text in all the cells. How can I modifiy this space locally, for one given row ?

A:
\documentclass[10pt,a4paper]{article}
\usepackage{color}
\usepackage{amsmath}
\usepackage{colortbl}
\usepackage{array}
\definecolor{myblue}{rgb}{0.866,0.894,0.996}
\newcolumntype{B}[1]{>{\centering\arraybackslash\columncolor{myblue}}p{#1}}
\setlength{\extrarowheight}{50pt}

\begin{document}
\begin{table}[!htb]
\begin{tabular}{ B{0.2\textwidth} | B{0.2\textwidth} }
title column 1 & title column 2 \\[50pt] \hline
content & content with binomial coefficient  {\setlength{\extrarowheight}{0pt} $\begin{pmatrix} n \\ k \end{pmatrix}$} \\ [50pt]
\end{tabular}
\end{table}
\end{document}

Since you need the distance above the \hline to be equal to that below it, you should add \setlength{\extrarowheight}{50pt} to control the distance above and add \\ [50pt] with the same value 50pt to control the distance below.
To cancel the effect within a math array, just issue the command \setlength{\extrarowheight}{0pt} to neutralize the previous setting. Alternatively, you can apply @Zacro's advice and use \binom{n}{k} instead of \begin{pmatrix} n\\k \end{pmatrix}. The latter does not get affected by \extrarowheight.

A: You can normalize the factor inside the table cells:
\newcolumntype{B}[1]{>{%
\renewcommand{\arraystretch}{1}%
\centering\arraybackslash\columncolor{myblue}}p{#1}}

so that the value of 2 is only used at the outer level.

Moreover, \arraystretch modifies the space between and after the text in all > the cells. How can I modifiy this space locally, for one given row ?

if you just want to change one row, do not change \arraystretch anywhere, leave it as 1, and just use \\[5cm] to have extra space after the spacial row.


text:
Q: How to take the data? I am learning to use neural networks, and have encountered a problem.
I can not figure out how to convert data for a neural network.
As I understand it, I need to normalize the data, after normalization and learning, the answer is always averaged.
https://jsfiddle.net/eoy7krzj/
<html>
<head>
    <script src="https://cdn.rawgit.com/BrainJS/brain.js/5797b875/browser.js"></script>

</head>
<body>

<div>
    <button onclick="train()">train</button><button onclick="Generate.next(); Generate.draw();">generate</button><button onclick="calculate()">calculate</button>
</div>

<canvas id="generate" style="border: 1px solid #000"></canvas>

</body>

<script type="text/javascript">
    var trainData = [];

    function randomInteger(min, max) {
        var rand = min - 0.5 + Math.random() * (max - min + 1)
        //rand = Math.round(rand);
        return rand;
    }

    function getRandomColor() {
        var letters = '0123456789ABCDEF';

        var color = '#';

        for (var i = 0; i < 6; i++) {
            color += letters[Math.floor(Math.random() * 16)];
        }

        return color;
    }

    var Generate   = new function(){
        var canvas = document.getElementById('generate');
        var ctx    = canvas.getContext('2d');
        var elem   = {
            input: [],
            output: []
        }

        var size = {
            width: 240,
            height: 140
        }

        canvas.width  = 500;
        canvas.height = 250;

        this.next = function(){
            this.build();

            trainData.push({
                input: elem.input,
                output: elem.output
            });
        }

        this.clear = function(){
            ctx.clearRect(0, 0, canvas.width, canvas.height);
        }

        this.draw = function(){
            this.clear();

            this.item(elem.input, function(item){
                ctx.strokeStyle = "green";

                ctx.strokeRect(item[0], item[1], item[2], item[3]);
            })

            this.item(elem.output, function(item){
                ctx.strokeStyle = "blue";

                ctx.strokeRect(item[0], item[1], item[2], item[3]);
            })

        }

        this.item = function(where, call){
            for (var i = 0; i < where.length; i+=4) {
                var input = [
                    where[i],
                    where[i+1],
                    where[i+2],
                    where[i+3],
                ];

                this.denormalize(input);

                call(input)
            }
        }

        this.normalize = function(input){
            input[0] = input[0] / 500;
            input[1] = input[1] / 250;
            input[2] = input[2] / 500;
            input[3] = input[3] / 250;
        }

        this.denormalize = function(input){
            input[0] = input[0] * 500;
            input[1] = input[1] * 250;
            input[2] = input[2] * 500;
            input[3] = input[3] * 250;
        }

        this.empty = function(add){
            var data = [];

            for (var i = 0; i < add; i++) {
                data = data.concat([0,0,0,0]);
            }

            return data;
        }

        this.build = function(){
            var output  = [];
            var input   = [];

            size.width  = randomInteger(100,500);
            size.height = randomInteger(50,250);

            var lines       = 1;//Math.round(size.height / 100);
            var line_size   = 0;
            var line_offset = 0;

            for(var i = 0; i < lines; i++){
                line_size = randomInteger(30,Math.round(size.height / lines));

                var columns        = Math.round(randomInteger(1,3));
                var columns_width  = 0;
                var columns_offset = 0;

                for(var c = 0; c < columns; c++){
                    columns_width = randomInteger(30,Math.round(size.width / columns));

                    var item = [
                        columns_offset + 10,
                        line_offset + 10,
                        columns_width - 20,
                        line_size - 20
                    ];

                    this.normalize(item);

                    input = input.concat(item);

                    columns_offset += columns_width;
                }

                var box = [
                    0,
                    line_offset,
                    columns_offset,
                    line_size
                ]

                this.normalize(box);

                output = output.concat(box);

                line_offset += line_size + 10;
            }

            elem.input  = input.concat(this.empty(5 - Math.round(input.length / 4)));
            elem.output = output.concat(this.empty(2 - Math.round(output.length / 4)));
        }

        this.get = function(){
            return elem.input;
        }

        this.calculate = function(result, stat){
            console.log('brain:',result);

            this.item(result, function(item){
                ctx.strokeStyle = "red";

                ctx.strokeRect(item[0], item[1], item[2], item[3]);
            })
        }

        this.train = function(){
            for(var i = 0; i < 40; i++){
                this.next();
            }
        }
    }

    Generate.train();

    Generate.log = true;

    var net,stat;

    function train(){
        net  = new brain.NeuralNetwork({ hiddenLayers: [8,4]});
        stat = net.train(trainData,{log: true, iterations: 250,learningRate: 0.01,errorThresh:0.05});

        console.log('stat:',stat)
    }

    function calculate(){
        Generate.calculate(net.run(Generate.get()))
    }

</script>
</html>

My goal is to train the network to find the elements and show their sizes.
Procedure:
Click to train
Click generate
Click to calculate
As a result, the network shows average results and red indicates that the network has found.
Maybe not so I transfer the data, can on another it is necessary?


text:
Q: Fixed highlighting in tmux I miss highlighting (reverse mode) on console since I started to use urxvt + tmux as main terminal. The highlights was replaced with with italic font - what looks pretty cool at first - however I can't find the one italic word in thousands non-italic when I try to search something in a less.
This is works properly while the terminal type is set to an xterm* profile (with e.g. set -g default-terminal "xterm-color" in .tmux.conf). However some shortcut can't works, apps can't get proper geometry of terminal, ... in this case.

A: I run urxvt in arch linux. The op's answer did not help me. This helped me:
https://github.com/tmux/tmux/blob/2.1/FAQ#L355-L383

search for italic and run that; then, put this in tmux config
set -g default-terminal "tmux"

don't use "tmux-256color". (try it, I suppose, but it didn't work for me.)

finally, add this to your rc (.zshrc, .bashrc, etc):
export TERM="xterm-256color"

A: Quicker way:
set -g terminal-overrides "screen.xterm-new"

Works without any further magic (and still heeds the warning in the tmux manual about the terminal type needing to be "screen" or a derivative thereof).

A: I have found info and solutions about it on tmux's pages:

*

*tmux's mailing list

*tmux's FAQ

Screen's terminfo description lacks italics mode and has standout mode in its place, but using the same escape sequence that urxvt uses for italics. This means applications (like vim) looking for italics will not find it and might turn to reverse in its place, while applications (like less) asking for standout will end up with italics instead of reverse.

[Fix 1] Replace terminfo entries and get reverse + italics
(per user!)

To make applications aware that tmux supports italics and to use a proper escape sequence for standout, you'll need to create a new terminfo file with modified sgr, smso, rmso, sitm and ritm entries:
$ mkdir $HOME/.terminfo/
$ screen_terminfo="screen"
$ infocmp "$screen_terminfo" | sed \
  -e 's/^screen[^|]*|[^,]*,/screen-it|screen with italics support,/' \
  -e 's/%?%p1%t;3%/%?%p1%t;7%/' \
  -e 's/smso=[^,]*,/smso=\\E[7m,/' \
  -e 's/rmso=[^,]*,/rmso=\\E[27m,/' \
  -e '$s/$/ sitm=\\E[3m, ritm=\\E[23m,/' > /tmp/screen.terminfo
$ tic /tmp/screen.terminfo

And tell tmux to use it in ~/.tmux.conf:
set -g default-terminal "screen-it"

If your terminal supports 256 colors, use:
$ screen_terminfo="screen-256color"

instead of "screen". See the FAQ entry about 256 colors support for more info. Also note that tmux will still display reverse video on terminals that do not support italics.
If your urxvt cannot display italics at all, make sure you have an italics capable font enabled, for example, add to ~/.Xdefaults:
urxvt.italicFont: xft:Bitstream Vera Sans Mono:italic:autohint=true

[Fix 2] Simply replace italic control characters with reverse
Add this terminal override to ~/.tmux.conf:
set -g terminal-overrides 'rxvt-unicode*:sitm@,ritm@'


text:
Q: JiBX Validation against a XSD Schema when unmarshalling to POJO I cant find any examples on the web explaining how to validate XML against an existing XSD schema during the unmarshalling phase.
Currently I have which works fine:
IBindingFactory bfact = BindingDirectory
    .getFactory(aClass.class);
IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
    return (aClass) uctx.unmarshalDocument(new FileInputStream(
          fname), null);
} catch (FileNotFoundException e) {
     throw new IOException(e);
    } catch (JiBXException e) {
     throw new IOException(e);
}

But where in this process can I tell Jibx to validate the XML against the schema before unmarshalling to the object?? Is it even possible with JiBX? I see examples using JaxB but none with JibX.

A: JiBX does not support full-validation from scratch.
You have to create a javax.xml.stream.XMLInputFactory with an implementation which supports validation (such as the one supplied by Sun as part of their JDKs), then call setProperty(XMLInputFactory.IS_VALIDATING, Boolean.TRUE) and create an actual parser with a createXMLStreamReader() call.
Once you have the validating parser for your input, you can use the org.jibx.runtime.impl.StAXReaderWrapper constructor to wrap this as an IXMLReader instance, which can then be set on your org.jibx.runtime.impl.UnmarshallingContext unmarshalling context instance.
Weird, I known, you can find a request for making it easier here JIBX-381


text:
Q: how to tell if my stdin is coming from stdout or stderr of the piped-in process How to tell from Linux process2 whether I am given standard output or error from the previous process.  Is it possible, to tell inside process2, whether particular line comes from stderr or stout
bash>process1 2>&1 | process2

So I guess by John's answer, it is "no".  Then I am guessing, one way to handle this, is to inject specific prefixes for each line inside process1:
1: <line>

for stdout
2: <line>

for stderr
then I can inspect them in process2.  Is this the normal thing to do?

A: No, it is not possible.  You can differentiate stdin from a terminal by isatty() but not what sort of stream the input came from in the way you want.


text:
Q: Windows Mobile: exception in Finalizer terminates program My Windows mobile application crashes sometimes with an exception that happens in the finalizer of System.Net.HttpReadStream.
It only happens sometimes, but then it brings down the whole program. Is there anything I can do to make the program continue when such an internal finalizer throws? Or alternatively, how can I prevent such an error?
Here's the stacktrace of the exception (not complete, since I have to type the whole thing...
ObjectDisposedException

at System.Threading.Timer.throwIfDisposed()
at System.Threading.Timer.Change(UInt32 dueTime, UInt32 period)
at ...
at System.Net.ContentLengthReadStream.doClose()
at System.Net.HttpReadStream.Finalize()

The calling code is:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(actionUrl);
request.AllowAutoRedirect = true;
request.AllowWriteStreamBuffering = true;
request.Method = "POST";
request.ContentType = "application/json";

using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
    JsonSerializer serializer = new JsonSerializer();
    serializer.Serialize(writer, myRequestObject);
}

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
    {
        JsonSerializer serializer = new JsonSerializer();
        MyResultObject result = (MyResultObject)serializer.Deserialize(reader, typeof(MyResultObject));

        return result;
    }
}

Update

The calling code above is fine. The problem was caused by another HttpWebRequest where the response was not disposed. So remember, always dispose the response object, but especially in Compact Framework since it can bring down your whole application!

A: This thread describes a similar problem.
The problem could be that you are returning inside the second using block. This way the response object won't get closed.

A: It won't hurt to close (Dipsose) the ResponseStream explicitly, as in:
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream respStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(respStream))
{
  JsonSerializer serializer = new JsonSerializer();
  MyResultObject result =
    (MyResultObject)serializer.Deserialize(reader, typeof(MyResultObject));

  return result;
}

Otherwise it is up to the Reader object to close it's stream, a bit flaky.

A: It turned out that it was another HttpWebRequest causing this. The code in my question was fine, but the dispose of the response was missing in the other place.


text:
Q: Make double-clicking the middle button do something special I want to make double-clicking the middle button to behave as ctrl+w so that I can close a tab/window with it. How can I do that? I can't find any one trying the same.
My operating system is Windows 10.

A: Using AutoHotkey, this will send Ctrl + W if the middle mouse button is pressed in quick succession:
ex. close_window.ahk
~MButton::
    If(A_TimeSincePriorHotkey<400) and (A_PriorHotkey="~MButton")
        Send ^w
Return

AutoHotkey References
List of Keys
Send


text:
Q: Get more facebook comments using Skybrud I'm developing an app which connects to a specific public page on facebook and search for the comments in a specific post, we have to look all the posts in order to find specific hashtags but there's one post with 4000+ comments, facebook throws this exception:
'StackTrace: Skybrud.Social.Facebook.Exceptions.FacebookException: Please reduce the amount of data you're asking for, then retry your request
   at Skybrud.Social.Facebook.Responses.FacebookResponse.ValidateResponse(SocialHttpResponse response, JsonObject obj)
   at Skybrud.Social.Facebook.Responses.Comments.FacebookCommentsResponse.ParseResponse(SocialHttpResponse response)
   at Skybrud.Social.Facebook.Endpoints.FacebookCommentsEndpoint.GetComments(String id, FacebookCommentsOptions options)'

As you can see I'm using Skybrud, I limited the comments to 800 and it works, but there are more comments and I don't know how to retrieve the other pages of comments, any ideas?.
Thanks for your time.

A: Maybe this could help someone else, use the two members from the FacebookCommentsOptions: Before and After, the response from Facebook will include this in the Paging section. Then call again the GetCommets method.


text:
Q: Phrase like "margin of error" or "buffer" but specifically about spare team capacity? I am trying to think of a phrase that means something like "margin of error" or "buffer," but specifically applying to spare capacity of a working team within a company. "Bench" sort of works for sports people, but it's not ideal because a bench is for players who can substitute in for other players, and I want to evoke the idea of additional workers waiting in the wings who can step in to accommodate a surge in demand.
I'm wanting to say something like

We are operating with razor-thin _______"

... fill in the blank? And "margins" doesn't work because that sounds like it's about profitability. Any ideas?


text:
Q: How do I structure Cloud Functions for Firebase to deploy multiple functions from multiple files? I would like to create multiple Cloud Functions for Firebase and deploy them all at the same time from one project. I would also like to separate each function into a separate file. Currently I can create multiple functions if I put them both in index.js such as:
exports.foo = functions.database.ref('/foo').onWrite(event => {
    ...
});

exports.bar = functions.database.ref('/bar').onWrite(event => {
    ...
});

However I would like to put foo and bar in separate files. I tried this:
/functions
|--index.js (blank)
|--foo.js
|--bar.js
|--package.json

where foo.js is
exports.foo = functions.database.ref('/foo').onWrite(event => {
    ...
});

and bar.js is
exports.bar = functions.database.ref('/bar').onWrite(event => {
    ...
});

Is there a way to accomplish this without putting all functions in index.js?

A: The answer by @jasonsirota was very helpful. But it may be useful to see more detailed code, especially in the case of HTTP triggered functions.
Using the same structure as in @jasonsirota's answer, lets say you wish to have two separate HTTP trigger functions in two different files:
directory structure:
    /functions
       |--index.js
       |--foo.js
       |--bar.js
       |--package.json

index.js:
'use strict';
const fooFunction = require('./foo');
const barFunction = require('./bar');

// Note do below initialization tasks in index.js and
// NOT in child functions:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const database = admin.database();

// Pass database to child functions so they have access to it
exports.fooFunction = functions.https.onRequest((req, res) => {
    fooFunction.handler(req, res, database);
});
exports.barFunction = functions.https.onRequest((req, res) => {
    barFunction.handler(req, res, database);
});

foo.js:
 exports.handler = function(req, res, database) {
      // Use database to declare databaseRefs:
      usersRef = database.ref('users');
          ...
      res.send('foo ran successfully');
   }

bar.js:
exports.handler = function(req, res, database) {
  // Use database to declare databaseRefs:
  usersRef = database.ref('users');
      ...
  res.send('bar ran successfully');
}

A: To be kept simple (but does the work), I have personally structured my code like this.
Layout
├── /src/
│   ├── index.ts
│   ├── foo.ts
│   ├── bar.ts
└── package.json

foo.ts
export const fooFunction = functions.database()......... {
    //do your function.
}

export const someOtherFunction = functions.database().......... {
    // do the thing.
}

bar.ts
export const barFunction = functions.database()......... {
    //do your function.
}

export const anotherFunction = functions.database().......... {
    // do the thing.
}

index.ts
import * as fooFunctions from './foo';
import * as barFunctions from './bar';

module.exports = {
    ...fooFunctions,
    ...barFunctions,
};

Works for directories of any nested levels. Just follow the pattern inside the directories too.

A: The Firebase docs have now been updated with a good guide to multi-file code organization:
Docs > Cloud Functions > Write functions > Organize functions
To summarize:
foo.js
const functions = require('firebase-functions');
exports.foo = functions.https.onRequest((request, response) => {
  // ...
});

bar.js
const functions = require('firebase-functions');
exports.bar = functions.https.onRequest((request, response) => {
  // ...
});

index.js
const foo = require('./foo');
const bar = require('./bar');
exports.foo = foo.foo;
exports.bar = bar.bar;

A: Update: Typescript is now fully supported so no need for the shenanigans below. Just use the firebase cli

Here is how I personnally did it with typescript:
/functions
   |--src
      |--index.ts
      |--http-functions.ts
      |--main.js
      |--db.ts
   |--package.json
   |--tsconfig.json

Let me preface this by giving two warnings to make this work:

*the order of import / export matters in index.ts

*the db must be a separate file

For point number 2 I'm not sure why. Secundo you should respect my configuration of index, main and db exactly (at least to try it out).
index.ts : deals with export. I find it cleaner to let the index.ts deal with exports.
// main must be before functions
export * from './main';
export * from "./http-functions";

main.ts: Deals with initialization.
import { config } from 'firebase-functions';
import { initializeApp } from 'firebase-admin';

initializeApp(config().firebase);
export * from "firebase-functions";

db.ts: just reexporting the db so its name is shorter than database()
import { database } from "firebase-admin";

export const db = database();

http-functions.ts
// db must be imported like this
import { db } from './db';
// you can now import everything from index.
import { https } from './index';
// or (both work)
// import { https } from 'firebase-functions';

export let newComment = https.onRequest(createComment);

export async function createComment(req: any, res: any){
    db.ref('comments').push(req.body.comment);
    res.send(req.body.comment);
}

A: This format allows your entry-point to find additional function files, and export each function within each file, automatically.
Main Entry Point Script
Finds all .js files inside of the functions folder, and exports each function exported from each file.

const fs = require('fs');
const path = require('path');

// Folder where all your individual Cloud Functions files are located.
const FUNCTIONS_FOLDER = './scFunctions';

fs.readdirSync(path.resolve(__dirname, FUNCTIONS_FOLDER)).forEach(file => { // list files in the folder.
  if(file.endsWith('.js')) {
    const fileBaseName = file.slice(0, -3); // Remove the '.js' extension
    const thisFunction = require(`${FUNCTIONS_FOLDER}/${fileBaseName}`);
    for(var i in thisFunction) {
        exports[i] = thisFunction[i];
    }
  }
});

Example Export of Multiple Functions from One File

const functions = require('firebase-functions');

const query = functions.https.onRequest((req, res) => {
    let query = req.query.q;

    res.send({
        "You Searched For": query
    });
});

const searchTest = functions.https.onRequest((req, res) => {
    res.send({
        "searchTest": "Hi There!"
    });
});

module.exports = {
    query,
    searchTest
}

http accessible endpoints are appropriately named

✔ functions: query: http://localhost:5001/PROJECT-NAME/us-central1/query
✔ functions: helloWorlds: http://localhost:5001/PROJECT-NAME/us-central1/helloWorlds
✔ functions: searchTest: http://localhost:5001/PROJECT-NAME/us-central1/searchTest

One file
If you only have a few additional files (e.g. just one), you can use:

const your_functions = require('./path_to_your_functions');

for (var i in your_functions) {
  exports[i] = your_functions[i];
}

A: So I have this project which has background functions and http functions. I also have tests for unit testing. CI/CD will make your life much easier when deploying cloud functions
Folder structure
|-- package.json
|-- cloudbuild.yaml
|-- functions
    |-- index.js
    |-- background
    |   |-- onCreate
    |       |-- index.js
            |-- create.js
    |
    |-- http
    |   |-- stripe
    |       |-- index.js
    |       |-- payment.js
    |-- utils
        |-- firebaseHelpers.js
    |-- test
        |-- ...
    |-- package.json

Note: utils/ folder is for share code between functions
functions/index.js
Here you can just import all the functions you need and declare them. No need to have logic here. It makes it cleaner in my opinion.
require('module-alias/register');
const functions = require('firebase-functions');

const onCreate = require('@background/onCreate');
const onDelete = require('@background/onDelete');
const onUpdate = require('@background/onUpdate');

const tours  = require('@http/tours');
const stripe = require('@http/stripe');

const docPath = 'tours/{tourId}';

module.exports.onCreate = functions.firestore.document(docPath).onCreate(onCreate);
module.exports.onDelete = functions.firestore.document(docPath).onDelete(onDelete);
module.exports.onUpdate = functions.firestore.document(docPath).onUpdate(onUpdate);

module.exports.tours  = functions.https.onRequest(tours);
module.exports.stripe = functions.https.onRequest(stripe);

CI/CD
How about having continuos integration and deployment every time you push your changes to the repo? You can have it by using google google cloud build. It's free until certain point :) Check this link.
./cloudbuild.yaml
steps:
  - name: "gcr.io/cloud-builders/npm"
    args: ["run", "install:functions"]
  - name: "gcr.io/cloud-builders/npm"
    args: ["test"]
  - name: "gcr.io/${PROJECT_ID}/firebase"
    args:
      [
        "deploy",
        "--only",
        "functions",
        "-P",
        "${PROJECT_ID}",
        "--token",
        "${_FIREBASE_TOKEN}"
      ]

substitutions:
    _FIREBASE_TOKEN: nothing

A: With Node 8 LTS now available with Cloud/Firebase Functions you can do the following with spread operators:
/package.json
"engines": {
  "node": "8"
},

/index.js
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();

module.exports = {
  ...require("./lib/foo.js"),
  // ...require("./lib/bar.js") // add as many as you like
};

/lib/foo.js
const functions = require("firebase-functions");
const admin = require("firebase-admin");

exports.fooHandler = functions.database
  .ref("/food/{id}")
  .onCreate((snap, context) => {
    let id = context.params["id"];

    return admin
      .database()
      .ref(`/bar/${id}`)
      .set(true);
  });

A: There is a pretty good way to organize all of your cloud functions for the long term. I did this recently and it is working flawlessly.
What I did was organize each cloud function in separate folders based on their trigger endpoint. Every cloud function filename ends with *.f.js. For example, if you had onCreate and onUpdate triggers on user/{userId}/document/{documentId} then create two files onCreate.f.js and onUpdate.f.js in directory functions/user/document/ and your function will be named userDocumentOnCreate and userDocumentOnUpdate respectively. (1)
Here is a sample directory stucture:
functions/
|----package.json
|----index.js
/----user/
|-------onCreate.f.js
|-------onWrite.f.js
/-------document/
|------------onCreate.f.js
|------------onUpdate.f.js
/----books/
|-------onCreate.f.js
|-------onUpdate.f.js
|-------onDelete.f.js

Sample Function
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const db = admin.database();
const documentsOnCreate = functions.database
    .ref('user/{userId}/document/{documentId}')
    .onCreate((snap, context) => {
        // your code goes here
    });
exports = module.exports = documentsOnCreate;

Index.js
const glob = require("glob");
const camelCase = require('camelcase');
const admin = require('firebase-admin');
const serviceAccount = require('./path/to/ServiceAccountKey.json');
try {
    admin.initializeApp({ credential: admin.credential.cert(serviceAccount),
    databaseURL: "Your database URL" });
} catch (e) {
    console.log(e);
}

const files = glob.sync('./**/*.f.js', { cwd: __dirname });
for (let f = 0, fl = files.length; f < fl; f++) {
    const file = files[f];
    const functionName = camelCase(file.slice(0, -5).split('/'));
    if (!process.env.FUNCTION_NAME || process.env.FUNCTION_NAME === functionName) {
        exports[functionName] = require(file);
      }
}

(1): You can use any name you want. To me, onCreate.f.js, onUpdate.f.js etc. seem more relevant to the kind of trigger they are.

A: Here's a simple answer if you're creating cloud functions with typescript.
/functions
|--index.ts
|--foo.ts

Near all your regular imports at the top just export all the functions from foo.ts.
export * from './foo';

A: I am also in the jouney of finding the best folder structure for Cloud Functions, so I decided to share what I've come up with:
+  /src
|    - index.ts
|    + /events
|    |    - moduleA_events.ts
|    |    - moduleB_events.ts
|    + /service
|    |    - moduleA_services.ts
|    |    - moduleB_services.ts
|    + /model
|    |    - objectA.ts
|    |    - objectB.ts
|    |    - objectC.ts

*

*/src/index.ts this file works as the entry point for all events (functions) available in your app, such as database events, https requests, scheduled functions. However, functions are not directly declared in index.js, but in the events folder indead. Code sample:
exports.user = require("./events/userEvents")
exports.order = require("./events/orderEvents")
exports.product = require("./events/productEvents")
Note: according to GCF official documentation, this approach will automatically rename all your functions to the "module-function" pattern. Example: if you have "userCreated" function inside userEvents.ts, firebase will rename this function to "user-userCreated"

*

*/src/events this folder should only contain cloud functions declarations and should not handle business logic directly. For the actual business, you should call custom functions from your /service folder (which maps the same modules as in the events folder). Code sample for userEvents.ts:
exports.userCreated = functions.firestore.document("/users/{documentId}").onCreate(async (snapshot) => {
userServices.sendWelcomeEmail()
}

*/src/service the actual busienss logic that will connect with other firebase services such as firestore, storage, auth. You can also import your /model layer here (typescript only).

*/src/model the interfaces used in typescript to ensure strong typed functions and objects.
As you would notice, this approach is mainly based on MVC and OOP principles. There is a lot of good debates on whether we should go with functional programming in serverless  environment instead. Since my backend background is Java & C#, the folder structure I presented here seems more natural to me, however, I would be very interested in knowing how different this folder structure would be when moving to a functional programming approach.

A: To be kept simple (but does the work), I have personally structured my code like this.
Layout
├── /src/
│   ├── index.ts
│   ├── foo.ts
│   ├── bar.ts
|   ├── db.ts
└── package.json

foo.ts
import * as functions from 'firebase-functions';
export const fooFunction = functions.database()......... {
    //do your function.
}

export const someOtherFunction = functions.database().......... {
    // do the thing.
}

bar.ts
import * as functions from 'firebase-functions';
export const barFunction = functions.database()......... {
    //do your function.
}

export const anotherFunction = functions.database().......... {
    // do the thing.
}

db.ts
import * as admin from 'firebase-admin';
import * as functions from 'firebase-functions';

export const firestore = admin.firestore();
export const realtimeDb = admin.database();

index.ts
import * as admin from 'firebase-admin';
import * as functions from 'firebase-functions';

admin.initializeApp(functions.config().firebase);
// above codes only needed if you use firebase admin

export * from './foo';
export * from './bar';

Works for directories of any nested levels. Just follow the pattern inside the directories too.

credit to @zaidfazil answer

A: bigcodenerd.org outline's a simpler architecture pattern in order to have methods separated into different files and exported in one line within the index.js file.
The architecture for the project in this sample is the following:
projectDirectory

*

*index.js

*podcast.js

*profile.js
index.js
const admin = require('firebase-admin');
const podcast = require('./podcast');
const profile = require('./profile');
admin.initializeApp();

exports.getPodcast = podcast.getPodcast();
exports.removeProfile = profile.removeProfile();

podcast.js
const functions = require('firebase-functions');

exports.getPodcast = () => functions.https.onCall(async (data, context) => {
      ...
      return { ... }
  });

The same pattern would be used for the removeProfile method in the profile file.

A: Ah, Cloud Functions for Firebase load node modules normally, so this works
structure:
/functions
|--index.js
|--foo.js
|--bar.js
|--package.json

index.js:
const functions = require('firebase-functions');
const fooModule = require('./foo');
const barModule = require('./bar');

exports.foo = functions.database.ref('/foo').onWrite(fooModule.handler);
exports.bar = functions.database.ref('/bar').onWrite(barModule.handler);

foo.js:
exports.handler = (event) => {
    ...
};

bar.js:
exports.handler = (event) => {
    ...
};

A: In case with Babel/Flow it would look like this:
Directory Layout
.
├── /build/                     # Compiled output for Node.js 6.x
├── /src/                       # Application source files
│   ├── db.js                   # Cloud SQL client for Postgres
│   ├── index.js                # Main export(s)
│   ├── someFuncA.js            # Function A
│   ├── someFuncA.test.js       # Function A unit tests
│   ├── someFuncB.js            # Function B
│   ├── someFuncB.test.js       # Function B unit tests
│   └── store.js                # Firebase Firestore client
├── .babelrc                    # Babel configuration
├── firebase.json               # Firebase configuration
└── package.json                # List of project dependencies and NPM scripts

src/index.js - Main export(s)
export * from './someFuncA.js';
export * from './someFuncB.js';

src/db.js - Cloud SQL Client for Postgres
import { Pool } from 'pg';
import { config } from 'firebase-functions';

export default new Pool({
  max: 1,
  user: '<username>',
  database: '<database>',
  password: config().db.password,
  host: `/cloudsql/${process.env.GCP_PROJECT}:<region>:<instance>`,
});

src/store.js - Firebase Firestore Client
import firebase from 'firebase-admin';
import { config } from 'firebase-functions';

firebase.initializeApp(config().firebase);

export default firebase.firestore();

src/someFuncA.js - Function A
import { https } from 'firebase-functions';
import db from './db';

export const someFuncA = https.onRequest(async (req, res) => {
  const { rows: regions } = await db.query(`
    SELECT * FROM regions WHERE country_code = $1
  `, ['US']);
  res.send(regions);
});

src/someFuncB.js - Function B
import { https } from 'firebase-functions';
import store from './store';

export const someFuncB = https.onRequest(async (req, res) => {
  const { docs: regions } = await store
    .collection('regions')
    .where('countryCode', '==', 'US')
    .get();
  res.send(regions);
});

.babelrc
{
  "presets": [["env", { "targets": { "node": "6.11" } }]],
}

firebase.json
{
  "functions": {
    "source": ".",
    "ignore": [
      "**/node_modules/**"
    ]
  }
}

package.json
{
  "name": "functions",
  "verson": "0.0.0",
  "private": true,
  "main": "build/index.js",
  "dependencies": {
    "firebase-admin": "^5.9.0",
    "firebase-functions": "^0.8.1",
    "pg": "^7.4.1"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.0",
    "babel-jest": "^22.2.2",
    "babel-preset-env": "^1.6.1",
    "jest": "^22.2.2"
  },
  "scripts": {
    "test": "jest --env=node",
    "predeploy": "rm -rf ./build && babel --out-dir ./build src",
    "deploy": "firebase deploy --only functions"
  }
}

$ yarn install                  # Install project dependencies
$ yarn test                     # Run unit tests
$ yarn deploy                   # Deploy to Firebase

A: I use a vanilla JS bootloader to auto-include all of the functions I want to use.
├── /functions
│   ├── /test/
│   │   ├── testA.js
│   │   └── testB.js
│   ├── index.js
│   └── package.json

index.js (bootloader)
/**
 * The bootloader reads all directories (single level, NOT recursively)
 * to include all known functions.
 */
const functions = require('firebase-functions');
const fs = require('fs')
const path = require('path')

fs.readdirSync(process.cwd()).forEach(location => {
  if (!location.startsWith('.')) {
    location = path.resolve(location)

    if (fs.statSync(location).isDirectory() && path.dirname(location).toLowerCase() !== 'node_modules') {
      fs.readdirSync(location).forEach(filepath => {
        filepath = path.join(location, filepath)

        if (fs.statSync(filepath).isFile() && path.extname(filepath).toLowerCase() === '.js') {
          Object.assign(exports, require(filepath))
        }
      })
    }
  }
})

This example index.js file only auto-includes directories within the root. It could be expanded to walk directories, honor .gitignore, etc. This was enough for me though.
With the index file in place, adding new functions is trivial.
/test/testA.js
const functions = require('firebase-functions');

exports.helloWorld = functions.https.onRequest((request, response) => {
 response.send("Hello from Firebase!");
});

/test/testB.js
const functions = require('firebase-functions');

exports.helloWorld2 = functions.https.onRequest((request, response) => {
 response.send("Hello again, from Firebase!");
});

npm run serve yields:
λ ~/Workspace/Ventures/Author.io/Firebase/functions/ npm run serve

> functions@ serve /Users/cbutler/Workspace/Ventures/Author.io/Firebase/functions
> firebase serve --only functions

=== Serving from '/Users/cbutler/Workspace/Ventures/Author.io/Firebase'...

i  functions: Preparing to emulate functions.
Warning: You're using Node.js v9.3.0 but Google Cloud Functions only supports v6.11.5.
✔  functions: helloWorld: http://localhost:5000/authorio-ecorventures/us-central1/helloWorld
✔  functions: helloWorld2: http://localhost:5000/authorio-ecorventures/us-central1/helloWorld2

This workflow is pretty much just "write and run", without having to modify the index.js file each time a new function/file is added/modified/removed.

A: I spent lot of time looking for the same, and there is what I think is the best way to achieve it (I'm using firebase@7.3.0):
https://codeburst.io/organizing-your-firebase-cloud-functions-67dc17b3b0da
No sweat ;)

A: The above answers pointed me to the right direction, just that none really worked for me. Below is a working prototype, an example of onCall, onRequest and a Database trigger
foo.js - onCall
exports.handler = async function(data, context, admin) {
    // const database = admin.database();
    // const firestore = admin.firestore();
    //...
};

bar.js - onRequest
exports.handler = async function(req, res, admin) {
    // const database = admin.database();
    // const firestore = admin.firestore();
    //...
};

jar.js - trigger/document/onCreate
exports.handler = async function(snapshot, context, admin) {
    // const database = admin.database();
    // const firestore = admin.firestore();
    //...
};

index.js
// import firebase admin SDK dependencies
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

// import functions
const foo = require("./foo");
const bar = require("./bar");
const jar = require("./jar");

// onCall for foo.js
exports.foo = functions.https.onCall((data, context) => {
    return foo.handler(data, context, admin);
});

// onRequest for bar.js
exports.bar = functions.https.onRequest((req, res) => {
    return bar.handler(req, res, admin);
});

// document trigger for jar.js
exports.jar = functions.firestore
  .document("parentCollection/{parentCollectionId}")
  .onCreate((snapshot, context) => {
    return jar.handler(snapshot, context, admin);
});

NOTE: You can also make a sub folder to house your individual functions

A: On my effort to implement the solution of @zaidfazil, I came up with the following (using JavaScript, not TypeScript).
multi.js
exports.onQuestionMultiCreate = functions.database
  .ref("/questions-multi/{questionId}")
  .onCreate(async (snapshot, context) => {
   ...
    }
  });

trueFalse.js
exports.onQuestionTrueFalseCreate = functions.database
  .ref("/questions-truefalse/{questionId}")
  .onCreate(async (snapshot, context) => {
   ...
    }
  });

index.js

const multi = require("./multi");
const trueFalse = require("./trueFalse");

module.exports = {
  ...multi,
  ...trueFalse


text:
Q: How to detect if an app is installed then taking actions Inside my app, I want to detect if an app like VLC is installed.
If it does, and when user clicks button, my app will proceed to play a video but if does not, the app will direct user to App store to download the app.
Is there a way to detect if an particular app is installed or not?

A: Try this:
PackageManager packageManager = getPackageManager();
List activities = packageManager.queryIntentActivities(***REPLACE_WITH_YOUR_INTENT***,
        PackageManager.MATCH_DEFAULT_ONLY);
boolean isIntentSafe = activities.size() > 0;

From the Android Docs:

Although the Android platform guarantees that certain intents will
  resolve to one of the built-in apps (such as the Phone, Email, or
  Calendar app), you should always include a verification step before
  invoking an intent.
To verify there is an activity available that can respond to the
  intent, call queryIntentActivities() to get a list of activities
  capable of handling your Intent. If the returned List is not empty,
  you can safely use the intent.
Note: You should perform this check when your activity first starts in
  case you need to disable the feature that uses the intent before the
  user attempts to use it. If you know of a specific app that can handle
  the intent, you can also provide a link for the user to download the
  app (see how to link to your product on Google Play).

So, you could use that like this:
Intent vlcIntent = new Intent(Intent.ACTION_VIEW);
vlcIntent.setPackage("org.videolan.vlc");

PackageManager packageManager = getPackageManager();
    List activities = packageManager.queryIntentActivities(vlcIntent,
            PackageManager.MATCH_DEFAULT_ONLY);
    boolean isIntentSafe = activities.size() > 0;

if (isIntentSafe){
    startActivity(vlcIntent);
} else {
    Intent marketIntent = new Intent(Intent.ACTION_VIEW);
    marketIntent.setData(Uri.parse("market://details?id=org.videolan.vlc"));
    startActivity(marketIntent);
}

Also, another link that might be useful(VideoLan Wiki):
Android Video Player Intents
It says:

For a simple media playback:
 int vlcRequestCode = 42;  Uri uri =
Uri.parse("file:///storage/emulated/0/Movies/KUNG FURY Official
Movie.mp4");  Intent vlcIntent = new Intent(Intent.ACTION_VIEW);
vlcIntent.setPackage("org.videolan.vlc");
vlcIntent.setDataAndTypeAndNormalize(uri, "video/*");
vlcIntent.putExtra("title", "Kung Fury");
vlcIntent.putExtra("from_start", false);
vlcIntent.putExtra("position", 90000l);
vlcIntent.putExtra("subtitles_location",
"/sdcard/Movies/Fifty-Fifty.srt");  startActivityForResult(vlcIntent,
vlcRequestCode);

If you specifically want to start VideoPlayerActivity, you can set
 vlcIntent.setComponent(new ComponentName("org.videolan.vlc",
 "org.videolan.vlc.gui.video.VideoPlayerActivity"));

You could also put the code into a boolean code block and pass in your intent, that way you could reuse the code. Like this:
private boolean checkIntent(Intent intent) {
    PackageManager packageManager = getPackageManager();
    List activities =     packageManager.queryIntentActivities(intent,
        PackageManager.MATCH_DEFAULT_ONLY);
        boolean isIntentSafe = activities.size() > 0;

        return isIntentSafe;
}

A: You will need to check to see if the package for VLC is installed. If it is not installed then open the play store showing the vlc install page.
This is the source:
String appPackageName = "org.videolan.vlc";
try {
    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
}

The source below will check to see if there is anything that can play video and if not, then it will prompt the user to install VLC. This is a more complete example that might help other users. It checks to see if anything locally installed can play the file and then if not, checks for vlc, and if VLC is not installed, then it will take the user to the Play Store.
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.fromFile(file));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString());
String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
intent.setDataAndType(Uri.fromFile(file), mimetype);

PackageManager manager = context.getPackageManager();
List<ResolveInfo> resolveInfoList = manager.queryIntentActivities(intent, 0);
if (resolveInfoList.size() > 0) {
    context.startActivity(intent);
} else {
    FragmentManager fragmentManager = ((AppCompatActivity) context).getSupportFragmentManager();
    ClassChatRecyclerAdapter.InstallVlcDialogFragment.newInstance(extension).show(fragmentManager, "INSTALL_VLC");
}

This is the dialog that will check for VLC and if it doesn't find it, then it will take the user to the play store to install it. You can take use the try/catch part of the source below to specifically solve your problem.
public static class InstallVlcDialogFragment extends DialogFragment {

    public static ClassChatRecyclerAdapter.InstallVlcDialogFragment newInstance(String mediaType) {
        ClassChatRecyclerAdapter.InstallVlcDialogFragment frag = new ClassChatRecyclerAdapter.InstallVlcDialogFragment();
        Bundle args = new Bundle();
        args.putString("mediaType", mediaType);
        frag.setArguments(args);
        return frag;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        String mediaType = getArguments().getString("mediaType");

        return new AlertDialog.Builder(getActivity(), R.style.AppDialogTheme)
                .setTitle("Unable to find video player for " +mediaType + " files.")
                .setMessage("Install VLC Player to play file?")
                .setPositiveButton("OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                String appPackageName = "org.videolan.vlc";
                                try {
                                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
                                } catch (android.content.ActivityNotFoundException anfe) {
                                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
                                }
                                dismiss();
                            }
                        }
                )
                .setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                dismiss();
                            }
                        }
                )
                .create();
    }
}


text:
Q: Convert string to numeric defining the number of decimal digits From a given data.frame of georeferred points I found the coordinate in a character column formatted as follow
"44.524768336 11.4832955249"
"44.6858512233 11.1698766486"
"44.498179364 11.6599683838"

To extract the numeric values from each rows I've used the following commands (I'll take the first row as example).
res <- strsplit(x = "44.524768336 11.4832955249", split = " ", fixed = T)
res
[[1]]
[1] "44.524768336"  "11.4832955249"

as.numeric(res[[1]][1])
[1] 44.52477
as.numeric(res[[1]][2])
[1] 11.4833

In this conversion I've lost 6 decimal digits.
Is there a method to convert strings to numbers setting the number of decimal places without modify any R global setting?

A: You didn't actually lose the digits; that's just how it is being printed to the console:
options(digits = 4)
R> as.numeric(res[[1]][1])
#[1] 44.52
##
options(digits = 12)
R> as.numeric(res[[1]][1])
#[1] 44.524768336

As pointed out in the comments by David Arenburg you can also use print(..., digits = <n>).

A: Taking the objective to obtain as results a number and adopting the suggestions provided by @nrussell in the previous answer (and followings comments) I've found the following solution:
string.number <- "44.004768336"

# Splitting the string in integer and decimal part
number.part <- strsplit(string.number, ".", fixed = T)
as.numeric(number.part[[1]][1])   # Integer part
[1] 44
as.numeric(number.part[[1]][2])   # Decimal part. Note the effect of the leading zeros
[1] 4768336

# saving the current and set the new setting the "digits" option
getOption(x = "digits")
[1] 11
current.n.dgt <- getOption("digits")
options(digits = 11)

# Combining integer and decimal in a number saving the required numbers of decimal digits
integer.part <- as.numeric(number.part[[1]][1])
exp.numb <- (trunc(log10(as.numeric(number.part[[1]][2])))+1+(nchar(number.part[[1]][2])-nchar(as.character(as.numeric(number.part[[1]][2])))))
decimal.part <- as.numeric(number.part[[1]][2])/(10^exp.numb)
res.number <- integer.part + decimal.part
res.number
[1] 44.004768336

A more simple way to avoid the string splitting is the following
getOption("digits")
[1] 7
current.n.dgt <- getOption("digits")

string.number <- "44.004768336"
options(digits = 11)
as.numeric(string.number)
[1] 44.004768336

options(digits = current.n.dgt)
getOption("digits")
[1] 7


text:
Q: Exchange 2013 Mailbox rights - how to prevent emails from being deleted I have a mailbox I would like to prevent users from deleting mails in, it is a shared mailbox on exchange 2013. At one stage the mailbox was converted from a shared folder to a shared mailbox, but some emails are going missing.
Is there a way that exchange can grant some users delete rights and some not.


text:
Q: Minecraft Launcher restarts when it is 99% done, why? Whenever I start downloading Minecraft Launcher and it is 99% done, it restarts automatically. I have tried downloading it three times, each time the same thing happened.
Here what is written in nativelog:
Native Launcher Version: 34
Operating System: Windows 8.1
Application Hash: 175f2b59d63d17f580f664c195ca8bb82666d0eb
Java Version:
x64: 1
Starting download of: https://launchermeta.mojang.com/mc/launcher.json
Created pFile
Content length is 00695D68
Got 200 from server
Download successful
Native launcher outdated!
Hash should be d026a01a83aeaec4111e8c7430ad89b21f3a30f3
Starting download of: http://launcher.mojang.com/mc/launcher/win/d026a01a83aeaec4111e8c7430ad89b21f3a30f3/Minecraft.exe
Created pFile
Content length is 006A37B0
Got 200 from server
Encountered internet exception 12002: The operation timed out
Starting download of: http://launcher.mojang.com/mc/launcher/win/d026a01a83aeaec4111e8c7430ad89b21f3a30f3/Minecraft.exe
Created pFile
Content length is 006A39C0
Got 200 from server
Download aborted
Deleted tmpLauncher.tmp

Any idea why this is happening and how I might prevent this?
I have read that slow net is also causing problem, My net speed is 2 mbps.
I have captured another error, Is this the problem?

A: This error is potentially caused by a slow network download speed.
Start downloading the new version, lock your PC and enjoy some tea or go out for a walk (just wait it out). After around 1 hour (considering that you have slow network speed), it should be completed; if not just keep waiting!


text:
Q: Dictionary based string matching algorithm - Java Is there any dictionary based string matching algorithm in Java?
Something that will give the percentage of similarity between two strings based on the dictionary ?
Like
 public double getSimilarity(String str1, String str2);

for which an implementation like :
 getSimilarity("Professor", "Teacher")

will give a very high percentage ?
Thanks in advance :)

A: There is a great work done by Shaul Markovitch and Evgeniy Gabrilovich, described in their article: Wikipedia-based Semantic Interpretation for Natural Language Processing.
The idea is as follows: Index wikipedia (or other context source).
Creating a mapping for each term (word): term -> articles in which the term appears in.
Each term is basically represented by a vector - for simplicity, let's say it is a binary vector - so for the term t the entry d will be '1' if and only if the term t appears in the document d.
Now, given these vectors - to find if two terms t1, t2 are similar - all you have to do it take the vector similarity of the two vectors that represent t1 and t2.

Note: The binary vector is a simplification, in fact the article uses the tf-idf score, that the term t has in a document d.


text:
Q: Query Optimization for Oracle to select single row from multiple views I have multiple tables a key of ACCOUNT_ID,
I have built multiple views to calculate various values for each CUSTOMER.
Now I am trying to traverse the relation:
EDIT: Given an svc_mrt_id, on account_id can be identified in CUS_SERVICE, then using the account_id, various statistics can be retrieved.
I tried this query
SELECT * FROM (
    SELECT *
    FROM CUS_SERVICE s
    LEFT JOIN CUSTOMER c ON s.account_id = c.account_id
    LEFT JOIN V_STCLOSE_5_CURRENT_BALANCE cb ON cb.stat_account_id = s.account_id
    LEFT JOIN V_STATUS_ALL sa ON sa.account_id = s.account_id
    LEFT JOIN V_NEXT_POOL_DATE pd ON pd.pool_donor = s.account_id
) WHERE svc_mrt_id = ?;

Query plan:
SELECT (245709)
    HASH JOIN (245078)
        HASH JOIN (628)
            NESTED LOOPS
                TABLE CUS_SERVICE (1)
                VIEW V_STATUS_ALL (626)
            VIEW V_STATUS_ALL (626)
/* This one is the culprit, should be (4317) if pushed predicates */
        VIEW V_STCLOSE_5_CURRENT_BALANCE (245078)
            HASH JOIN(232729)
                MAT_VIEW ACCESS(4)
                VIEW (232670)
/* Not pushing this predicate further is completely wrong */
/* Filtering here will generate large intermediate result set for only one row*/
/* Should be pushed to base table to generate only that one row required */
                    FILTER PREDICATES t1.ACCOUNT_ID = s.ACCOUNT_ID

The predicates now is pushed only to V_STATUS_ALL but not V_STCLOSE_5_CURRENT_BALANCE when two views are joined together with table CUS_SERVICE
Does anyone know if it is possible to fix this, or have any alternative to this?
Further informations:
Edit: 2013/12/26 19:13 GMT+8
I've isolated two views that are incompatible after some further testing. Here is the result:
SELECT * FROM (
    SELECT sa.account_id
    FROM V_STCLOSE_5_CURRENT_BALANCE cb
    LEFT JOIN V_STATUS_ALL sa ON sa.account_id = cb.stat_account_id
) WHERE account_id = ?;
/* COST = 4323 */

SELECT * FROM (
    SELECT s.svc_mrt_id
    FROM CUS_SERVICE s
    LEFT JOIN V_STCLOSE_5_CURRENT_BALANCE cb ON cb.stat_account_id = s.account_id
) WHERE svc_mrt_id = ?;
/* COST = 4322, looks right */

SELECT * FROM (
    SELECT s.svc_mrt_id
    FROM CUS_SERVICE s
    LEFT JOIN V_STATUS_ALL sa ON sa.account_id = s.account_id
) WHERE svc_mrt_id = ?;
/* COST ~ 2045 */

SELECT * FROM (
    SELECT s.svc_mrt_id
    FROM CUS_SERVICE s
    LEFT JOIN V_STCLOSE_5_CURRENT_BALANCE cb ON cb.stat_account_id = s.account_id
    LEFT JOIN V_STATUS_ALL sa ON sa.account_id = s.account_id
) WHERE svc_mrt_id = ?;
/* cost ~ 232729, something strange happened about this 3-Table join combination */

For the view query:
/*IV_STCLOSE_1_1_T*/
/*IV_STCLOSE_1_2_T*/
/*IV_STCLOSE_2_1_T*/
/*These are materialized view for the bill day related logic,
basically calculate the open and close dates for each customer each month,
and is only refreshed once per day*/

/*IV_STCLOSE_2_2_T*/
/*This filter some unnecessary, outdated transaction records*/
/*As each customer may have only 20/3M transaction records required for calculation,
the query must push select of account_id up to here to be most selective*/
SELECT ACCOUNT_ID, POINT_DATE, POINT
FROM history_point
WHERE point_date >= (
    SELECT MIN(open_date)
    FROM IV_STCLOSE_2_1_t
)

/*IV_STCLOSE_3_T*/
/*This sum points within each month*/
SELECT p0.account_id, p0.open_date, p0.close_date,
COALESCE(SUM(DECODE(SIGN(p.point),-1,p.point)),0) AS point_used,
COALESCE(SUM(DECODE(SIGN(p.point),1,p.point)),0) AS point_earned
FROM iv_stclose_2_1_t p0
LEFT JOIN iv_stclose_2_2_t p
ON p.account_id = p0.account_id
AND p.point_date >=  p0.open_date
AND p.point_date < p0.close_date + INTERVAL '1' DAY
GROUP BY p0.account_id, p0.open_date, p0.close_date

/*IV_STCLOSE_4_T*/
/*This sums each month's point earned and used for the open and close balance*/
SELECT v.account_id AS STAT_ACCOUNT_ID, v.open_date, v.close_date,
v.close_balance + t1.open_balance AS open_balance,
t1.point_earned AS point_earn, t1.point_used,
v.close_balance + t1.open_balance + t1.point_earned + t1.point_used AS close_balance
FROM IV_STCLOSE_2_1_T v
LEFT JOIN (
    SELECT v1.account_id, v1.open_date, v1.point_earned, v1.point_used,
    COALESCE(sum(v2.point_used + v2.point_earned),0) AS OPEN_BALANCE
    FROM IV_STCLOSE_3_T v1
    LEFT JOIN IV_STCLOSE_3_T v2
    ON v1.account_id = v2.account_id
    AND v1.OPEN_DATE > v2.OPEN_DATE
    GROUP BY v1.account_id, v1.open_date, v1.point_earned, v1.point_used
) t1
ON v.account_id = t1.account_id
AND v.OPEN_DATE = t1.OPEN_DATE

/*V_STCLOSE_5_CURRENT_BALANCE*/
/*This select the most recent balance*/
SELECT v.STAT_ACCOUNT_ID,v.OPEN_DATE,v.CLOSE_DATE,
v.OPEN_BALANCE,v.POINT_EARN,v.POINT_USED,v.CLOSE_BALANCE
FROM IV_STCLOSE_4_T v
WHERE MONTHS_BETWEEN(TRUNC(SYSDATE), v.OPEN_DATE) < 1

A: Try adding an index hint so the optimizer will use that particular index.  You could also try listing the tables in the order in which they should be joined and then add the /*+ ordered */ hint.


text:
Q: Php and ajax compare issue I'm ajaxing over to this php file.
$a = 'old';
$b = 'new';
if ($_POST['info-type'] == $a || $b)
{
    $info = $_POST['info-type'];
    $query = "SELECT * FROM `tld` WHERE type = '".$var."'";
}

$query = "SELECT * FROM `tld` ";

$result = mysqli_query($link,$query);

while($row = mysqli_fetch_assoc($result))
{
    echo '<div>'.$row['something'].'</div>';
}

The data posted is either 'all' 'new' or 'old'.
If I send the data as either new or old, the script works and outputs as expected.
If the posted data is neither new or old but all instead, it fails and don't show any errors or respond anything back (I've monitored via dev tools as well).
So, I tried this:
if ($_POST['info-type'] == $a || $b)
{
    $info = $_POST['info-type'];
    $var = "SELECT * FROM `tld` WHERE type = '".$var."'";
} elseif ($_POST['info-type'] == 'all')
{
    $query = "SELECT * FROM `tld` ";
}

But the script still fails. If i fully remove the IF statements and use the query without the WHERE clause like it is after the elseif, it works?

A: This statement is very odd:
if ($_POST['info-type'] == $a || $b) {

You probably intended:
if ($_POST['info-type'] === $a || $_POST['info-type'] === $b) {

Also, in this case === is good since the type of both variables is string.
$_POST['info-type'] == $a || $b will always be true if $b is truethy (which it is).

A: You need to compare $_POST['info-type'] with both $a and $b:
if ($_POST['info-type'] == $a || $_POST['info-type'] == $b)

The problem with what you have is that $_POST['info-type'] == $a || $b sees if $_POST['info-type'] == $a is true OR if $b is true.
Since $b is true (it is non-empty string), the if condition will always be true.

If $_POST['info-type'] can only be all new or old, then the following will be more elegant:
if ($_POST['info-type'] == 'all')
{
    $query = "SELECT * FROM `tld` ";
}
else // info type will be old or new
{
    $info = $_POST['info-type'];
    $query = "SELECT * FROM `tld` WHERE type = '".$info."'";
}


text:
Q: colon (:) gives load error in locale YAML file I have a string in en: locale which is
display_device: to play : get player

The colon sign is giving me error which is

can not load translations from C:/Documents and  Settings/rajg/discoveryaws/branches/internationalization/config/locales/en.yml, expected it to return a hash, but does not

How can I make this work?

A: You can escape colons (and other 'important' characters) in your string if you surround it with quotes like this:
display_device: "to play : get player"