Capybara results in a no method error when its methods are referenced by Rspec

Question: Gem file
source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.0.0'

# Use sqlite3 as the database for Active Record
gem 'sqlite3'

# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.0'

# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'

# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'

# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'

# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'

# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 1.2'

group :doc do
  # bundle exec rake doc:rails generates the API under doc/api.
  gem 'sdoc', require: false
end

# Use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.0.0'

# Use unicorn as the app server
# gem 'unicorn'

# Use Capistrano for deployment
# gem 'capistrano', group: :development

# Use debugger
# gem 'debugger', group: [:development, :test]

gem "factory_girl_rails"

group :development, :test do
  gem "rspec-rails", "~> 2.0"
  gem "capybara", "~> 2.1.0"
end

spec_helper.rb
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
require 'capybara/rspec'
require 'capybara/rails'

# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }

# Checks for pending migrations before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.check_pending! if defined?(ActiveRecord::Migration)

RSpec.configure do |config|
  config.include Capybara::DSL
  # ## Mock Framework
  #
  # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
  #
  # config.mock_with :mocha
  # config.mock_with :flexmock
  # config.mock_with :rr

  # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
  config.fixture_path = "#{::Rails.root}/spec/fixtures"

  # If you're not using ActiveRecord, or you'd prefer not to run each of your
  # examples within a transaction, remove the following line or assign false
  # instead of true.
  config.use_transactional_fixtures = true

  # If true, the base class of anonymous controllers will be inferred
  # automatically. This will be the default behavior in future versions of
  # rspec-rails.
  config.infer_base_class_for_anonymous_controllers = false

  # Run specs in random order to surface order dependencies. If you find an
  # order dependency and want to debug it, you can fix the order by providing
  # the seed, which is printed after each run.
  #     --seed 1234
  config.order = "random"
end

xxtests_spec.rb
require 'spec_helper'

describe "Xxtests" do
    describe "GET /xxtests" do
       it "works! (now write some real specs)" do
        get 'people/new'
        response.status.should be(200)
       end
       it "works! (now write some real specs)" do
        get people_path
        response.status.should be(200)
       end
    end

    describe "POST /persons" do
        # visit 'people/new'
        response.status.should be(200)
    end
end

All works perfectly. The second I uncomment
visit 'people/new'

I get
undefined method error.

I have read the Capybara and Rspec documentation through very carefully, and I've done everything. I really don't know what else to say, but it just does not work.
Answer: You are calling visit inside a describe block instead of within a code example (it block). Try:
describe "POST /persons" do
  it "responds with success status" do
    visit 'people/new'
    response.status.should be(200)
  end
end

The Capybara methods are mixed into instances of the code examples so are not available outside.


How can I integrate a stemmer with Search API?

Question: Exactly what the question says - I'm using Search API with Database Search. I also have the Porter Stemmer module, but my understanding is that it only works with the Drupal built-in search.
Any help with this would be greatly appreciated.
Answer: It is possible to use the Porter Stemmer module with other modules besides the Drupal standard search. I have done it before (with Views exposed filters).
In your module, you could either invoke the porterstemmer_search_preprocess() function or just copy its contents into your own function. And then pass your search terms to this function. E.g.:
function your_function_for_preprocessing_text($text) {
   // Include porterstemmer (change accordingly).
   module_load_include('module', 'porterstemmer');

  // Convert text to lower case, and replace special apostrophes with regular
  // apostrophes.
  $text = drupal_strtolower(str_replace(''', "'", $text));

  // Split into words
  $words = preg_split('/(' . PORTERSTEMMER_BOUNDARY . '+)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);

  if (!count( $words )) {
    return $text;
  }

  $has_pecl_stem = _porterstemmer_pecl_loaded();

  // Process each word, skipping delimiters.
  $isword = !preg_match('/' . PORTERSTEMMER_BOUNDARY . '/', $words[0] );
  foreach ($words as $k => $word) {
    if ($isword) {
      if ( $has_pecl_stem ) {
        $words[$k] = stem_english($word);
      }
      else {
        $words[$k] = porterstemmer_stem($word);
      }
    }
    $isword = !$isword;
  }

  // Put it all back together (note that delimiters are in $words).
  return implode('', $words);
}

As I said, I have used the Porter Stemmer to stem all the terms entered in a Views exposed search. However, you'll still need to find the right hook in the Search API module to pre-process the text before the search query is run against the database.


while loop getting stuck - Openmp

Question: I was trying to implement some piece of parallel code and tried to synchronize the threads using an array of flags as shown below
// flags array set to zero initially

#pragma omp parallel for num_threads (n_threads) schedule(static, 1)
    for(int i = 0; i < n; i ++){
        for(int j = 0; j < i; j++) {
            while(!flag[j]);
            y[i] -= L[i][j]*y[j];
        }
        y[i] /= L[i][i];
        flag[i] = 1;
    }

However, the code always gets stuck after a few iterations when I try to compile it using gcc -O3 -fopenmp <file_name>. I have tried different number of threads like 2, 4, 8 all of them leads to the loop getting stuck. On putting print statements inside critical sections, I figured out that even though the value of flag[i] gets updated to 1, the while loop is still stuck or maybe there is some other problem with the code, I am not aware of.
I also figured out that if I try to do something inside the while block like printf("Hello\n") the problem goes away. I think there is some problem with the memory consistency across threads but I do not know how to resolve this. Any help would be appreciated.
Edit: The single threaded code I am trying to parallelise is
    for(int i=0; i<n; i++){
        for(int j=0; j < i; j++){
            y[i]-=L[i][j]*y[j];
        }
        y[i]/=L[i][i];
    }

Answer: You have data race in your code, which is easy to fix, but the bigger problem is that you also have loop carried dependency. The result of your code does depend on the order of execution. Try reversing the i loop without OpenMP, you will get different result, so your code cannot be parallelized efficiently.
One possibility is to parallelize the j loop, but the workload is very small inside this loop, so the OpenMP overheads will be significantly bigger than the speed gain by parallelization.
EDIT: In the case of your updated code I suggest to forget parallelization (because of loop carried dependency) and make sure that inner loop is properly vectorized, so I suggest the following:
for(int i = 0; i < n; i ++){
    double sum_yi=y[i];
    #pragma GCC ivdep
    for(int j = 0; j < i; j++) {
        sum_yi -= L[i][j]*y[j];
    }

    y[i] = sum_yi/L[i][i];
}

#pragma GCC ivdep tells the compiler that there is no loop carried dependency in the loop, so it can vectorize it safely. Do not forget to inform compiler the about the vectorization capabilities of your processor (e.g. use -mavx2 flag if your processor is AVX2 capable).
Comment: If you use or do not use the while loop, you get different result in a single threaded code. My suggestion is the following: update your post and show us the single threaded code you wish to parallelize and we tell you how to do it (if possible).
Comment: Thanks for the response. From what I have thought, the execution of the line y[i] -= L[i][j] * y[j] is the one carrying loop dependence and to remove the dependence, I have put the while loop before it, which stalls the execution of the statement until the correct value is put in y[j]. Wouldn't it resolve the issue then?

while loop getting stuck - Openmp


Create object array with dynamic properties

Question: In the targetData array, objects has properties("january",etc ) are taken from  source array.... I am unable to transform sourceEvents to TargetData array.
var sourceEvents =[
    {
        "title": "Course Tile1",
        "details": "Webex| Advanced",
        "month": "January"
    },
    {
        "title": "Course Tile1",
        "details": "Webex| Advnced",
        "month": "february"
    },
    {
        "title": "Course Tile1",
        "details": "Webex| Advnced",
        "month": "febrary"
    }];

var TargetData =[
    {"january":
  [
        {
            "title": "Course Tile1",
            "details": "Webex| Advanced"
        },
        {
            "title": "Course Tile2",
            "details": "Webex| Advanced",

        }
  ]
    },
    { "Feb":[
    {
            "title": "Course Tile3",
            "details": "Webex| Advanced"
        },
        {
            "title": "Course Tile4",
            "details": "Webex| Advanced"

        }]
}
]

I need to use ng-repeat to loop the resulting array.
Comment: That target structure will be hard to loop through usefully.
Answer: It'll be hard to loop through the structure you've shown. I'd suggest this instead:
var targetData = [
    {
        "month": "january",
        "entries": [
            {
                "title": "Course Tile1",
                "details": "Webex| Advanced"
            }, {
                "title": "Course Tile2",
                "details": "Webex| Advanced",

            }
        ]
    },
    {
        "month": "february",
        "entries": [
            {
                "title": "Course Tile3",
                "details": "Webex| Advanced"
            },
            {
                "title": "Course Tile4",
                "details": "Webex| Advanced"

            }
        ]
    }
];

That way, you have nested ng-repeats: One for months, then the next for the entries in the month.
In which case, it's fairly easy to produce with a loop over your source data and a temporary index of months to entries:

var sourceEvents = [
    {
        "title": "Course Tile1",
        "details": "Webex| Advanced",
        "month": "January"
    },
    {
        "title": "Course Tile1",
        "details": "Webex| Advnced",
        "month": "February"
    },
    {
        "title": "Course Tile1",
        "details": "Webex| Advnced",
        "month": "February"
    }
];

var months = Object.create(null);
var targetData = [];
sourceEvents.forEach(function(event) {
    var month = event.month;
    var entry = months[month];
    if (!entry) {
        months[month] = entry = {
            month: month,
            entries: []
        };
        targetData.push(entry);
    }
    entry.entries.push({
        title: event.title,
        details: event.details
    });
});
document.body.innerHTML =
    "
" + JSON.stringify(targetData, null, 4).replace(/</g, "<") + "
";

Note: Your source data had a couple of typos which I've fixed in the above.

Side note: I've used targetData rather than TargetData in the above because it's more in keeping with the majority of JavaScript style guides.
Comment: @Dew: Wow, just how old a browser are you using? **:-)** [`Array#forEach`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) was added by the ES5 specification in 2009, all modern browsers have it. It can be shimmed on obsolete browsers like IE8, or just use a `for` loop instead. There's a truly exhaustive list of options for looping through arrays [in this answer](http://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript/9329476#9329476).
Comment: @tj   foreach doesnt work, should I include any library...?
Answer: Note the quotes or lack thereof:
var sourceEvents = [
    {
        title:"Course Tile1",
        details:"Webex| Advanced",
        month:january
    },
    {
        title:"Course Tile1",
        details:"Webex| Advnced",
        month:february
    },
    {
        title:"Course Tile1",
        details:"Webex| Advnced",
        month:february
    }
];
var january = [
    {
        title:"Course Tile1",
        details:"Webex| Advanced"
    },
];
var february = [
    {
        title:"Course Tile1",
        details:"Webex| Advanced"
    },
];
var targetEvents = [
    {
        january, february,
    }
];


How can I reuse Laravel 5 Collection Filters?

Question: I've got a custom collection sortBy function that I use to sort a model. The problem is, I'm copying and pasting this filter code every time I want to sort it. It seems like this must be beyond best practices since copying and pasting code for reuse is a no no. What is the best practice way to handle this?
For instance, we have Eloquent scopes for reusable query based sorting and stuff like that, but nothing for collections along the same vein.
Comment: Can't you add the sortBy method to the Model class? Everytime you extend Model (with all your models) they will inherit it.
Comment: My bad, you were talking about Collections. So, can't you edit the Collection class?
Answer: Declare a "helper" function (see Laravel's helpers for where to put this & how to autoload it) and use that wherever you need to sort, like this:
The sort function:
function mySortHelper($a, $b) {
    // ... sorting code goes here ...
}

And when you need to use it:
$collection->sortBy("myHelperFunction");

Edit: Adding a helper function
Here's the way I've done this in my applications.
In the app directory, create a folder called Helpers.
Inside the Helpers directory, create a new PHP file called (for example) Sorting.php.
In this new file, create your function like this:
if ( ! function_exists('mySortHelper'))
{
    function mySortHelper($a, $b)
    {
        return $a<$b ? -1 : 1;
    }
}

This code is copied (with changes) from the the Laravel framework helpers file (found at vendor/laravel/framework/src/Illuminate/Foundation/helpers.php).
Then the only thing left is the autoloading. Update your composer.json file with:
"autoload": {
    "files": [
        ...
        "app/Helpers/Sorting.php",
        ...
    ]
},

There may be other sections in the autoload section of the composer.json or other things listed under files. Just add the file you created to that section of your composer.json and run composer dump-autoload to update. Your helper function will now be available throughout your Laravel application.


Find a control in Detailsview

Question: I want to find a control which is in the details view. I am new to .net.
How can I do this?
Answer: you can use FindControl method for that, like...
<code>TextBox TextBox1 = (TextBox)yourDetailsViewID.FindControl("TextBox1");
</code>
Comment: you need to take care your DetailsView mode and template

Find a control in Detailsview


Joining 3 grouped values

Question: I have 3 queries that counts for each company, number of rows during certain month, from 3 different tables, and returning the same columns :qty,  month and company_name.
Instead of this I need to return 1 table with same 3 columns but qty must sum the value of all the 3 separated queries.
Can you suggest the best way to join or execute it in which I will not loose speed of execution.
Here is example of one of queries, the other 2 queries has exactly the same syntax, just instead T_CUSTSK, they use T_CUSTSK2 and T_CUSTSK3:
SELECT
    COUNT(*) as qty,
    DATEPART (MONTH, [start_date]) AS [month],
    T_SYSCOM.company_name
FROM
    T_CUSTSK
INNER JOIN
    T_SYSCOM ON T_CUSTSK.company_id = T_SYSCOM.company_id
WHERE
    DATEPART (MONTH, [start_date]) = 12
GROUP BY
    DATEPART (MONTH, [start_date]), T_SYSCOM.company_name
ORDER BY
    month, qty DESC

Comment: Can u post some sample input and output?
Comment: Could you post the table schema of T_CUSTSK and T_SYSCOM table?
Comment: company name is varchar(100), qty int
Comment: Which RDBMS is this for? Please add a tag to specify whether you're using `mysql`, `postgresql`, `sql-server`, `oracle` or `db2` - or something else entirely.
Answer: Union all will combine your queries.
You can then wrap your statement with another query that sums:
select sum(qty), month, company_name from (
Select count(*) as qty, datepart(month, [start_date]) as [month], T_SYSCOM.company_name
from T_CUSTSK
INNER JOIN T_SYSCOM
ON T_CUSTSK.company_id=T_SYSCOM.company_id
where datepart(month, [start_date])=12
group by datepart(month, [start_date]), T_SYSCOM.company_name
order by month, qty DESC

union all

<second query>

union all

<third query> )

group by month, company_name

Answer: Try this you could do UNION ALL of all the T_CUSTSKx tables in the subquery and join that result once with T_SYSCOM table.
I'm assuming the start_date is in T_CUSTSK table
Select count(*) as qty, datepart(month, [start_date]) as [month], T2.company_name
from (
SELECT company_id,start_date FROM T_CUSTSK
UNION ALL
SELECT company_id,start_date FROM T_CUSTSK2
UNION ALL
SELECT company_id,start_date FROM T_CUSTSK3
) T1
INNER JOIN @T_SYSCOM T2
    ON T1.company_id=T2.company_id
where datepart(month, [start_date])=12
group by datepart(month, [start_date]), T2.company_name
order by month, qty DESC

kindly let me know if this works
Comment: i should mention that in the 2 queries each date field has different name. start_date1, start_date2, start_date3
Comment: If the fields are of different name, then you set the column name as start_date in the inner sub query.  ""SELECT company_id,start_date1 AS start_date FROM T_CUSTSK
UNION ALL
SELECT company_id,start_date2 AS start_date FROM T_CUSTSK1
UNION ALL
SELECT company_id,start_date3 AS start_date FROM T_CUSTSK2""

Joining 3 grouped values


Is there a combinatorial way to calculate the probability of a run in this scenario?

Question: Say I have a vector (list) $V$ consisting of $O$ ones and $Z$ zeroes, e.g., ${1,1,1,0,0,0,0,0}$ has $O$ of 3 and $Z$ of 5.
I take $K$ random permutations of $Z$ and then sum the results, e.g, say $K$ were 2, and the two random permutations of the above $Z$ were ${1, 0, 0, 0, 1, 0, 0, 1}$ and ${0, 0, 0, 0, 1, 1, 1, 0}$, giving a sum of ${1, 0, 0, 0, 2, 1, 1, 1}$.
I'm interesting in calculating the probability, given $O, Z$, and $K$, of a run of $R$ or more zeros in the resulting sum.
Right now, I'm just using a simulation, but I'm wondering if there is a direct combinatorial way of accomplishing this.
Comment: Is there any particular range of values of parameters that you are interested in? For example, $O<>Z$, $K$, $R$ large or small?
Comment: @A.S. : Yes, as a matter of fact in my current needs, $O<<Z$ (as in 2-4 and 200-300 respectively), $K$ is between 50 and 60, and $R$ between 10 and 20. I am after an *exact* solution is possible, or if not a very accurate estimator, else I might as well just simulate it.
Comment: and do you want necessarily probability of a run of at least $R$ zeros or are you trying to approximate some other metric/express some other more general notion? Basically what is the real problem for which you came up with this model.
Comment: @A.S.: I am only interested in the probability of runs of at least $R$ zeros. The real problem has to do with a random allocation of resources into resource slots where the slots represent a temporal sequence.
Comment: Are all parameters in question fixed quantities or themselves distributed somehow and you are interested in average (max/min) over those distributions?
Comment: For any given case of interest, they are all fixed for that case. I am only after probability for some fixed set of parameters for a given case - I'll know them beforehand.
Answer: Average ones per bit:
$$r=\frac {OK}N\in[0.33|0.67|1.20]$$
Probability that a given bit is $0$ after $K$ permutations are added up:
$$p_1(N)=(1-\frac O N)^K\lessapprox e^{-OK/(N-O/2)}\lessapprox e^{-r}\in[0.30|0.51|0.72]$$
Let $X_i$ be an indicator variable of the event that bits from $i$ to $i+R-1$ are all $0$ (run of length $R$) (with cancellation for $O\le R$ as the case for given parameter values):
$$p_R(N)=P(X_i=1)=\prod_{i=0}^{R-1}p_1(N-i)=\left(\prod_{i=0}^{R-1}\frac {N-O-i}{N-i}\right)^K=\left(\prod_{i=0}^{O-1}\frac{N-R-i}{N-i}\right)^K\lessapprox\left(\frac{N-R-(O-1)/2}{N-(O-1)/2}\right)^{OK}\lessapprox e^{-OKR/(N-(O+R-1)/2)}\lessapprox e^{-rR}\in[3.47\cdot 10^{-11}|4.11\cdot 10^{-5}|3.74\cdot 10^{-2}] \tag 1$$
Let $W=\sum_{i=1}^{N-R+1} X_i$ be the total number of such runs. Then $$E(W)=(N-R+1)p_R(N)\in[6.94\cdot 10^{-9}|1.03\cdot 10^{-2}|11.2]REVISE$$
If $E(W)$ is not too large, we can get a great approximation by Poisson. A run of length $R$ will be followed by an average of $\frac {p_1(N-R)}{1-p_1(N-R)}$ more runs for a total of $\frac 1 {1-p_1(N-R)}$ runs clumped together. Hence density of isolated clumps of length at least $R$ is $$\lambda\approx p_R(N)(1-p_1(N-R))$$ which implies that
$$P(W=0)\approx \exp(-\lambda (N-R+1))\approx $$

If we are interested in approximating all of $W$, not just $P(W\ge 1)$, we can use Stein's method (specifically p.15)
Collection ${X_i}$ is positively associated and $$E(X_iX_j)\approx p^Rp^{\min\{|i-j|,R\}}$$
Approximate $W$ by $\bar W=Pois(\lambda)$ where $\lambda=Np^R$. Then $$|P(W\ge 1)-(1-e^{-Np^R})|\le d_{TV}(W,\bar W)\le\min\{1,1/\lambda\}(var(W)-\lambda+2Np^{2R})=\min\{1,\lambda\}(2\frac {p-p^R}{1-p}-(2R-3)p^R)$$
If $\lambda$ or $p$ is are small, the approximation is good in absolute terms. If $p$ is small, it's good in relative terms as well.


iOS image resize: is there a better interpolation than the kCGInterpolationHigh?

Question: I use this method to resize an image to the double of its original dimensions:
<code>- (UIImage *)doubleSizeImage:(UIImage *)image {
    CGSize newSize = CGSizeMake(image.size.width*2, image.size.height*2);
    UIGraphicsBeginImageContext(newSize);
    CGContextSetInterpolationQuality(UIGraphicsGetCurrentContext(), kCGInterpolationHigh);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
 }
</code>
The fact is that the interpolation is still poor: I can see well the pixelated effect which, for example, iOS Safari doesn't have when zooming pages. So I was wondering if there a better way to upscale an image, also using a third party library/category or something like that? Thanks!
Comment: Are you sure that you're actually using kCGInterpolationHigh? What if you get rid of that line... does it look the same? Just double checking. Also, it would be helpful if you shared the results of this vs. Safari just for our information.
Answer: Any time you interpolate, you're going to get some kind of artifacts.
Safari doesn't get artifacts on the page because the page is essentially a vector document, with outline fonts and resizable objects—but if you look at a raster image on the page, you'll see that if you blow it up big enough, the image will indeed show artifacts. Safari is not immune; nothing is.
Comment: I know that, and I was not talking about the vector parts. Given the same zoom, images on safari simply are better interpolated: of course with artifacts, but better "blurred". In my app, the same image at the same size is just more pixelated. But hey, I guess that in the end it's just ok.
Comment: @AndreaSprega: It's possible that Safari is using a different interpolation level that you prefer, or that it is changing the size of a layer (and I don't know how that relates to any of the interpolation values or the current one in the view's context).


How to list the parent commit of a stash in `git stash list`

Question: When I generate a stash in git, there is a "parent" (the last commit before I stashed my changes).
When I use git stash to stash my changes, an ID to that parent-commit is added to the message describing my stash. calling git stash list can e.g. show:
stash@{0}: WIP on master: c09a3fc second commit
stash@{1}: WIP on master: 063b893 first commit
stash@{2}: WIP on master: 063b893 first commit

But when I run git stash save "My own message" the ID of the parent-commit is not added (git stash list):
stash@{0}: On master: My own message
stash@{1}: WIP on master: c09a3fc second commit
stash@{2}: WIP on master: 063b893 first commit
stash@{3}: WIP on master: 063b893 first commit

It there a way to show the ID of the parent-commit to the list of stashes?
I tried: git stash list --oneline --parents, which gave me:
1b5dfb1 4efd3e0 refs/stash@{0}: On master: My own message
4efd3e0 1e9b384 refs/stash@{1}: WIP on master: c09a3fc second commit
1e9b384 51eb834 refs/stash@{2}: WIP on master: 063b893 first commit
51eb834 refs/stash@{3}: WIP on master: 063b893 first commit

But here the wrong IDs are shown. I expected (the first line beeing the ID of the parent-commit which is the same for groups of two commits in this example):
c09a3fc 1b5dfb1 refs/stash@{0}: On master: My own message
c09a3fc 4efd3e0 refs/stash@{1}: WIP on master: c09a3fc second commit
063b893 1e9b384 refs/stash@{2}: WIP on master: 063b893 first commit
063b893 51eb834 refs/stash@{3}: WIP on master: 063b893 first commit

Comment: If you want to do it for a single stash you can do `git show stash@{0}^`, as `stash@{0}` is a valid refname. You could build a small script around that to get the output you want - but that's an exercise for the reader, so this is just a comment :-)
Comment: @JanFabry Thanks for your comment. Is `git show stash@{0}^` the answer to my question here? https://stackoverflow.com/questions/62840077/how-to-recover-from-git-added-by-us-conflict-after-applying-stash-after-renami/62842712#comment111147132_62842712
Comment: Also, for people interested in this topic, I noticed that this question is quite similar: https://stackoverflow.com/q/16071720/470749
Answer: If you want the ID included in the message you supply, you can supply the ID as part of the message.  That is, instead of:
$ git stash save "My own message"

you might run:
$ git stash save "[$(git rev-parse --short HEAD)] My own message"

(you might turn this into an alias—either a shell alias, or a git alias that invokes the shell).
If you want to make use of the parent IDs actually stored in the tree, you must delve into the implementation of git stash.  See this answer for lots of detail, but in short, the first parent of the work-tree commit w (refs/stash, or the reflog entry, points to this w commit) is the commit that was HEAD at the time the stash was made.
The git stash list sub-command simply passes additional arguments directly to git log, so --oneline --parents does what it does with git log—except that git stash list does it like this:
git log --format="%gd: %gs" -g --first-parent -m "$@" $ref_stash --

(where "$@" are your additional arguments).  Unfortunately, --parents uses history simplification and parent rewriting (see the documentation for git rev-list), which with -g, turns into "replace parentage with result of reflog walk", which totally destroys the original parentage information.
(Incidentally, the only reason I can see for the explicit --first-parent here is to make --parents hide the index and optional extra commit.  Since --parents get clobbered anyway by the reflog walk, it seems to be pointless.  Not sure if the git folks might intend reflog walks not to clobber parent information, and if it didn't clobber, you'd have seen what you wanted.  So this might be a git bug, although there is a lot of guessing-at-intentions here.)
You can (sort of) get what you want by going back to the original commit IDs (the w commits) and using git rev-parse to find the first-parent of each w commit:
git log -g --format="%gd %H" refs/stash |
while read name hash; do
    printf "%s %s " $name $(git rev-parse --short $name^)
    git log -1 --format=%s $hash
done

(there may be ways to shorten this, the above is pretty straightforward though).
Comment: In mac os 10.12.6 with git version 2.17.1,I found out the result is printed in a series of less screen, append `| cat` to above command fix the problem.
Comment: @cmicat: `git log` uses your pager, or doesn't, based on your configuration settings. Set `core.pager` to control which pager is used; use `git --no-pager` to inhibit the pager for one command; set `pager.` (e.g., `pager.log`) to `true` or `false`. Since `git log` is used for a lot of other things, you might not want to change its defaults here. Note that if you use `less` as your pager, you can set `LESS` options in your environment. If you don't, Git will set them for you, to `FRX`, by default (this is a Git build-time option).
Comment: Thank you for this answer. Would you mind seeing if you can clarify on my similar question here? https://stackoverflow.com/q/62867041/470749


In Views, when using a filter on a datetime field, what is the time zone of the offset?

Question: When I use an offset like "-4 hours" in a Views filter on a datetime field, which timezone is used?
More details
In Views, when I add a filter for a datetime field, I get the following options for Value type:

A date in any machine readable format. CCYY-MM-DD HH:MM:SS is preferred.
An offset from the current time such as "+1 day" or "-2 hours -30 minutes"

On my site, users can set their own timezones. (/admin/config/regional/settings Users may set their own time zone)
So there are potentially three timezones in play:

In the database, the strings for datetime are stored in the UTC timezone
The site timezone is set to Tokyo
The user timezone is set to Berlin

So, which of these timezones does the offset use?
Answer: For datetime fields, it uses the timezone for the user viewing the page. If no user timezone is set, it uses the default site timezone.
See the relevant comment from Drupal\datetime\Plugin\views\filter\Date.php:

Date-only fields do not have a time zone associated with them, so the filter input needs to use UTC for reference. Otherwise, use the time zone for the current user.

<code>/**
 * Get the proper time zone to use in computations.
 *
 * Date-only fields do not have a time zone associated with them, so the
 * filter input needs to use UTC for reference. Otherwise, use the time zone
 * for the current user.
 *
 * @return string
 *   The time zone name.
 */
protected function getTimezone() {
  return $this->dateFormat === DateTimeItemInterface::DATE_STORAGE_FORMAT
    ? DateTimeItemInterface::STORAGE_TIMEZONE
    : date_default_timezone_get();
}
</code>


Laravel: Syntax error or access violation: 1071 Specified key was too long

Question: Fui fazer a criação das tabelas no banco de dados, mas me mostra o erro: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes.
Como arrumar isso?
Answer: Isso acontece pois o Laravel alterou o valor default dos campos. Para corrigir isso, basta ir no arquivo app/Providers/AppServiceProvider.php e adicionar o seguinte código:
use Illuminate\Support\Facades\Schema;

public function boot()
{
    Schema::defaultStringLength(191);
}

Comment: Na realidade você está alterando o valor default executando esse comando, o erro realmente ocorre pelo fato de o banco não estar com o encode correto, no seu arquivo database.php você pode alterar o `charset` e o `collation` e irá funcionar, ai não precisa mexer no padrão de String.
`'charset' => 'utf8mb4',`
`'collation' => 'utf8mb4_unicode_ci',`
`'engine' => 'InnoDB ROW_FORMAT=DYNAMIC',`
Answer: Uma outra forma de resolver é adicionar o nome do índice no segundo parâmetro:
$table->string('seu_campo')->unique(null,'chave');


Como redirecionar um usuário para uma página específica apenas no primeiro login do site em wordpress?

Question: Eu inclui direto na tabela wp_users alguns usuários, somente com o ID, USER_LOGIN, USER_PASS, USER_NICENAME E DISPLAY_NAME.
Ficando assim , por exemplo:
INSERT INTO wp_users (ID, user_login, user_pass, user_nicename, user_email,
user_url, user_registered, user_activation_key, user_status, display_name)
VALUES
(1500, 'steoliv', '65442334hio','steoliv', ", ",'2018-01-09 13:01:00′, ", 0,
'Stefany');

Eu gostaria que no primeiro acesso, feito pelo nome de usuário e senha que eu criei, redirecionasse o usuário para uma página , que eu tbm já criei (site/editar-cadastro) e atualizasse os dados com as informações que faltam, como por exemplo o e-mail.
Tem algum plugin ou algum código que seja possível fazer o que eu desejo?
Comment: acredito que você precise de uma `flag` para saber isso; tente adicionar outro campo como `first_login` no usuario e assim voce pode verificar se é ou não o primeiro login; quando realizar o cadastro o campo fica como "1" e depois de ir editar os dados na pagina que voce quer fique como "0".
Comment: Ta, mas ai vc está me dizendo para verificar.
Preciso de algo que me ajude nem que seja para fazer isso todas a vezes que o usuário logar. Se eu encontrar um que já faça isso já é meio caminho andado.
Answer: Você pode utilizar uma flag para saber se é ou não a primeira vez que um usuário faz login na sua plataforma. Acrescente essa flag no seu banco de dados e sempre que o usuário for fazer login você testa a fleg. Depois de testar se o usuário e a senha estão corretos você testa a flag
if(result['flag'] == 0){
    // Atualiza a colona da flag
    $query = "UPDATE wp_users SET flag = 1 WHERE usuario = $usuario";
    mysqli_query($con,$query);
    // Faz o redirecionamento para a página de editar cadastro
    header("location: http://minhaurl/site/editar-cadastro");
}else{
    header("location: http://minhaurl/site/outra-area");
}


Calculating multivariate integrals between lower and upper bounds

Question: Suppose $\vec{X}=(x_1,x_2,...,x_n)$ follows some continuous multivariate distribution, such that $x_i\in{\rm I\!R}, i=1,...,n$.
Suppose also that I have access to the following functions:

$\phi(\vec{x})$, which gives me the pdf at point $\vec{x}=(x_1,x_2,...,x_n)$
$\Phi^{upper}(\vec{x})$, which calculates the CDF from $-\infty$ to $\vec{x}$. More specifically: $\Phi^{upper}(\vec{x})=\int_{\vec{k}=(-\infty,...,-\infty)}^{(x_1,...,x_n)}\phi(\vec{k})d\vec{k}$

My main question is: how can I use $\Phi^{upper}(\vec{x})$ to calculate the CDF between lower and upper bounds?
In other words, how can I calculate integral of $\phi$ from $\vec{x}_{lower}$ to $\vec{x}_{upper}$ using $\Phi^{upper}$?
In mathematical terms, how can I use $\Phi^{upper}$ to calculate the following integral?
$$\Phi^{upper}_{lower}(\vec{x}_{lower},\vec{x}_{upper})=\int_{\vec{k}=(x_1^{lower},...,x_n^{lower})}^{(x_1^{upper},...,x_n^{upper})}\phi(\vec{k})d\vec{k}$$
I know that if there are only 2 dimensions in $\vec{X}$, I can calculate $\Phi^{upper}_{lower}(\vec{x}_{lower},\vec{x}_{upper})$ like this:
$$\Phi^{upper}_{lower}(\vec{x}_{lower},\vec{x}_{upper}) =  \Phi^{upper}(x_1^{upper},x_2^{upper})  - \Phi^{upper}(x_1^{upper},x_2^{lower})  - \Phi^{upper}(x_1^{lower},x_2^{upper})  + \Phi^{upper}(x_1^{lower},x_2^{lower})$$
However, I don't know how to generalize this result for an N-dimensional case.
Does anyone have any insight on how to do this?
Thank you very much!
Comment: Not exactly, no. Consider the 2 dimensional example I gave. If you just do $\Phi^{upper}(\vec{x}_{upper}) - \Phi^{upper}(\vec{x}_{lower})$, you're leaving in a few areas that shouldn't be considered.
[Here is an image](https://www.dropbox.com/s/zl72gt7wqrdeys6/lower_upper.png?dl=0) to illustrate my point.
Comment: Assuming you're talking about a rectangular area, you probably want to apply the [inclusion-exclusion rule](https://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle) here.
Comment: I can see how this touches on what I'm getting at, but I'm having a bit of a hard time understanding how I would apply this concept from set theory to this particular problem. Could you maybe elaborate a little bit further on how to do so? Thanks!
Answer: This problem involves the application of a probability measure over a union of non-disjoint sets, and so it can be solved by application of the inclusion-exclusion rule.
To facilitate this analysis, we will let $\mathcal{A}(x) \equiv (-\infty, x]$ denote the real numbers up to $x$ so that $\mathcal{A}(x_1) -\mathcal{A}(x_0) = (x_0,x_1]$ is a bounded interval.  (If you are dealing with a continuous random variable you do not have to worry about whether the ends of the intervals are open or closed.)  We will also simplify the problem by using a slight abuse of notation, treating each $\mathcal{A}(x_i)$ as a subset of $\mathbb{R}^n$ with an upper bound in dimension $i$ and free in the other dimensions.  This means that for an input vector $\mathbf{x} = (x_1,...,x_n)$ you have CDF values of the form:
$$\Phi(\mathbf{x}) = \mathbb{P} (\mathbf{X} \leqslant \mathbf{x}) = \mathbb{P} \Bigg( \bigcap_{k=1}^n \mathcal{A}(x_k) \Bigg).$$
You want to calculate the probability of a rectangular area, which can be written as an intersection of bounded intervals as $\mathcal{R}_n = \bigcap_{k=1}^n (\mathcal{A}(\bar{x}_{k}) -\mathcal{A}(\underline{x}_{k}))$, where you have lower and upper bounds $\underline{\mathbf{x}} < \bar{\mathbf{x}}$.  You want to be able to write the probability of this rectangular  event using your CDF $\Phi$.  To apply the inclusion-exclusion rule we will let $\mathfrak{N}_k$ denote the class of all subsets of $\{ 1,...,n \}$ with exactly $k$ elements.  Using this rule, and some other set algebra, we have:
$$\begin{equation} \begin{aligned}
\mathbb{P}(\mathcal{R}_n)
&= \mathbb{P} \Bigg( \bigcap_{k=1}^n (\mathcal{A}(\bar{x}_{k}) -\mathcal{A}(\underline{x}_{k})) \Bigg) \\[6pt]
&= \mathbb{P} \Bigg( \bigcap_{k=1}^n \mathcal{A}(\bar{x}_{k}) \Bigg) - \mathbb{P} \Bigg( \bigcap_{k=1}^n \mathcal{A}(\bar{x}_{k}) \cap \bigcup_{k=1}^n \mathcal{A}(\underline{x}_{k}) \Bigg)  \\[6pt]
&= \mathbb{P} \Bigg( \bigcap_{k=1}^n \mathcal{A}(\bar{x}_{k}) \Bigg) -
\sum_{k=1}^n \Bigg[ (-1)^{k-1} \sum_{\mathcal{D} \in \mathfrak{N}_k} \mathbb{P} \Bigg( \bigcap_{i \notin \mathcal{D}} \mathcal{A}(\bar{x}_{i}) \cap \bigcap_{i \in \mathcal{D}} \mathcal{A}(\underline{x}_i) \Bigg) \Bigg]  \\[6pt]
&= \Phi (\bar{\mathbf{x}}) -
\sum_{k=1}^n (-1)^{k-1} \sum_{\mathcal{D} \in \mathfrak{N}_k} \Phi(\mathbf{x_\mathcal{D}}),  \\[6pt]
\end{aligned} \end{equation}$$
where the data vector $\mathbf{x}_\mathcal{D}$ uses the lower bounds $\underline{x}_i$ for all $i \in \mathcal{D}$ and the upper bounds $\bar{x}_i$ for all $i \notin \mathcal{D}$.  This gives you a general mathematical form for calculating the probability of a rectangle directly using a multivariate CDF.

Special cases: Application of the general rule yields and expression with $2^n$ terms.  For small $n$ we can write this out explicitly without using summation notation and it is not too long.  For $n=2$ we get the special case:
$$\mathbb{P}(\mathcal{R_2}) = \Phi(\bar{x}_1, \bar{x}_2) -
\Phi(\underline{x}_1, \bar{x}_2) - \Phi(\bar{x}_1, \underline{x}_2) + \Phi(\underline{x}_1, \underline{x}_2).$$
For $n=3$ we get the special case:
$$\begin{equation} \begin{aligned}
\mathbb{P}(\mathcal{R_3}) &= \Phi (\bar{x}_1, \bar{x}_2, \bar{x}_3) -
\Phi(\underline{x}_1, \bar{x}_2,  \bar{x}_3) - \Phi(\bar{x}_1, \underline{x}_2,  \bar{x}_3) - \Phi(\bar{x}_1, \bar{x}_2,  \underline{x}_3) \\[4pt]
&\quad + \Phi(\underline{x}_1, \underline{x}_2, \bar{x}_3) + \Phi(\underline{x}_1, \bar{x}_2, \underline{x}_3) + \Phi(\bar{x}_1, \underline{x}_2, \underline{x}_3) - \Phi(\underline{x}_1, \underline{x}_2, \underline{x}_3).
\end{aligned} \end{equation}$$
For larger $n$ the number of terms increases exponentially and so it becomes cumbersome to write the expression out without using the summation notation in the general form.
Comment: Thanks for the clear example. The last special case really helped me see what was going on in those nested summations.
Just got a python code up and running and spitting out the correct results. Thanks again!
Comment: That's great that you got the code working.  The easiest way to code something like this is to sum over all the $2^n$ binary values of length $n$, using the binary values as representations of whether you are using an upper or lower bound for an argument in the CDF.
Answer: As suggested by @Ben, this problem boils down to an application of the inclusion-exclusion principle. For notational simplicity, let's replace $x_i^{lower}$ with $0$, and $x_i^{upper}$ with $1$, so that for example the vector $\vec{x}=(x_1^{lower},x_2^{upper},x_3^{upper},x_4^{lower})$ becomes $\vec{x}=(0,1,1,0)$.
Then the general formula for $\Phi^{upper}_{lower}(\vec{x}_{lower},\vec{x}_{upper})$ with $n$-dimensional $\vec{x}$ is:
$$\Phi^{upper}_{lower}\big((0,\dots,0),\ (1,\dots,1)\big) \ = \ \Phi^{upper}(1,\dots,1) \ - \sum_{x_1+\cdots+x_n=n-1} \Phi^{upper}(x_1,\dots,x_n) \ +  \cdots \\+ \ (-1)^{n-1} \cdot \sum_{x_1+\cdots+x_n=1} \Phi^{upper}(x_1,\dots,x_n) \ + \ (-1)^n \cdot\Phi^{upper}(0,\dots,0)$$
Comment: @FelipeD. My reference to $\vec{x}=(x_1^{lower},x_2^{upper},x_3^{upper},x_4^{lower})$, which I assume is what your confusion is about in your first comment, was just meant to show an example of the notation that I'm using, where it just so happens that $n=4$. You're correct that using this notation $\vec{x}_{lower}=(0,\dots,0)$ and $\vec{x}_{upper}=(1,\dots,1)$. You are also correct in your understanding of the summation notation, that it's referring to all combinations of $x_i$ such that the equality holds. This is a commonly-used notational convention.
Comment: Regarding your second comment, yes, all of the $x_i$ are either $0$ (denoting $x_i^{lower}$) or $1$ (denoting $x_i^{upper}$)
Comment: Thanks for clearing things up! But I'm still a bit confused.

First of all, if we only have two dimensions, $\vec{x}=(x_1,x_2)$. So I believe you meant to say that $\vec{x}_{lower}=(0,0)$ and $\vec{x}_{upper}=(1,1)$. Or more generally, for an n-dimensional case, $\vec{x}_{lower}=(0,...,0)$ and $\vec{x}_{upper}=(1,...,1)$.

But besides that, I'm still getting confused with the limits of the summations. What do you mean when you use $x_1+...+x_n=n-1$ as the **limits/bounds** of your summation? Is it summing all possible combinations where $x_1+...+x_n=n-1$ is true?
Comment: Furthermore, what are the terms $x_1, ..., x_n$ in your example? Are they ones or zeros? This seems a bit ambiguous. Thanks again for the help!


Can't build Gridsome website with Vue2 Smooth Scroll

Question: It works in develop mode but it does not build: 'ReferenceError: window is not defined'
I do understand it is a problem with SSR support, although it says it has support to it
I have tryed to implement some similar approaches of integration as seen here:
https://gridsome.org/docs/assets-scripts/#without-ssr-support
Import Vue-Navigation-Bar in Gridsome
I've tryed a lot of approaches in main.js and my template.vue files, but I'm failing to  understand the logic for adapting the solution perfectly.
My last approach which worked on develop:
On my template.vue file:

<ClientOnly>
Text click here
</ClientOnly>

Also have tryed to set 'container' option to '#app' or '#body' added to the body, but it didn't work not even in develop.
Answer: OK, I could find it here:
https://github.com/gridsome/gridsome/issues/180#issuecomment-513550238
It doesn't need <ClientOnly></ClienteOnly> tags in template.vue file
In main.js, I have made this changes:
//import vueSmoothScroll from 'vue2-smooth-scroll'
//Vue.use(vueSmoothScroll);

export default function (Vue, { router, head, isClient }) {
  ...
  if (process.isClient) {
    const vueSmoothScroll = require('vue2-smooth-scroll').default;
    Vue.use(vueSmoothScroll);
  }
}


Erro ao tentar executar uma classe

Question: Este é o meu primeiro post aqui no stack, estou tendo dificuldades executando essa classe no NetBeans. Estou usando a versao 1.8.0_40 do Java, já tentei pesquisar sobre alguma solução, mas não achei.
public class Dialog1 {

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        // TODO code application logic here
        JOptionPane.showMessageDialog(null, "Bem Vindo ao Java");
    }

}

ao compilar essa classe ele até da como sucesso, mas da uma mensagem de erro

run: Erro: Não foi possível localizar nem carregar a classe principal
  dialog1.Dialog1 Java Result: 1 CONSTRUÍDO COM SUCESSO (tempo total: 1
  segundo)

Alguém sabe o que pode estar acontecendo?
Comment: Sugiro tentar executar o programa por linha de comando. Se pela linha de comando não tiver problemas, é algo na IDE mesmo.
Comment: Este erro parece que está relacionado a configuração do projeto, se você criou um projeto Java, veja nas propriedades se está setado corretamente a jre correta para execução.
Answer: Pode ser que esteja faltando o import no começo do arquivo:
import javax.swing.JOptionPane;

Answer: Falta a importação da classe JOptionPane. Assim como já dito pelo Victor, você pode importá-la com import javax.swing.JOptionPane; no início do código.
Mas como nesse caso você só está usando ela uma vez, poderia fazer assim:
javax.swing.JOptionPane.showMessageDialog(null, "Bem vindo ao java!");

Nesse caso, está "chamando" a classe para ser usada apenas nessa linha. Se precisar dela de novo, terá que repetir esse comando.

Erro ao tentar executar uma classe


Durbin-Watson statistic = 2.601 - Can I still use multiple regression?

Question: My sample size is just 15. I have a Durbin-Watson statistic of 2.601 which may indicate negative autocorrelation.
First off, can I still use multiple regression analysis given the possibility that there may not be independence of observations?
Also, what does having a negative autocorrelation mean in relation to the data?
Answer: First off, this is a very small sample, and thefore you should not try large models on it and be cautious about interpretation of results.
Do you have the critical values to compare 2.601 to? They depend on model specification, and there is not enough information in your post to identify that. You should be able to find the relevant critical values either in your programme output or by searching for "Durbin Watson critical values" online.
If 2.601 appears not to be significantly different from 2 (which it should be under the null), then you could think this is due to chance and ignore it. If 2.601 appears to be significantly different from 2, then your model is misspecified (violation of i.i.d. errors) and OLS estimators will not have all the nice properties they otherwise would.
Also, be careful with independence: it's not independence of observations but independence of errors that is relevant for OLS estimation.
A negative autocorrelation in model errors means your model is misspecified. Perhaps a variable is missing (e.g. lag of the dependent variable).
Comment: What would you recommend that is targeted to the issues faced by the OP with 15 obs?
Comment: @DJohnson, With just 15 obs. I would try to find out as much as possible about the subject matter and use that knowledge in model building.
Comment: To Richard Hardy's point, with only 15 observations you will not be able to fit models such as ARIMA, Box-Jenkins or VAR. After finding the critical pseudo-F value for your model -- the DW tables are readily available online or in many texts -- you fine that the errors are autocorrelated, then your next step should be to take the first difference of your response variable and re-estimate. If your data is quarterly, in theory at least, you could test for seasonality. How many predictors do you have? This will limit model fitting as you can easily and quickly exhaust the degrees of freedom
Comment: @DJohnson, why difference? Differencing should be justified by a unit-root test, not by Durbin-Watson statistic. These are two different things. A stationary, non-unit-root series may have a Durbin-Watson statistic far away from 2.
Comment: I assumed that first differences were a solution for autocorrelated errors. Based on your comment, it sounds like that was wrong. Tell me something, is a unit-root test even possible with 15 observations? In theory it is, but would it be a reliable test with so little information?
Comment: I don't know how a unit-root test (say, the ADF test) would perform in such a small sample, but as you say, perhaps not very good. However, differencing is only a solution against a unit root, but not against autocorrelation in general. Overdifferencing (differencing when there is no unit root) brings new problems. Meanwhile, autocorrelation can be dealt with by changing the model specification or allowing the model errors to follow and ARMA pattern.
Comment: But wouldn't an ARMA pattern be too data intensive in this case with only 15 obs?
Comment: @DJohnson, for the particular sample, it could be. I listed the options for dealing with autocorrelation to illustrate what can be done in general, not necessarily in this case.


Como fazer INSERT em três tabelas com Stored Procedure?

Question: Preciso realizar um insert em três tabelas relacionadas na mesma query.  Tenho o seguinte cenário: Cidade, Estado e Pais
Como posso construir uma stored procedure em Sql Server para isso?
Answer: Existem várias formas ! Em uma PROCEDURE você pode criar a sua lógica .
Vou dar um exemplo, porém não entendi exatamente o que você quer fazer e não tenho a estrutura da sua tabela
Com o seguinte esquema:
create table pais(cod_pais int identity primary key,nome nvarchar(50))
go
create table estado(cod_estado int identity primary key,cod_pais int foreign key references pais,nome nvarchar(50))
go
create table cidade(cod_cidade int identity primary key,cod_estado int foreign key references estado,nome nvarchar(50));
go

Você pode criar uma procedure que insere pais, estado e cidade juntos :
create procedure InserirTudoJunto @nome_pais nvarchar(50) , @nome_estado nvarchar(50) , @nome_cidade nvarchar(50)
as
begin
  begin transaction t
    begin try
        declare @ids table (cod_pais int,cod_estado int);
        insert into pais (nome) output inserted.cod_pais into @ids(cod_pais) values ('Brasil');
        insert into estado (nome,cod_pais) output inserted.cod_estado into @ids(cod_estado) values (@nome_estado,(select cod_pais from @ids));
        insert into cidade (nome,cod_estado) values(@nome_cidade,(select cod_estado from @ids where cod_estado is not null));
        commit transaction t
    end try
    begin catch
        rollback transaction t
    end catch
end

E agora pra rodar a procedure é só executar
 exec InserirTudoJunto 'Brasil','Minas Gerais','Belo Horizonte'

Obs:quando uma ou mais operações de insert/update/delete dependem de outras, pra não correr o risco que uma funcione e a outra não ,  é importante que elas sejam feitas dentro de uma transaction.


Reading data from one-to-many relationship SQL table into my model

Question: I have below two classes which represent my SQL tables (generated by ADO.net entity data model):
public partial class Parent
{
    public Parent()
    {
        this.Students = new HashSet<Student>();
    }

    public int Parent_Id { get; set; }
    public string Parent1_Last_Name { get; set; }
    public string Parent1_First_Name { get; set; }
    public virtual ICollection<Student> Students { get; set; }
}

public partial class Student
{
        public int Student_Id { get; set; }
        public string Student_Last_Name { get; set; }
        public string Student_First_Name { get; set; }
        public int Parent_Id { get; set; }
        public virtual Parent Parent { get; set; }
}

Now I am trying to read the data from my tables in a method as below:
var parent = new Parent();
var students = new List<Student>();

using (var dc = new SchoolDataEntities())
{
    students = dc.Students.Where(s => s.Parent_Id.Equals(parentId)).ToList();
    parent = dc.Parents.Where(p => p.Parent_Id.Equals(parentId));
    parent.Students = students;
}

I am getting a run-time "Invalid Cast" exception error when I reading from Parent table (Students table is working fine).

Error: System.InvalidCastException: 'Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[SchoolApplication.Parent]' to type 'SchoolApplication.Parent'.'

Someone please educate me what I was doing wrong?
Comment: You need to materialize the query with `dc.Parents.Where(p => p.Parent_Id.Equals(parentId)).FirstOrDefault()` or `dc.Parents.Where(p => p.Parent_Id.Equals(parentId)).SingleOrDefault()`.
Answer: This part is your problem:
parent = (Parent)dc.Parents.Where(p => p.Parent_Id.Equals(parentId));

The output of "Where" is a collection of Parent rather than just a single parent.
You can use "Single" or "First" rather than "Where" in this case.
Answer: This part of code returns IQueryable collection instead of single Parent model:
parent = dc.Parents.Where(p => p.Parent_Id.Equals(parentId));

For this reason, you need to materialize the query to Parent model with either FirstOrDefault() or SingleOrDefault():
parent = dc.Parents.Where(p => p.Parent_Id.Equals(parentId)).FirstOrDefault();

parent = dc.Parents.Where(p => p.Parent_Id.Equals(parentId)).SingleOrDefault();

Related: Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[]' using linq lambda expression


Como enviar valores da Activity para webview cordova?

Question: Como eu faço para enviar dados da Activity e resgatar na WebView com javascript da index.html do cordova/Phonegap
Answer: Uma vez que você já possua sua WebView em ação, você pode executar um método JavaScript dentro dela assim:
webView.loadUrl("javascript:foo('" + bar + "')");

E dentro do index.html tem a implementação do método foo(), recebendo um parâmetro.
Comment: Ok @Paulo Rodrigues! funcionou belezinha, muito obrigado.


Divided differences and differentiability

Question: Let  $f: R \rightarrow R$, $y_0,y_1,y_2 \in R$.   We define divided differences:
$$[y_0;f]=f(y_0),$$
$$[y_0,y_1;f]=\frac{f(y_1)-f(y_0)}{y_1-y_0},$$
$$[y_0,y_1,y_2;f]=\frac{[y_1,y_2;f]-[y_0,y_1;f]}{y_2-y_0}.$$
Assume that for each $x \in R$ and  $\varepsilon>0$ there exists a $\delta>0$ such that $$|[y_0,y_1,y_2;f]-[y_0',y_1',y_2';f]|< \varepsilon$$ for arbitrary sets $\{y_0,y_1,y_2\}$, $\{y_0',y_1',y_2'\}$ of distinct points such that $|y_i-x|<\delta$, $|y_i'-x|<\delta$ ($i=0,1,2$).
Is it $f$ of class $C^2$ ?
Comment: I personally like the pointwise version more: is $\displaystyle f''(x)=\lim_{y_1,y_2,\to x}[x,y_1,y_2;f]$ whenever the limit exists? If the answer is yes, the continuity of $f''$ in your case follows at once. But maybe you ask in this form because you have a counterexample to the pointwise version?
Comment: @LVK: a) I think it should be $\frac12f''(x)$? b) I don't understand your comment. In the first-order version, $f'(x)=\lim_{y\to x}[x,y;f]$ is just the definition of the derivative, which doesn't guarantee continuity -- why is this different in the second-order version? Why would $\displaystyle f''(x)=\lim_{y_1,y_2,\to x}[x,y_1,y_2;f]$ fail to hold for discontinuous second derivative?
Answer: A. First order case. By definition of the first derivative, we have
$$
[x,z;f]\to f'(x),
\qquad\textrm{as}\quad z\to x,
$$
at each $x$. In the following, let us fix $x$. By assumption, for any $\varepsilon>0$, there exists $\delta>0$ such that
$$
|[x,z;f]-[y,t;f]|<\varepsilon,
\qquad\textrm{for all}\quad z,y,t\in B_\delta(x),
$$
where $B_\delta(x)=\{t:|t-x|<\delta\}$.
Now we fix $\varepsilon>0$, and will show that with $\delta>0$ given by assumption as above, it holds for each $y\in B_\delta(x)$ that
$$
|f'(x)-f'(y)|<3\varepsilon.
$$
To prove the claim, first, pick $z\in B_\delta(x)$ satisfying
$$
|[x,z;f]-f'(x)|<\varepsilon.
$$
Then, pick $t\in B_\delta(x)$ satisfying
$$
|[y,t;f]-f'(y)|<\varepsilon.
$$
Combining the above inequalities, we get the claim.
B. Second order case. One can prove as in Einar's answer that the divided differences converge to some function $g$ pointwise. Then the argument from Part A shows that $g$ is continuous. So the only remaining question is the existence of $f''$ and whether or not $f''=2g$.
Let $G$ be a function satisfying $G''=2g$.
Then it is well known that the second order divided differences of $G$ converge pointwise to $g$. Hence by linearity, the same divided differences of $u=f-G$ converge pointiwse to $0$. If we could show that $u''$ exists everywhere and $u''\equiv0$, this would imply that $f''$ exists and $f''=2g$ everywhere.
Therefore from now on, we can assume $g\equiv0$. We have
$$
[x,y,z;f]=\frac{[x,y;f]-[y,z;f]}{x-z}=\frac{[y,x;f]-[y,z;f]}{x-z}\to0,
$$
as $\max\{|x-y|,|z-y|\}\to0$, for each $y$. This means
$$
[y,x;f]-[y,z;f]=o(\delta),
$$
with the $o(\delta)$-term being uniform in $x,z\in B_\delta(y)$. In particular, $[y,x;f]$ is convergent as $x\to y$, and so $f'(y)=[y,y;f]$ exists everywhere. Now the idea is to consider
$$
[x,x_1,y;f]+[x,y_1,y;f]=\frac{[x,x_1;f]-[y,x_1;f]+[x,y_1;f]-[y,y_1;f]}{x-y},
$$
which goes to $0$ as $x_1,y_1,y\to x$,
and somehow take the limits $x_1\to x$ and $y_1\to y$, before taking the other limits.
C. Proof that $f''$ exists and $f''\equiv0$. Let $x$ be a point and let $\varepsilon>0$.
Then pick $\delta>0$ such that $|[x,z,y;f]|<\varepsilon$ for any $y,z\in B_\delta(x)$.
We will show that
$$
\left|\frac{f'(x)-f'(y)}{x-y}\right|<5\varepsilon,
\qquad\textrm{for any}\quad
y\in B_\delta(x)\setminus\{x\}.
$$
To this end, choose $x_1,y_1\in B_\delta(x)$ such that
$$
|f'(x)-[x,x_1;f]|<\varepsilon|x-y|,
\qquad
|f'(y)-[y_1,y;f]|<\varepsilon|x-y|,
$$
and that
$$
|[x,y_1;f]-[x_1,y;f]|<\varepsilon|x-y|.
$$
This is possible because $[x,x_1;f]\to f'(x)$ as $x_1\to x$, $[y,y_1;f]\to f'(y)$ as $y_1\to y$, and $[z,t;f]$ is a continuous function of $z$ and $t$.
Note the higher order smallness in the right hand sides, which formalizes "taking the limits $x_1\to x$ and $y_1\to y$ first".
Finally, we use the simple decompositions
$$
f'(x)
=
\left(f'(x)-[x,x_1;f]\right)
+\left([x,x_1;f]-[x_1,y;f]\right)
+[x_1,y;f],
$$
and
$$
-f'(y)
=
-[x,y_1;f]
+\left([x,y_1;f]-[y_1,y;f]\right)
+\left([y_1,y;f]-f'(y)\right),
$$
to conclude that
$$
\left|\frac{f'(x)-f'(y)}{x-y}\right|
<
\varepsilon+|[x,x_1,y;f]|+\varepsilon+|[x,y_1,y;f]|+\varepsilon
<5\varepsilon.
$$
Comment: @Graphth: Partly because of the bounties, partly because they are intrinsically interesting. The fact that they have bounties means maybe something interesting about them. In any case, what is the point of bounty if it is not for attracting good answers? On the other hand, you can check from my user page that I spent a lot of effort on questions without bounties as well.
Comment: Timur, do you only answer questions with bounties?  I'm joking but I noticed recently you had the most reputation in the last week, and it was because you had collected 3 bounties for a total of 1100 reputation.  And, here you are again.
Comment: @Graphth: It is worth mentioning that many of the bounties are given by some experienced users other than the asker, and many of them have an eye towards how to improve the site, by diversifying and deepening the collected knowledge on the site. When I have sufficient reputation I will use my reputation for this purpose as well.
Comment: @joriki: No need to delete the comments. I think they can be useful to read.
Comment: Why are only $z,y,t$ freely chosen and $x$ fixed? Wouldn't the first-order analogue of the statement in the question have all four of them within $\delta$ of some common value?
Comment: @joriki: Yes, but having $x$ fixed is assuming less than what you wrote, right?
Comment: Sorry, I wrote that comment before you finished the answer, and I thought you were trying to disprove the statement, like Einar. Since you're trying to prove it, of course you're right and you can fix $x$. Another question: Why can you assume $g\equiv0$ by subtracting $G$ with $G''=g$ from $f$ *before* you prove $g=f''$?
Comment: @joriki: Because then it would prove that $(G-f)''=0$, which means $f''=G''=g$. I realize that you don't have to do this, it just simplifies some formulas.
Comment: I don't understand. How do you know anything about $g$ *before* you prove $g=f''$? At that point you don't know anything about $g$ -- how can *assuming* that it's identically zero prove that $(G-f)''=0$? For all you know at that point, it might never be identically zero, no matter what you subtract from $f$. Am I missing something? (I'm familiar with this general technique of subtracting something out to reduce to a case where something is zero; I'm just saying I don't see how it applies in this case.)
Comment: @joriki: We know something about $g$, that is the pointwise limit of the second differences of $f$. On the other hand, the second differences of $G$ converge to $g$ by a standard result. Then the second differences of $u=f-G$ will converge to $0$.
Comment: @timur I'm mostly joking.  I don't mind if you answer questions with bounties.  In fact, the fact that you can answer so many questions with bounties is very impressive.
Comment: I see; I didn't realize you were taking that result as given. What threw me off was "Now the question is if $g=f''$". So if I understand correctly, what you mean there is mainly whether $f''$ exists, and you're taking as given that if it does exist then it equals $g$? Perhaps you should clarify that. One more question (sorry about all the questions; it's a great proof! :-) -- when you use the continuity of $[z,t;f]$ to fulfill $|[x,y_1;f]-[x_1,y;f]|<\varepsilon|x-y|$, don't you have to adjust $\delta$? Why does this work with the $\delta$ you chose further up?
Comment: On a minor note, $g$ actually converges to $f''/2$.
Comment: @joriki: This result is not related to the choice of $\delta$. Choose $x_1$ close enough to $x$, and $y_1$ close enough to $y$, and use $[x,y_1;f]-[x_1,y;f]=[x,y_1;f]-[x,y;f]+[x,y;f]-[x_1,y;f]$. I will clarify the point about $g=f''$ tomorrow. Thanks for the suggestion!
Comment: To @joriki's comment just before my last one: Thanks for spotting this!
Comment: On $\delta$: Ah, I see, makes sense. Shall we remove all those comments? A long thread like that tends to throw doubt on a proof for the casual reader, and all my doubts have been removed now :-) About the factor of $2$: Well, I had to spot *something* in asking so many questions ;-)
Comment: Nicely done! Although I have to admit $\epsilon$s and $\delta$s tend to make me a bit dizzy. I think this argument can be generalised to prove that $[y_0,\ldots,y_n;f]\rightarrow g_n(x)$ when $y\rightarrow x$ makes $f\in C^n$. E.g. one may note that $[y_0,\ldots,y_n;f]$ extends to a continuous function on $\mathbb{R}^{n+1}$ which is symmetric in the $y$s.
Comment: @Einar: It would be good to have a general argument for higher order cases. It seems plausible, but I don't know how to do it nicely (maybe induction on $n$?).
Comment: Your rewriting of the $2g=f''$ part doesn't correspond to what I thought I'd understood your argument to be. I agree that you can prove as in part A that $g$ converges to a continuous function; you don't have to take that as given. What I believe you're taking as given is that *if* $f''$ exists, then it is $2g$. Without that, I don't see how your subtraction argument gets off the ground. Above you had written "the second differences of $G$ converge to $g$ by a standard result". Presumably this is by virtue of $G''=2g$, and then the same result yields $f''=2g$ if $f''$ exists.
Comment: @joriki: I think I misunderstood your earlier comment. So I believe actually there is nothing taken as given. Please have a look at the update.
Comment: I'm afraid we're still taking past each other. By "taking for given" I mean nothing more than what you meant by "a standard result", or by "it is well known" in the update. You're taking it as well known that if $G''=2g$, then the second-order divided differences of $G$ converge to $g$. All I'm saying is that if you do, then there's no need to prove $f''=2g$, since as long as $f''$ exists, it is equally well known that its second-order divided differences converge to $f''/2$, and since we already know they converge to $g$, that implies $f''=2g$.
Comment: @joriki: Ok. I think now I understand what you meant. I leave the post as it is, even though some of the steps seem to be redundant as you observe.
Answer: I'll try to provide a proof of the general case $[y_0,\ldots,y_n;f]$. This proof has many similarities to that of timur, but I'll formulate things more in terms of limits rather than using $\epsilon$s and $\delta$s. My other answer was wrong, but I leave it since it had some useful bits, one of which I'll redo here.
Hope I didn't overlook anything grave this time. However, I'm sure I've taken a few technical short-cuts which could need filling in: the lemma provided at the end is an attempt at that.
Notation: Let $R^{n+1}_k\subset\mathbb{R}^{n+1}$ consist of the points $y=(y_0,\ldots,y_n)$ for which at most $k$ coefficients have the same value: i.e. $R^{n+1}_1$ are those where all $y_i$ are distinct, while $R^{n+1}_{n+1}=\mathbb{R}^{n+1}$. We then have $[\cdot;f]:R^{n+1}_1\rightarrow\mathbb{R}$ defined as
$$
[y_0,\ldots,y_n;f]=\frac{[y_1,\ldots,y_n;f]-[y_0,\ldots,y_{n-1};f]}{y_n-y_0}
\tag{1}
$$
for $y\in R^{n+1}_{1}$: generalised from the cases $n=0,1,2$ stated in the original problem.
Definition: We say that a function $f$ is $\mathcal{F}^n$ if for any $y,y'\in R^{n+1}_1$,
$$\lim_{y,y'\rightarrow x^{[n+1]}}\Big|[y;f]-[y';f]\Big|=0\tag{2}$$
where, for $x\in\mathbb{R}$, the point $x^{[n+1]}=(x,\ldots,x)\in\mathbb{R}^{n+1}$. This is just the equivalent of the $\epsilon$-$\delta$ formulation in terms of limits.
(i) Assume $f$ is $\mathcal{F}^n$. If we take any sequence $y^{(k)}\in R^{n+1}_1$ which converges to $x^{[n+1]}$, then $[y^{(k)};f]$ becomes a Cauchy sequence: i.e. for $p,q\ge k$, $\big|[y^{(p)};f]-[y^{(q)};f]\big|\rightarrow0$ as $n\rightarrow\infty$. Hence, $[f^{(k)};f]$ must converge. Let's denote the limit $[x^{[n+1]};f]=g_n(x)$.
(ii) Let's prove by induction that $[y_0,\ldots,y_n;f]$ is symmetric in the $y_i$. Obviously, it holds for $n=0,1$. Assume it holds for $n<N$. Setting $n=N\ge2$, let $y=(u,v,A,w)\in R^{n+1}_1$ where $A=(a_1,\ldots,a_{n-2})$ (possibly empty). We then have
$$
\begin{split}
[u,v,A,w;f]=&\frac{[u,v,A;f]-[v,A,w;f]}{u-w}\\
=&\frac{1}{u-w}\Big([u,A,v;f]-[v,A,w;f]\Big)\\
=&\frac{1}{u-w}\left(\frac{[u,A;f]-[A,v;f]}{u-v}-\frac{[v,A;f]-[A,w;f]}{v-w}\right)\\
=&\frac{[u,A;f]}{(u-v)(u-w)}+\frac{[v,A;f]}{(v-u)(v-w)}+\frac{[w,A;f]}{(w-u)(w-v)}
\end{split}
$$
which is symmetric in $u,v,w$. From the first step, we also see that it must be symmetric in permutations of $v,A$. These symmetries generate the whole permutation group, so symmetry also holds for $n=N$.
(iii) Again, we use induction, assuming the following holds for $n<N$: A function $f$ is $\mathcal{F}^n$ if and only if it is $C^n$, i.e. $\mathcal{F}^n=C^n$: in particular, it is also $\mathcal{F}^k$ for all $k<n$. The definition of $[y;f]$ for $y\in R^{n+1}_1$ may be extended continuously to all $y\in\mathbb{R}^{n+1}$. Moreover, $g_n(x)=f^{(n)}(x)/n!$ where $f^{(n)}$ is the $n$th derivative.
For $n=0,1$, the asumption holds true. So we let $n=N\ge2$.
In order to utilise the induction hypothesis, we first need to show that when $f$ is $\mathcal{F}^n$, it is also $\mathcal{F}^{n-1}$. To do this, we rewrite equation (1)
$$(u-v)[u,A,v;f]=[u,A;f]-[A,v;f]$$
for $A=(a_1,\ldots,a_{n-1})$. For $u=(u_1,\ldots,u_n)$ and $v=(v_1,\ldots,v_n)$, both in $R^n_1$, we then get
$$
\begin{split}
(u_1-v_1)[u_1,\ldots,u_n,v_1;f]&+(u_2-v_2)[u_2,\ldots,u_n,v_1,v_2;f]\\
&+\cdots+(u_n-v_n)[u_n,v_1,\ldots,v_n;f]\\
=&[u_1,\ldots,u_n;f]-[v_1,\ldots,v_n;f]\\
\end{split}\tag{3}
$$
where $u,v\rightarrow x^{[n]}$ leads to
$\big|[u;f]-[v;f]\big|\rightarrow0$,
i.e. the definition of $f$ being $\mathcal{F}^{n-1}$.
For any $y\in R^{n+1}_n$, i.e. not all $y_i$ are equal, we can rearrange the $y_i$ to make $[y;f]=[u,A,v;f]$ where $u\not=v$ and use (1) to get $[y;f]$ expressed in terms of $[u,A;f]$ and $[A,v;f]$, both of which are defined on the whole $\mathbb{R}^n$. This provides us with an extension of $[y;f]$ to all $y\in R^{n+1}_n$.
Finally, in equation (3), we let $u=x^{[n]}$, $v=x'^{[n]}$: by continuity, we can do that, or alternatively we can take limits $u\rightarrow x^{[n]}$ and $v\rightarrow x'^{[n]}$ (and we take these limits before the later limit). Dividing by $x-x'$ on both sides then gives
$$
\frac{g_{n-1}(x)-g_{n-1}(x')}{x-x'}
=[x,\ldots,x,x';f]+\cdots+[x,x',\ldots,x';f]
$$
where $x'\rightarrow x$ gives $g_{n-1}'(x)=n\cdot[g_n(x)]$. Hence, $g_n(x)=f^{(n)}/n!$.
The only remaining thing to point out is that the final extension of $[y;f]$ from $y\in R^{n+1}_n$ to all of $\mathbb{R}^{n+1}$ is continuous. This basically follows from the definition, but we have to use the following lemma (which I have implicitly used further up as well), to ensure the limit in (2) holds true even if the sequence even if $y\in R^{n+1}_n$ rather than $R^{n+1}_1$.
Lemma: Given $x,v_i,u^{(i)}_j\in\mathbb{R}$ so that $v_i\rightarrow x$ and $u^{(i)}_{j}\rightarrow v_i$, then we can pick $j_i$ so that $u^{(i)}_{j_i}\rightarrow x$.
One use of the lemma is that if $y^{(i)}\in R^{n+1}_n$, $z^{(i,j)}\in R^{n+1}_1$, we can set $v_i=[y^{(i)};f]$, $u^{(i)}_j=[z^{(i,j)};f]$, and replace the limit of $[y^{(i)};f]$, which is taken in $R^{n+1}_n$, with a limit taken in $R^{n+1}_1$.
Answer: NB: The main argument in this answer, that the clause does not imply $C^2$, is wrong.
I'll leave the answer since it contains some useful arguments about the existence of a limit ($[y_0,\ldots,y_n;f]\rightarrow g_n(x)$ as $y\rightarrow x$) as well as some examples high-lighting the difference between having a derivative and it being continuous.

As has been commented already, the expression is essentially the definition of second derivative, however there are some technical problems (which I realised from the comment by timur).
For any $n$, having
$$\big|[y_0,\ldots,y_n;f]-[y'_0,\ldots,y'_n;f]\big|<\epsilon$$
for all $y_i, y'_i$ sufficiently close to $x$, guarantees that there is a limit $g_n(x)$ with
$$\big|[y_0,\ldots,y_n;f]-g_n(x)\big|<\epsilon.$$
E.g. if you pick a sequence of $n+1$-tuples $y^{(k)}=(y^{(k)}_0,\ldots,y^{(k)}_n)$ with $|y^{(k)}_i-x|<\delta_k$, where $\delta_k\rightarrow0$ as $\epsilon_k\rightarrow0$, by plugging in $y=y^{(k)}$ and $y'=y^{(l)}$ for some $l>k$, we find that $[y^{(k)};f]$ is a Caucy sequence, so we know it converges.
I'm fairly confident the limiting function will be be $g_n(x)=f^{(n)}(x)/n!$, where $f^{(n)}$ is the $n$th derivative, provided the $n$th derivative exists. (I thought I had an example where the limit exists but $f$ does not have $n$th derivative, which I claimed in a previous version of this answer, but this was not correct.)
For $f$ to be $C^n$, a function must not only have an $n$th derivative, but it must be continuous. This need not be the case, and it fails already at $n=1$ with $f(x)=x^2\sin(1/x)$ (setting $f(0)=\lim_{x\rightarrow 0}f(x)=0$). This has $f'(x)=0$ due to the $x^2$ factor. Accordingly, $[y_0,y_1;f]\rightarrow 0$ when $y_i\rightarrow 0$. However, $f'(x)=2x\sin(1/x)-\cos(1/x)$ which is not continuous at $x=0$ as $\cos(1/x)$ fluctuates between $1$ and $-1$.
For $n=2$, I previously used $f(x)=x^3\sin(1/x)$ as a counterexample: this is $C^1$, but does not have a second derivative at $x=0$. However, my claim that get$[y_0,y_1,y_2;f]\rightarrow 0$ as $y_i\rightarrow 0$ does not seem to be correct.
Instead, for $n=2$, we can set $f(x)=x^4\sin(1/x)$. This has second derivative defined everywhere, but which is not continuous.
My main doubt now is that it seems to me $|[y_0,\ldots,y_n;f]-g_n(x)|<\epsilon$ not only ensures that $f$ has an $n$th derivative in $x$, but that it also bounds the $n$th derivative in a neighbourhood of $x$ (by the same $\epsilon$--$\delta$ limit). Hence, the proposal in the original problem statement should be true.
Comment: In the counterexample, what about the value $f'(0)$? It seems that if the divided differences converge, it should be $f'(0)=0$, but I cannot see it from the analytic expression.
Comment: How do you get $[y_0,y_1,y_2;f]\rightarrow 0$ as $y_i\rightarrow 0$ in the last paragraph? As you say, $f'$ fluctuates between $1$ and $-1$; and the terms in the numerator of $[y_0,y_1,y_2;f]$ approximate $f'$; then why does $[y_0,y_1,y_2;f]$ converge? Also note that my comment under the question was only directed at LVK's "pointwise version"; I didn't say that the version in the question is just the second derivative, and I doubt that it is, because of the freedom in choosing $y_0$.
Comment: @timur In the first counterexample, although $f'(x)$ is discontinuous at $x=0$, due to the $x^2$ factor we get $f'(0)=0$. For the second counterexample, this is more problematic as $f'(x)$ contains $x\cos(1/x)$, so $f'(x)$ is continuous but not differentiable at $x=0$; however, $f(x)/x^2\rightarrow0$ as $x\rightarrow0$. Will edit the answer.
Comment: @timur Thanks for noting, by the way. Of course, this means that not only does $f$ (from the original problem) not have to be $C^2$, but unlike what I originally wrote it does not have to have a second derivative everywhere.
Comment: Isn't it $f'(x)=2x\sin(1/x)-x\cos(1/x)$ (with $x$ in front of $\cos$)? I think there is no question on the existence of the derivative though.
Comment: @timur For $f(x)=x^2\sin(1/x)$, you get $f'(x)=2x\sin(1/x)-\cos(1/x)$ since the derivative of the $1/x$ inside the sinus is $-1/x^2$.
Comment: @joriki I realise I may have been too fast in asserting $[y_0,y_1,y_2;f]\rightarrow0$ when $f(x)/x^3$ is bounded. I noted that $[ty_0,ty_1,ty_2;f]/t$ is bounded when $t\rightarrow0$, but see now this is not enough. As for the limit $g_2(x)=f''(x)/2$, I know this claim was not in the original question; yet, I think that if $f$ is twice differentiable at $x$ (even if not $C^2$), it should have to be true. Will have to work more on the proof though.
Comment: @Einar: Yes, certainly $g_2(x)=f''(x)/2$ if that exists, so the expression in the question is *at least* as strong as the definition of the second derivative. "As has been commented already, the expression is essentially the definition of second derivative" sounded as if it can't guarantee continuity because it's *nothing more* than the definition of the second derivative -- I just wanted to clarify that that's not what my comment under the question was meant to imply.
Comment: @joriki Sorry if my comment was unclear. What I was thinking of was actually the contrary: that, much like for the case of $n=1$, the definition of the second derivative is close to being a special case of the assumed limit. However, at that time I had not yet realised that the assumption also had implication for the second derivatives in a neighbourhood of $x$. And, of course, the second derivative is not defined from a single limit defined on $f$, but is based on $f'$, which is what makes the problem technically more challenging.