Adding functionality to a form button that would load user details / corresponding field data for "autofill"

Question: I have a form that has a address field holding inputs for:
name
address
phone etc.
I've added a button on this form/field: Load my data which I would like to load user details/data.
On click it should load a corresponding address field from user's profile by ajax and use it to fill in form fields.
Form can have multiple address fields so it should know which address field needs to filled with user data.
Button isn't shown to anonymous users of course.
Answer: Take a look at how Commerce Addressbook solves these same requirements: https://www.drupal.org/project/commerce_addressbook.
There is a demo video on the project page: https://commerceguys.com/blog/commerce-module-tuesday-commerce-addressbook.
I think if you dig through the module code of that module, you'll find all the logic and code examples you'll need to pull off a similar solution on your custom form.
If you want to see this in action on a local setup, I recommend installing commerce kickstart with commerce addressbook to see how the addresses are organized.
Good luck, Jason
Comment: Hi! Almost same idea/problem but a bit different solution. Codebase was rather extensive but that figures since the whole solution is a bit more wider than mine. Therefore I couldn't really understand what was going on. However, I've managed to create ajax button that already removes the address field but doesn't replace it since I don't know how I could create a renderable array of user profile field?


Drupal 7 Ajax Forms - select element

Question: I've got a custom module form in Drupal 7. The code looks like this:
function form_example_dynamic_form($form, &$form_state) {

$form['tables'] = array(

        '#type' => 'select',
        '#options' => drupal_map_assoc(array("2012", "2013")),
        '#title' => t('Select year:'),

        '#ajax' => array(
            'callback' => 'form_example_dynamic_myajax',
            'wrapper' => 'abcd',
            'effect' => 'fade',
            'method' => 'replace',
            ),

       );

 return $form;
 }

 function form_example_dynamic_myajax($form, $form_state) {
     return $form_state['values']['tables'];
 }

So this simple code should update #abcd tag with the value of the 'tables' select. And the problem is that it works only for the first selection. If I chose 2013 it returns "2013" text in my #abcd tag. But, when I chose 2012, an #abcd tag stays unchanged. It still apperas 2013.
Here is the example: http://kuzaj.yamandi.com/pl/form_example_dynamic
Does anyone has any idea how to solve it?
Answer: The problem is that Drupal is unable to find the element #abcd in the further calls.
Since you are returning the values alone, it will replace the element #abcd with the value; so the element #abcd will be removed from the document, and it will not be available for further processing. That's why it is not updating the values in the second time.
To overcome this in form_example_dynamic_myajax(), you need to return the values like in the following code.
 function form_example_dynamic_myajax($form, $form_state) {
   return '
' . $form_state['values']['tables'] . '
';
 }

Comment: Thank you for explanation. That makes sense. I assume my code isn't exacly what it should be. Is there a way to change the code that #abcd tag always stays and only the content of it is changed?
Comment: you can specify the method as **html** instead of **replace** for method in ajax declaration.
Comment: THANK YOU!!! Everything works perfect. Just like I should. Thank you very much for support.

Drupal 7 Ajax Forms - select element


Fundamental theorem of Calculus: $\frac{d}{dx} \int_{-x}^{x} \frac{1}{3+t^2} \ dt$ Possible textbook mistake

Question: using the FTC we are supposed to evaluate
$$
\frac{d}{dx} \int_{-x}^{x} \frac{1}{3+t^2} \ dt
$$
and the answer, the textbook says, should be a constant. When I evaluate that derivative I get
$$
\frac{d}{dx} \int_{-x}^{x} \frac{1}{3+t^2} \ dt = \frac{d}{dx} \int_{-x}^{0} \frac{1}{3+t^2} \ dt + \frac{d}{dx} \int_{0}^{x} \frac{1}{3+t^2} \ dt\\
= - \frac{d}{dx} \int_{0}^{-x} \frac{1}{3+t^2} \ dt + \frac{d}{dx} \int_{0}^{x} \frac{1}{3+t^2} \ dt\\
= - \frac{1}{3+(-x)^2} \cdot (-1) + \frac{1}{3+x^2}\\
= \frac{1}{3+x^2} + \frac{1}{3+x^2}\\
= \frac{2}{3+x^2}
$$
but I suppose that the textbook is expecting the answer $0$ (which for me is not correct since the chain rule, on the first term, makes the fraction not cancel). Is there really a mistake?
Thank you.
Comment: This looks correct to me, and makes sense (for large $x$ you only add a little bit of area when you increase $x$ a little bit).
Comment: I believe your answer is right. Intuitively, the answer cannot be zero because by increasing $x$, you extend the area of integration _both_ to the right _and_ to the left. Since the integrand is positive, the value of the integral must grow.
Comment: Another way to see that it is correct is to use that the integrand is even, $f(t) = f(-t)$ , so $F(x) = \int_{-x}^x f(t) dt = 2\int_0^x f(t)dt$ giving $\frac{d}{dx}F(x) = 2f(x)$
Comment: @AndréNicolas I did put the minus sign. Can you please review my answer?
Answer: Your answer is correct. Note if the textbook was correct then the integral would be independent of $x$: clearly this is false because the function is always positive so increasing $x$ will add more to the integral.
Answer: $$
\frac{d}{dx} \int_{-x}^{x} \frac{1}{3+t^2} \ dt
= 1\frac{1}{3+x^2}+1\frac{1}{3+(-x)^2}=\frac{2}{3+x^2}$$
Note that $$
\frac{d}{dx} \int_{g(x)}^{f(x)} h(t) \ dt=f'(x)h(f(x))-g'(x)h(g(x))$$


What link is this link?

Question: I am trying to identify the following link

SnapPy is not able to identify it.
Please let me know if you have the answer.
Many thanks
Answer: The census on SnapPy only has knots and links identified up to 16 crossings I believe, so since your link has 22 crossings, there is no chance of an identification.  But it is not hard to see that this is a satellite link of the Whitehead link (Wikipedia, Knot Atlas, Wolfram). Image below is from Knotatlas.

The standard Whitehead link looks like a circle with a figure 8 overlaid, then made alternating.  The circle component, we can see was replaced with the unlink on two components with $0$-framing (i.e. no twisting) and the figure 8 was also replaced with two components but we have some twisting going on.  If you want to be precise, you will need to work out the framing on the figure 8 part.  Framing is not obvious, so I would avoid just eyeballing it.  See Rolfsen for some in-depth discussion of framings. Page 110 I think is where it starts.
Good luck.

What link is this link?


reselect across multiple comoponents work only with deepEqual check

Question: I've tested in various ways... Still, It isn't working.
I don't seem to doing anything wrong

exactly same code as reselect doc
redux store is all normalized
reducers are all immutable

From parent component, I just pass down a prop with id and from child component, connected with redux and used selector to get that exact item by id(from parent component)
### This is what Parent components render looks like
render() {
    return (

Parent component

        {this.props.sessionWindow.tabs.map(tabId =>
           <ChildComponentHere key={tabId} tabId={tabId} />
        )}

    );
  }

### This is what Child component looks like
render() {
    const { sessionTab } = this.props  (this props is from connect() )

        <Tab key={sessionTab.id} tab={sessionTab} />

    ))
  }
### Selectors for across multiple components
const getTheTab = (state: any, ownProps: IOwnProps) => state.sessionWindows.sessionTab[ownProps.tabId];
const makeTheTabSelector = () =>
  createSelector(
    [getTheTab],
    (tab: object) => tab
  )
export const makeMapState = () => {
  const theTabSelector = makeTheTabSelector();
  const mapStateToProps = (state: any, props: IOwnProps) => {
    return {
      sessionTab: theTabSelector(state, props)
    }
  }
  return mapStateToProps
}

Weirdly Working solution: just change to deep equality check.(from anywhere)

use selectors with deep equality works as expected.
at shouldComponentUpdate. use _.isEqual also worked.

.
 1. const createDeepEqualSelector = createSelectorCreator(
       defaultMemoize,
       isEqual
    )
 2. if (!_isEqual(this.props, nextProps) || !_isEqual(this.state, nextState)){return true}

From my understanding, my redux is always immutable so when something changed It makes new reference(object or array) that's why react re-renders. But when there is 100 items and only 1 item changed, only component with that changed props get to re-render.
To make this happen, I pass down only id(just string. shallow equality(===) works right?)using this id, get exact item.(most of the components get same valued input but few component get different valued input)  Use reselect to memoize the value.  when something updated and each component get new referenced input compare with memoized value and re-render when something trully changed.
This is mostly what I can think of right now... If I have to use _isEqual anyway, why would use reselect??  I'm pretty sure I'm missing something here. can anyone help?
For more clarification.(hopefully..)
First,My redux data structure is like this
sessionWindow: {
  byId: {  // window datas byId
    "windowId_111": {
      id: "windowId_111",
      incognito: false,
      tabs: [1,7,3,8,45,468,35,124] // this is for the order of sessionTab datas that this window Item has
    },
    "windowId_222": {
      id: "windowId_222",
        incognito: true,
        tabs: [2, 8, 333, 111]
    },{
      ... keep same data structure as above
    }
  },
  allIds: ["windowId_222", "windowId_111"] // this is for the order of sessionWindow datas
}
sessionTab: {  // I put all tab datas here. each sessionTab doesn't know which sessionWindow they are belong to
  "1": {
    id: 1
    title: "google",
    url: "www.google.com",
    active: false,
    ...more properties
  },
  "7": {
    id: 7
    title: "github",
    url: "www.github.com",
    active: true
  },{
    ...keep same data structure as above
  }
}

Problems.
1. when a small portion of data changed, It re-renders all other components.
  Let's say sessionTab with id 7's url and title changed. At my sessionTab Reducer with 'SessionTabUpdated" action dispatched. This is the reducer logic
const updateSessionTab = (state, action) => {
  return {
    ...state,
    [action.tabId]: {
      ...state[action.tabId],
      title: action.payload.title,
      url: action.payload.url
    }
  }
}

Nothing is broken. just using basic reselect doesn't prevent from other components to be re-rendered. I have to use deep equality version to stop re-render the component with no data changed
After few days I've struggled, I started to think that the problem is maybe from my redux data structure? because even if I change one item from sessionTab, It will always make new reference like {...state, [changedTab'id]: {....}}  In the end, I don't know...
Comment: oh! are you the author of http://blog.isquaredsoftware.com/. I've read all your practical and Idiomatic series. It was all great. This structure of redux and react components(not only connect from top containers but many times for performance. pass ids to props. etc...) is by reading your blogs. Probably, I don't fully understand it yet, hahaha
Comment: Can you clarify what the actual problem is?  You've described what you've done to try to fix the issue, but not what the issue is in the first place.  What is "broken" when you don't use `_.isEqual` ?  Also, can you post your reducer?
Comment: sorry about late reply, somehow didn't see it from my gmail. I tried to make it clearer. It started from bold subtitle.  short version of edit.
Problem: component with no data changed still re-renders.
Nothing is broken without _isEqual. Just still component with no data changed still re-renders.
Comment: Haha, thanks, and glad to know those posts have been helpful! :)
Answer: Three aspects of your selector definition and usage look a little odd:

getTheTab is digging down through multiple levels at once
makeTheTabSelector has an "output selector" that just returns the value it was given, which means it's the same as getTheTab
In mapState, you're passing the entire props object to theTabSelector(state, props).

I'd suggest trying this, and see what happens:
const selectSessionWindows = state => state.sessionWindows;

const selectSessionTabs = createSelector(
    [selectSessionWindows],
    sessionWindows => sessionWindows.sessionTab
);

const makeTheTabSelector = () => {
    const selectTabById = createSelector(
        [selectSessionTabs, (state, tabId) => tabId],
        (sessionTabs, tabId) => sessionTabs[tabId]
    );
    return selectTabById;
}

export const makeMapState() => {
 const theTabSelector = makeTheTabSelector();
  const mapStateToProps = (state: any, props: IOwnProps) => {
    return {
      sessionTab: theTabSelector(state, props.tabId)
    }
  }
  return mapStateToProps
}

No guarantees that will fix things, but it's worth a shot.
You might also want to try using some devtool utilities that will tell you why a component is re-rendering.  I have links to several such tools in the Devtools#Component Update Monitoring section of my Redux addons catalog.
Hopefully that will let you figure things out.  Either way, leave a comment and let me know.
Comment: your selector does really make sense, still It re-renders...  when one tab's data changed all the tab components are re-rendered.
why-did-you-update addon still says "props: Value did not change. Avoidable re-render!"    I removed other HOC in case, still the same result.(I'm using react-dnd)
  If simply making it deep equal solves re-rendering problem(whether it is from reselect or shouldComponentUpdate), then my data update logic is immutable right? Then using reselect will prevent re-render problem was my guess...
  Anyway thanks for your big help
Comment: Yeah, it's hard to say what else might be happening without actually having the entire project to look at.
Comment: That's true. I'll keep it this way until my programming skill goes up and can fix this problem.
Comment: I've made the similar example here. [link](https://codesandbox.io/s/my3wq7vj) As your advice, passing only ids solves the all problem.(my first attempt to prevent re-render) I don't  seem to need reselect at all...  I don't know what is wrong with my real project...   I'll leave a comment If It is not a stupid mistake and a real problem.
Comment: I think I found it.... It's because of the library I've been using from the beginning... [react-chrome-redux](https://github.com/tshaddix/react-chrome-redux/issues/10)
Comment: It passes actions between background, contentScript, popup, etc... BUT It returns whole updated state. This is why It re-renders every time. response is always the whole serialized copy of the store.(new object reference) It sounds not familiar if you haven't done chrome extension development.. whew... after I found this, don't know what to do. either build a new library or using current one knowing all this problem...
Comment: or this one [https://github.com/tshaddix/react-chrome-redux/issues/98](https://github.com/tshaddix/react-chrome-redux/issues/98)


Trying to capture an error in rails in `rescues/layout`?

Question: I have a lot of pictures, and occasionally one or two fail to access properly.   Instead of inserting a blank spot, I would like to capture the error and not put in anything.
The error:
Rendered /Users/me/.rvm/gems/ruby-1.9.3-p362/gems/actionpack-3.2.8/lib/action_dispatch/middleware/templates/rescues/routing_error.erb within rescues/layout (0.6ms)
How do I test in the html.erb?

        <% @photos.each do |photo| %>
          <% if [HOW DO I TEST IT HERE?] %>  //if no error

              <%= link_to image_tag(photo.image.url(:thumb)), photo %>

          <% else %> //if it errors that it can't access the file
             // put nothing
          <% end %>
        <% end %>

Also, why is it called/located in rescues/layout?   I thought that the errors were handled by the logger, or is this different?
Full trace:
`Started GET "/system/images/13/thumb/f838fe117a5a1f03ff5d2056d026d61a.jpg?1358062373" for 127.0.0.1 at 2013-01-14 00:19:19 -0500

ActionController::RoutingError (No route matches [GET] "/system/images/13/thumb/f838fe117a5a1f03ff5d2056d026d61a.jpg"):
  actionpack (3.2.8) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'
  actionpack (3.2.8) lib/action_dispatch/middleware/show_exceptions.rb:56:in `call'
  railties (3.2.8) lib/rails/rack/logger.rb:26:in `call_app'
  railties (3.2.8) lib/rails/rack/logger.rb:16:in `call'
  actionpack (3.2.8) lib/action_dispatch/middleware/request_id.rb:22:in `call'
  rack (1.4.3) lib/rack/methodoverride.rb:21:in `call'
  rack (1.4.3) lib/rack/runtime.rb:17:in `call'
  activesupport (3.2.8) lib/active_support/cache/strategy/local_cache.rb:72:in `call'
  rack (1.4.3) lib/rack/lock.rb:15:in `call'
  actionpack (3.2.8) lib/action_dispatch/middleware/static.rb:62:in `call'
  railties (3.2.8) lib/rails/engine.rb:479:in `call'
  railties (3.2.8) lib/rails/application.rb:223:in `call'
  rack (1.4.3) lib/rack/content_length.rb:14:in `call'
  railties (3.2.8) lib/rails/rack/log_tailer.rb:17:in `call'
  rack (1.4.3) lib/rack/handler/webrick.rb:59:in `service'
  /Users/me/.rvm/rubies/ruby-1.9.3-p362/lib/ruby/1.9.1/webrick/httpserver.rb:138:in `service'
  /Users/me/.rvm/rubies/ruby-1.9.3-p362/lib/ruby/1.9.1/webrick/httpserver.rb:94:in `run'
  /Users/me/.rvm/rubies/ruby-1.9.3-p362/lib/ruby/1.9.1/webrick/server.rb:191:in `block in start_thread'

  Rendered /Users/me/.rvm/gems/ruby-1.9.3-p362/gems/actionpack-3.2.8/lib/action_dispatch/middleware/templates/rescues/routing_error.erb within rescues/layout (0.6ms)`

Answer: Put your logic in a helper method
#PhotosHelper
def validate_image(img_path)
    "

" if File.exist?(img_path)
end

#view
<% @photos.each do |photo| %>
<%= validate_image(photo.image.url(:thumb))%>
<% end %>

You could clean the validate_image method up using
content_tag


Pagination in a .NET Core API Project

Question: I am trying to implement pagination on .NET Core RESTful API's (with EF).
Rather than re-inventing the wheel, I was hoping there was a way to either use a generic function that could hook into the API handler and intercept requests to apply them to EF Query results or something built into .NET Core that I am un-aware of. Can anyone point me in the general direction of a library that they are aware of that does this in .NET Core
The way I would previously do this (and have done in non .NET Core apps) is to make a function that I have to physically add the parameters to the controller function (pageSize, pageNumber) which does get tedious (and I think a tad untidy) to add these two parameters to every single function.
Comment: EF has two usefull methods fot that: `Skip(int)` and `Take(int)`. You can combine both to get only the page you need.
Comment: As far as I know there is nothing built-in. But the way I always did it was via a class which is returned from repositories (when using repository pattern for simple applications), which implements one or two interfaces (for sorting, pagination). This way DbContext/IQueryable interface doesn't have to leak into the domain or application layer. With CQRS it's wholly different, as you would have command/queries for a specific handler
Answer: There is no built-in feature for pagination, and if there was, you would not like it. Imagine a controller method returning 1.000.000 results for pagination just to pick 10 from them. It is up to you to implement the pagination.
The tedious and untidy controller methods like
public class FooController : Controller
{
    public IEnumerable<Foo> GetAll(
        string Filter,
        string Whatever,
        ...,
        int pageNumber = 1,
        int pageSize = 20 )
    { ... }
}

can be reorganized to
public class FooController : Controller
{
    public IEnumerable<Foo> GetAll( GetAllArgs args )
    {
        IQueryable<Foo> query = ...

        return query.Paginate( args ).ToList();
    }

    public class GetAllArgs : QueryArgsBase
    {
        public string Filter { get; set; }
        public string Whatever { get; set; }
    }
}

public interface IPaginationInfo
{
    int PageNumber { get; }
    int PageSize { get; }
}

public abstract class QueryArgsBase : IPaginationInfo
{
    public int PageNumber { get; set; } = 1;
    public int PageSize { get; set; } = 20;
}

public static class QueryableExtensions
{
    public static IQueryable<T> Paginate<T>(
        this IQueryable<T> source,
        IPaginationInfo pagination )
    {
        return source
            .Skip( ( pagination.PageNumber - 1 ) * pagination.PageSize )
            .Take( pagination.PageSize );
    }
}

Change any other controller method to have such an argument class and inherite from QueryArgsBase or implement IPaginationInfo to use the QueryableExtensions.Paginate method.
Comment: where should I put pagination logic if I use service layer that I call from my controllers?
Answer: Here's a ready-to-use code based on Sir Rufo's answer:
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace ProjectName.Utilities
{
    public static class Extensions
    {
        public static async Task<PaginatedResult<T>> paginate<T>(this IQueryable<T> source,
                                                int pageSize, int pageNumber)
        {
            return await new PaginatedResult<T>(pageNumber, pageSize).paginate(source);
        }
    }

    public class PaginatedResult<T> : ActionResult
    {
        private const int defaultPageSize = 20;
        private const int maxPageSize = 50;

        public int total { get; private set; }
        public int limit { get; private set; }
        public int page { get; private set; }
        public List<T> objects { get; private set; }

        internal PaginatedResult(int pageNumber, int pageSize = defaultPageSize)
        {
            limit = pageSize;
            page = pageNumber;

            if (limit < 0 || limit > maxPageSize)
            {
                limit = defaultPageSize;
            }
            if (pageNumber < 0)
            {
                page = 0;
            }
        }

        internal async Task<PaginatedResult<T>> paginate(IQueryable<T> queryable)
        {
            total = queryable.Count();

            if (limit > total)
            {
                limit = total;
                page = 0;
            }

            int skip = page * limit;
            if (skip + limit > total)
            {
                skip = total - limit;
                page = total / limit - 1;
            }

            objects = await queryable.Skip(skip).Take(limit).ToListAsync();
            return this;
        }
    }
}

And in your controller:
// ...
[HttpGet]
public async Task<ActionResult<PaginatedResult<MyDataType>>> getMyData(int pageSize = 20,
                                                                       int pageNumber = 0)
{
    return await _context.myData.AsNoTracking().paginate(pageSize, pageNumber);
}
// ...

Pagination in a .NET Core API Project


Finding the NP test

Question: I am really interested on solving the following problem I found in the Casella and Berger.
Suppose we have the following pdf: 2$\theta x + 2(1-\theta)(1-x)$ where $ 0<x<1$ and  $0<\theta<1$. We are looking for the NP test where the hypothesis we look to test is: $H_0 : \theta = \theta_0$ vs $H_1: \theta = \theta_1$ , where $\theta_1 < \theta_0$ Just one observation.
We wish to find the acception region when $\alpha$ is unknown.
WHAT I HAVE DONE:
Using the NP Lemma
$\frac{f_{\theta_0}}{f_{\theta_1}} \leq K$ which implies that $2\theta_0x + 1 - x - \theta_0 -2\theta_1Kx - K + Kx + K\theta_1\leq 0$
By doing the algebra, we then have that $x \leq \frac{(\theta_0 - K\theta_1) + (K-1)}{2(\theta_0 - K\theta_1) + (K-1)}$
I then defined $K^* = \frac{(\theta_0 - K\theta_1) + (K-1)}{2(\theta_0 - K\theta_1) + (K-1)}$
To find the acception region, we seek
$\alpha = P(x\leq K^*$ when $\theta = \theta_0) = \int_{0}^{K^*}2\theta_0x+2(1-\theta_0)(1-x)dx = 2(K^*(1-\theta_0)-\frac{(K^*)^2}{2})$
First question: Is what I have done correct?
Second question: The next step is solving for $\alpha$, how should I approach such problem?
Comment: Is this for some class?
Answer: First question: Yes.
Second question: You have to express $K^{*}$ in function of $\theta_0$ and $\alpha$.

Finding the NP test


How to find classification of a single image instance? (fastai)

Question: The code below creates a classifier from MNIST data set for 3 and 7 image digits.
Can you help me figure out how to use this learner to classify a new image?
!pip install -Uqq fastbook
import fastbook
fastbook.setup_book()

from fastai.vision.all import *
from fastbook import *

matplotlib.rc('image', cmap='Greys')
path = untar_data(URLs.MNIST_SAMPLE)
dls = ImageDataLoaders.from_folder(path)
learn=cnn_learner(dls,resnet18,pretrained=False,loss_func=F.cross_entropy,metrics = accuracy)
learn.fit_one_cycle(1,0.1)

Answer: Just use learn.predict('testImage.jpg')
For your reference, see the fastai docs vision tutorial
Comment: I tried it, didn't work.
img = (path/'valid/3').ls()[0]
learn.predict(img)

Getting:
--> 233                 else [self.items[i_] for i_ in i])
IndexError: list index out of range

gets me the following error
Comment: from your error message it seems you are trying to access an item in a list that doesn`t exist. Can you check if your image path is correct?
Comment: I used  img = (path/'valid/3').ls()[0]  to make sure.
Comment: Is this not working for you `learn.predict(path/'valid/3')` ?
Comment: Getting the following
IsADirectoryError: [Errno 21] Is a directory: '/root/.fastai/data/mnist_sample/valid/3'

You can access the code and run it using this:

https://colab.research.google.com/drive/1GYIweSLWaWKjXjNpH-s_ry24_y0O1GFT?usp=sharing
Comment: Also - To double check that the path I used for the file is correct I ran:
img = (path/'valid/3').ls()[0]
Image.open(img)
And the image shows up so 'img' is defined correctly
Comment: correct. I tried it as well as a specific image path. Didn't work


Why doesn't the bassoon play any notes in the beginning of RV 484?

Question: In Vivaldi's Concerto in E minor for Bassoon, RV 484, you can hear the violins introduce the theme, and then the bassoon enters to play solo.
In every video I watch the procedure is the same: first violins and the orchestra, then the bassoon.
Looking at the sheet music, I see that the bassoon actually plays through the whole piece, mainly by pedal bass notes. Why do most renditions of the piece choose to not play them as notated?
Answer: You unfortunately fail to mention the edition you are looking at for comparison, so I won't comment much on its authority or authenticity. Given, how hard it is to find an urtext edition of that concert and its high popularity (leading to numerous editions), some doubt is in order. So as notated is a claim asking for supporting sources.
I already encountered passages likes this (clarification follows) in an arrangement for bassoon and piano marked as ad libitum - the soloist is free to chose, whether to play it or not. Looking at the first page of the IMSLP score (non-PD in EU) and finding the bassoon having to play the same notes, which cellos and double basses already play, I understand every soloists, choosing not play here: there is more demanding  material to follow later, so why waste the breath?


Execute javascript code from android service when app is closed

Question: I want to execute a javascript function from native android even when the application was closed.
I have a service in android and i called the javascript function every hour or minutes like this:
private class mainTask extends TimerTask
{
    public void run()
    {
       fireEvent("event", null);
       //this calls webView.sendJavascript(js);
    }
}

This is working well while the application is still in the foreground, it calls the javascript function in the hybrid part,
but when I closed/kill the app the service is still running and the fireEvent function and webView.sendJavascript(js) were still executed but the javascript function is not executed anymore.
This is my js:
cordova.plugins.background.event = function () {
    console.log("background mode on active");
    //also put a javascript notification here to know if its executed.
}

Am I missing something or its not possible to execute a javascript code if the application is close?
Comment: when app is background, js code can't execute. Only run native code.
Comment: can you show some documentation or support to your answer?                In here https://github.com/christocracy/cordova-plugin-background-geolocation it says that a callback can be called and its running in background, I'm just not totally sure if it calls the callback if the app was killed since i haven't tested it.
Comment: plugin-background-geolocation use native code to post tracking location to your server when app in background. In document, plugin's author said: in IOS, callback js can trigger after app in background and Android then callback js will not fire, all js will be stop in Android.
Answer: if the app is closed... you can't execute code of this app.
You could:
 1. execute code outside of the app... (but this is maybe not what you want)
 2. try to launch again silently the app (not sure exactly if you can do that from a service)


Why does $\mathbb{Z}$ satisfy the ACC?

Question: This might be a really trivial question but somehow my reasoning shows the opposite of what it is supposed to be.

Show that the set of integers $\mathbb{Z}$ satisfies the Ascending Chain Condition.

My work:
Since every ideal is of the form $(m)$ for some $m\in\mathbb{Z}$, then as $m$ increases the set $(m)$ becomes less "dense", then how can I show $I_1\subset I_2\subset\dots I_i\subset\dots$? How can a less "dense" set be a superset of a "denser" set?
How can we explain the claim both in rigorous and in intuitive manner?
If there is any flaw in my reasoning, please correct it.
Thanks!
Comment: You can show that $\Bbb{Z}$ is a PID and hence satisfies the ACC. Here's a proof of why PIDs satisfy the ACC :http://www.proofwiki.org/wiki/Principal_Ideal_Domain_fulfills_Ascending_Chain_Condition
Answer: From your description of your reasoning, I  think you're mixing up $\supset$ and $\subset$, and also perhaps confused about what you want to show.
You're right that as $m$ increases the set $(m)$ becomes less "dense"; in fact, one can be more precise:
$$(m)\subseteq(n)\iff n\mid m$$
where $n\mid m$ means "$n$ divides $m$", or in other words "$n$ is a factor of $m$". Thus, "less dense" sets are contained in "denser" sets, as you would expect. Therefore, given a collection of ideals $I_i=(m_i)$, they are an ascending chain, i.e. they satisfy
$$I_1\subseteq I_2\subseteq I_3\cdots$$
if and only if the integers $m_i$ satisfy
$$m_2\mathsf{\text{ is a factor of }}m_1,\quad m_3\mathsf{\text{ is a factor of }}m_2,\quad\ldots$$
Hopefully it is clear from this why the chain of ideals must stabilize.
You then ask

how can I show $I_1\subset I_2\subset\cdots I_i\subset\cdots$

but this is not the ACC. In fact, the above statement doesn't mean anything - we haven't said what these $I_i$'s are. You want to show that there does not exist such an increasing chain of ideals (or, if you use $\subset$ to mean $\subseteq$, you want to show that any such collection of ideals will eventually stabilize).
Answer: Think about what containment of ideals in $\mathbb{Z}$ means in terms of prime factorisations. When is $(m) \subseteq (n)$? It means that $n$ has prime factors only occurring in the prime factorisation of $m$, and so as you go "further along" in the sequence you end up either stopping, or finishing at $1$.
It's definitely easier to see this (for me at least) in terms of the equivalent characterisation. The ascending chain condition is equivalent to ideals being finitely generated. In the case of $\mathbb{Z}$, it's even better: they are singly generated.
Answer: Here is another approach, in its core it is quite the same answer as the others gave, but it's wrapped differently. Its applicability to your situation may depend on theorems which you may or may not have learned about $\Bbb Z$.
Note that if $I$ is a non-zero ideal then $\Bbb Z/I$ is a finite set. If $I\subseteq J$ then $J/I$ is an ideal in $\Bbb Z/I$, and $(\Bbb Z/I)/(J/I)\cong\Bbb Z/J$. Therefore the larger the ideal is -- the smaller the quotient is.
Therefore an increasing sequence of ideals corresponds to a decreasing sequence of finite sets. How long can such sequence be?
Comment: It seems that someone takes the time to downvote two answers of mine every day.
Answer: Hint: $ $ for principal ideals: $\ (a)\supset (b)\!\iff\! a\mid b,\ $ i.e. constains $\!\iff\!$ divides, hence
$$\begin{eqnarray} \ldots && (a_3) &\supsetneq& (a_2)&\supsetneq&(a_1)\quad {\rm wlog}\ \ a_i \ge 0,\ \ {\rm by}\ \ (a) = (|a|) \\
\iff\ \ldots && \ \ a_3 &\,\mid& \ \ a_2 &\,\mid& \ \ a_1\quad\ \ \text{where each division is  proper}\\
\Rightarrow\,\ \ \ldots && \ \ a_3 &<& \ \ a_2 &<& \ \ a_1 \\
\end{eqnarray}$$
Thus the chain stabilizes at the ideal with the least generator $\ge 0,\,$ which is also the least element in the (ascending) union of the ideals. Viewed arithmetically, this least element is the gcd of the generators, and also the gcd of all elements in the union of the ideals.
Answer: How can a less "dense" set be a superset of a "denser" set?
Thinking of chain conditions as "density" does not really strike me as a good mental model. It really should be something more like "size."
Chain conditions like the ACC and DCC just put limits on "how deep" or "how tall" a chain can be. In $\Bbb Z$, you are trying to show that you can't have an infinitely tall chain of proper containments. That is, it's a limit on how fast such chains can grow in a particular direction.
Why is this? Since $\Bbb Z$ is a PID, its ideals are all principal and have particularly simple relationships with each other: $(b)\subseteq (a)$ iff $a$ divides $b$. But the fundamental theorem of arithemetic puts limits on what can divide $a$, and hence limits what can properly lie above $(b)$.
But on the other hand, $\Bbb Z$ admits infinitely deep descending chains. For example $(2)\supsetneq(4)\supsetneq(8)\supsetneq\dots$ is possible. If it were the case that $(2^n)=(2^{n+1})$, then $2^{n+1}|2^n$ is just not possible because of the nature of the integers.

A good mental model of density is something like the field of fractions for a domain. For example $\Bbb {Z}$ is really "dense" (="large") in its field of fractions $\Bbb Q$ since every nonzero additive subgroup of $\Bbb Q$ has to have nonzero intersection $\Bbb Z$. In that sense $\Bbb Z$ is so "thick" in $\Bbb Q$ that you can't avoid hitting it.

To get a better flavor of the ACC and DCC, I recommend you search the site for some examples of an Artinian module which isn't Noetherian, so you can see what that example looks like. If you have access, you can also skim Lectures on Modules and Rings by Lam, page 228, which is a section on finiteness conditions on rings. There you can find many interesting variants of chain conditions, which will hopefully convince you that such conditions aren't really about density, but rather about height and depth.
Comment: Actually, I think density is kind of a good way to think about ideals of $\mathbb{Z}$.  I picture the sieve of Eratosthenes: the ideal $2\mathbb{Z}$ is denser than $4\mathbb{Z}$ because half of all integers are even, whereas only a quarter of all integers are multiples of $4$.  However, the OP has this density backwards!
Comment: Dear @SpamIAm : By reasoning with that logic of "percentages of $\Bbb Z$," $4\Bbb Z$ is more dense than $p\Bbb Z$ for any prime $p$ larger than $4$. This seems a little strange since all of those ideals are rather special prime (and maximal) ideals. Was that intended? I guess we could agree to only compare ideals which are comparable by containment, but then "denser" just becomes "contains." Regards
Comment: Yes, I guess this idea of density and containment only works if you have a chain of ideals as in the question.
Answer: Suppose we have a sequence of increasing subgroups $G_n = (k_n)$ that doesn't stabilize. Then $G_i = (k_i) \subset G_j = (k_j)$ iff $k_j|k_i$. Then all $k_j$ divide $k_1$, but we cannot have infinitely many distinct $k_j$ dividing $k_1$.

Why does $\mathbb{Z}$ satisfy the ACC?


How do I redirect to www and https in settings.php?

Question: I want to include code in settings.php which would handle redirects to the www alias and also https.
Because it is for a distribution I would prefer not to have hard-coded URLs and I would also prefer not to be changing the .htaccess file so that core updates are easier.
I am using the code below, and I just want to be sure it doesn't have any security issues. Does it have any security issues, and I should therefore use different code?
<code>// Redirect to www
  if (substr($_SERVER['HTTP_HOST'], 0, 4) !== 'www.') {
  header('Location: '.$protocol.'www.'.$_SERVER['HTTP_HOST'].'/'.$_SERVER['REQUEST_URI']);
exit;
}
// Redirect to HTTPS
  if($_SERVER["HTTPS"] != "on")
{
  header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
exit();
}
</code>
Comment: Welcome to Drupal Answers! Notice that [tag:security] is not about using https://.
Comment: I take your point and thank you for the correction @kiamlaluno - my intent was to ask if the code is secure.
Answer: The caveat to the settings.php approach is 2 issues:

Your redirect requires that Drupal be bootstrapped to work. If there's a resource that bypasses Drupal (e.g. any hosted files), you're not going to see the www redirect occur.
It's arguably bad practice. settings.php is for Drupal settings; depending on your intent this might be considered a web server setting. A developer working on your project in a local environment might have trouble understanding where the redirect is coming from as standard Drupal configurations use the .htaccess file for this.

An alternative to prevent .htaccess overwriting would to be place the rewrite directive in an Apache configuration (e.g. vhost.conf if you're using virtual hosts) that defines your host.
Comment: 1. An interesting point that I hadn't considered, however the intended use case would make this an unlikely scenario. 2. Fair point although it is an internal distro and would not be used by external devs. Lastly I should do some reading up on Apache config. Thank you for the tips @Shawn Conn.
Answer: You can also choose to use the htaccess module that allows these options with some radio buttons. It comes with Drush integration for re-deploying the .htaccess file after a core update, and monitors and warns if the file has changed. You might find it interesting.
From the module page:

this module is dedicated to webmasters who don't want to manually
  modify htaccess every time during a version upgrade to use Drupal.
Comment: Might this approach be more efficient than using settings.php?
Comment: @MrPaulDriver Not sure, I suppose apache will process `.htaccess` before bootstrapping Drupal and loading the settings. So rather than loading Drupal 2 or 3 times, it will load .htaccess 2-3 times and then attempt to load Drupal. So my guess would be this is better. I might be wrong though.


Find $ \lim_{n\rightarrow \infty} \frac{1}{n^2} + \frac{2}{(n+1)^2}+\dots+\frac{n+1}{(2n)^2} $

Question: I want to find the following limit:
$$ \lim_{n\rightarrow \infty} \frac{1}{n^2} + \frac{2}{(n+1)^2}+ \frac{3}{(n+2)^2}+\dots+\frac{n+1}{(2n)^2} $$
I guess it converges to 0 and I tried to prove it using the squeeze theorem but it doesn't seem to work.
Any ideas?
Comment: What do you mean by $n\rightarrow 0$?
Comment: my mistake, I edited it
Comment: I don't know if it helps, but this can also be written as $$\lim_{n\to\infty}\sum_{x=0}^n\frac{x+1}{(x+n)^2}$$ Sometimes rewriting in sigma notation helps me
Answer: Your limit can be rewritten as a Riemann sum + $a_n$ where $a_n\rightarrow 0$.
This is a Riemann sum:
\begin{align}
\lim_{n\rightarrow \infty} \frac{1}{(n+1)^2}+ \frac{2}{(n+2)^2}+\dots+\frac{n}{(2n)^2}&=\lim_{n\rightarrow \infty} \frac{1}{n}\left ( \frac{1/n}{(1+1/n)^2}+ \frac{2/n}{(1+2/n)^2}+\dots+\frac{n/n}{(1+n/n)^2}\right)\\
&=\int_{0}^1 \frac{x}{(1+x)^2} \text{d}x \\
&=\int_{0}^1 \frac{x+1}{(1+x)^2} \text{d}x -\int_{0}^1 \frac{1}{(1+x)^2} \text{d}x\\
&=\int_{0}^1 \frac{1}{1+x} \text{d}x -\int_{0}^1 \frac{1}{(1+x)^2} \text{d}x
\end{align}
Now,
\begin{align}a_n&=\frac{1}{n^2} + \frac{1}{(n+1)^2}+ \frac{1}{(n+2)^2}+\dots+\frac{1}{(2n)^2} \\
&\leq \frac{1}{n^2} + \frac{1}{n^2}+ \frac{1}{n^2}+\dots+\frac{1}{n^2}\\
&=(n+1)\frac{1}{n^2}\rightarrow 0
\end{align}
Comment: Thanks for the answer, although I was looking for something simpler as it adresses to students not familiar with Riemann sums, just basic properties of sequences and limits
Answer: Note that
$$\frac{1}{n^2} + \frac{2}{(n+1)^2}+ \frac{3}{(n+2)^2}+\dots+\frac{n+1}{(2n)^2}=\sum_{k=n}^{2n}\frac{k-n+1}{k^2}
=\sum_{k=n}^{2n}\frac{1}{k}-(n-1)\sum_{k=n}^{2n}\frac{1}{k^2}\sim \log \left(\frac{2n}{n-1}\right)-\frac{n+1}{2n}\to\log 2-\frac12$$
indeed for Harmonic series and Euler–Maclaurin formula
$$\sum_{k=n}^{2n}\frac{1}{k}=\sum_{k=1}^{2n}\frac{1}{k}-\sum_{k=1}^{n-1}\frac{1}{k}\sim\log2n-\log (2n-1)=\log \left(\frac{2n}{n-1}\right)$$
$$\sum_{k=n}^{2n}\frac{1}{k^2}=\sum_{k=1}^{2n}\frac{1}{k^2}-\sum_{k=1}^{n-1}\frac{1}{k^2}\sim -\frac1{2n}+\frac{1}{n-1}=\frac{n+1}{2n(n-1)}$$


Dúvida sobre API do Twitter

Question: Na documentação diz o seguinte:

Tokens are passwords
  Keep in mind that the consumer key & secret, bearer token credentials, and the bearer token itself grant access to make requests on behalf of an application. These values should be considered as sensitive as passwords, and must not be shared or distributed to untrusted parties.

Traduzindo isto:

Tokens são senhas
  Tenha em mente que a chave do consumidor e o segredo, as credenciais token do portador eo token do portador em si permitem o acesso para fazer solicitações em nome de um aplicativo. Esses valores devem ser considerados sensíveis como senhas e não devem ser compartilhados ou distribuídos para partes não confiáveis.

Fonte: https://dev.twitter.com/oauth/application-only?lang=ko
Estou querendo que o usuário ao invés de clicar no botão Entrar com o Twitter usando oAuth, ele preencha um formulário com seus dados do Twitter, usuário e  senha.
OBS: Não quero roubar informações, pois não é possível...
Com tudo, se o Token são senhas, posso recuperar o screen_name e usar um crypt, não sei se o Twitter usa sha1, pra eu pode recuperar a senha também. Se alguém souber, informe aqui.
Fonte: https://dev.twitter.com/overview/api/users
Estou correto ou errado?
Answer: O que a documentação quer é que as credenciais (token, bearer token, secret key...) devem ser mantido apenas com você, em segurança. Uma vez que se obter essas informações será capaz de fazer requisições em nome do seu aplicativo do Twitter.
Qualquer um que conseguir sua chave privada (API Secret) poderá autenticar os usuários se passando por sua aplicação. Bem como que qualquer um que tiver os tokens/bearer token também poderá utiliza-los como quiser, em nome do seu aplicativo. Por exemplo, poderão postar tweets como se o seu aplicativo estivesse postado, sem que você de fato tenha feito isso.
Por esse motivo essas informações não podem ser compartilhada ou distribuídas, assim se mantendo apenas com você.

Estou querendo que o usuário ao invés de clicar no botão Entrar com o Twitter usando oAuth, ele preencha um formulário com seus dados do Twitter, usuário e  senha.

A API oficial do Twitter, a pública, apenas permite que utilize o oAuth. Ele foi construído justamente para que os usuários não informem suas credenciais para terceiros.
Não há nenhuma maneira oficial de fazer o que você quer. O que existe são gambiarras. Que é utilizar a API privada, aquela que twitter utiliza. Salvo engano já havia informado como pode fazer isso. Você pode fazer uma engenharia reversa no aplicativo móvel do twitter, assim como monitorar as requisições feita pelo aplicativo.
No website do Twitter você pode simplesmente monitorar o tráfego (os navegadores já possuem este recursos) e então saberá os endpoints utilizados.
Você pode tentar procurar por alguém que já tenha feito esse trabalho, inclusive poderá achar pessoas que já disponibilizaram tais informações publicamente ou até mesmo bibliotecas em alguma linguagem que utiliza a API privada.
Uma vez com a posse das senhas você poderá obter o cookie da sessão, essa é quase um "Token", porém da API privada. Ela normalmente é armazenada em cookies (ou em vários cookies), no caso da API do aplicativo móvel talvez esteja criptografado, exigindo alguma engenharia reversa para obter as chaves.

OBS: Não quero roubar informações, pois não é possível...

Ora, se você pede a senha de outras pessoas... A frase "Não quero roubar informações, pois não é possível..." é um erro. Não só você tem a capacidade de "roubar" as credenciais, como outras pessoas podem "roubar o seu roubo".
Uma vez que você pede e recebe as senhas do Twitter você terá as senhas, você tem acesso a tais credenciais. Mesmo que utilize HTTPS, as informações são descriptografadas em seu lado, na melhor das hipóteses, e serão armazenados em "alguma memoria", afim você tem acesso.

Com tudo, se o Token são senhas, posso recuperar o screen_name e usar um crypt, não sei se o Twitter usa sha1, pra eu pode recuperar a senha também. Se alguém souber, informe aqui.

Sinceramente não entendi o que quer dizer. O Token é aleatório, gerado apatir da sua chave privada e pública para o usuário que autorizou a sua aplicação. Elas são como uma senha no ponto de vista de seu sigilo, uma vez que tanto sua senha e tanto um Token não devem ser compartilhados, e assim como ambas concedem acesso a fazer interações em seu nome.
Salvo engano o oAuth2 não utiliza nenhuma criptografia no Token em si, somente no seu tráfego, isto é feito para tornar as respostas mais rápidas e até por isso não exige que você criptografe qualquer Token.
Se você quiser manter o Token de maneira extremamente segura o máximo que pode fazer, ao meu ver, é utilizar uma criptografia assimétrica e usar algum HSM para armazenar as chaves.
Comment: Excelente @Inkeliz, achei que o token era a senha do usuário, e sim foi contraditório eu dizer que não quero roubar informações, mas realmente não quero, vou explicar o que eu quero fazer... Quero fazer um site com troca de seguidores, semelhante a este... http://twitterlike.com.br, se você puder me responder... (com o botão "Entrar com o Twitter") utilizando o oAuth sem que o usuário entre com suas credenciais é possível? Tenho intermediário em PHP e Javascript,  se você disser que é possível vou tenta-lo fazer, caso contrário jogo tudo na lixeira... Obrigado pela resposta bem elaborada...
Comment: Ótima resposta, mas a melhor parte, para mim, foi essa: **Não só você tem a capacidade de "roubar" as credenciais, como outras pessoas podem "roubar o seu roubo".**
Comment: Fazer isso é simples, é possível, _tanto que já fizeram_. Utilizar a API pública (essa do "Entrar com o Twitter") é possível, porém é muito mais fácil o Twitter bloquear o aplicativo, assim você irá perder todos os usuários para a "troca de seguidores", exigindo que todos se conectem num novo aplicativo. Já com a API privada o máximo que podem fazer é banir o seu IP, logo você pode usar vários proxies.
Comment: A questão do "roubo" vem justamente do "Não se preocupe não temos acesso a sua senha" desde que me prove o contrário, eles tem acesso a senha, o máximo que podem fazer é não armazena-la de maneira persistente. Mas vão armazenar a sessão, que da na praticamente na mesma.
Comment: A API Privada e Pública se refere à API em si, não as chaves. https://www.upwork.com/hiring/development/public-apis-vs-private-apis-whats-the-difference/
Comment: Não, mas o Twitter construiu. Nem todos os recursos estão acessíveis através da API pública ("Entrar com o Twitter"). Veja por exemplo o link: `https://api.twitter.com/1.1/jot` ele não está documentado na API Pública, ele é usado exclusivamente pelo Twitter em si. Um outro exemplo é o `https://twitter.com/scribe`, entre e dará um página em branco. Também tem o `https://twitter.com/account/authenticate_web_view`, esses são alguns "_links_" que são usados exclusivamente na "Private API", _eles podem ser obtidos monitorando o tráfego_. É essa API que você "deve" utilizar, **lembre-se dos ToS**.
Comment: Se até mais tarde não houver resposta melhor que a tua eu marco ela como resolvido ta ok?.... Agora acho que vou usar o botão "Enter with Twitter", e salvar todos os tokens em uma tabela e fazer uma roleta para os usuários se auto se seguirem...
Comment: @Inkeliz, eu não entendi a parte de API Privada, teria como editar o tópico explicando melhor? eu procurei revirei o Google e não encontrei nada..., **Fazer isso é simples, é possível, tanto que já fizeram. Utilizar a API pública** Eu acho que é só renovar as Keys do do aplicativo... Mas voltando... poderia explicar?
Comment: Entendi, li o artigo... conclusão API privada, eu mesmo terei que construí-la? acho que entendi...
Comment: **ToS?** caramba, ta cada vez mais complicado, mas com tuas dicas, vou fazer um esforcinho... to cheio das dúvidas ainda, mas não quero "Folgar em ti". Obrigado, qqr coisa eu abro outra pergunta.
Comment: Pra monitorar é `f12` > `network` né?
Comment: Acho que consegui autenticar... mas o cookie em sim está aleatório não está o mesmo do twitter
Answer: Sim Tokens são senhas conforme diz a documentação da API do Twitter, ele usa Base64 com codificador se eu não estou enganado.
Para transferir pro formulário, você não deve usar oAuth pois ele gera um Token que é passado por $_GET, terás que descobrir outra forma de validar seu formulário, lembrando que vai ter que fazer por exemplo:
curl_setopt($ch, CURLOPT_URL, "http://www.google.com/");
Esta é minha opinião, e estou quase certo que estou correto.
Comment: Como eu te disse, terás que descobrir outras formas de autenticar o usuário sem usar oAuth.
Comment: Será? o que devo estudar alem de `json` e a documentação, não vejo lógica em não usar o `oAuth`.
Answer: Aperte f12 na página de login do Twitter, vai em network, aperte f5 pronto verás algumas informações necessárias.

Dúvida sobre API do Twitter


Como armazenar o valor de retorno de uma função em uma váriavel local em C?

Question: Criei uma função que retornava determinado valor, quando utilizo essa função na função main do programa, como posso fazer para armazenar o retorno dela, e por exemplo, exibir esse retorno em um printf na main?
#include <stdio.h>
#include <stdlib.h>

int distanciaCorrida(int inicio, int fim){
    int distancia = 0;
    distancia = fim - inicio;
    return distancia;
}

int main(){
    int kminicial, kmfinal;
    kminicial = 200000;
    kmfinal = 207349;
    distanciaCorrida(kminicial,kmfinal);
    printf("A distancia percorrida pelo carro foi de %d km",);
    return 0;
}

Comment: Não é nem muito uma questão de não estar conseguindo mas sim de como fazer. mas vou colocar o código
Comment: Só fazer int dp = distanciaCorrida(kminicial,kmfinal); e depois printf("A distancia percorrida pelo carro foi de %d km", &dp);
Comment: @JoeTorres: O operador de endereço `&` está demais nessa tua expressão; vai imprimir o valor errado deste jeito.
Comment: Tem razão. & vai só no scanf não no print....
Answer: Assim como você pode atribuir um valor literal na variável, pode atribuir uma expressão já que fez uma subtração, que é uma expressão. Uma expressão pode conter uma série de coisas que gerem algum resultado. Uma função gera um resultado, então é só usá-la de na atribuição da variável. Veja explicações dos termos.
Aproveitei e simplifiquei o código.
#include <stdio.h>

int distanciaCorrida(int inicio, int fim) {
    return fim - inicio;
}

int main() {
    int kminicial = 200000;
    int kmfinal = 207349;
    int distancia = distanciaCorrida(kminicial, kmfinal);
    printf("A distancia percorrida pelo carro foi de %d km", distancia);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
A variável distancia aí nem é necessária, na verdade todas elas, mas para fazer da maneira exposta e indicar como fazer se fosse algo que a variável é necessária. Poderia fazer:
printf("A distancia percorrida pelo carro foi de %d km", distanciaCorrida(kminicial, kmfinal));

A não ser em um caso de querer gerar uma abstração, é até mais simples fazer o cálculo simples direto sem criar uma função, mas entendo que seja uma questão de aprendizado. Só não aprende fazer sempre assim se não tiver necessidade.
Uma pergunta bem parecida.


How to print the product variation separately from the submit/pay button in a Commerce add to cart form?

Question: I want to put the calculated product price between the "product variation" select widget and the "pay" button.
In commerce-product.html.twig (my products display an add to cart form on the product itself), I have this code:

{{ product.title }}

  {{ product|without('title', 'variation_price' }}
  {{ product.variation_price }}

variation_price is the calculated price.

What is the name of the variable that contains the product variation select widget?  Answer: product.variations
How can I place the submit/pay button separately from the variation type selection widget?  Answer: ??

I tried using kint to debug but it broke my site.  (And then people on this site kindly explained how to fix it.)  So I now understand that the variable containing the widget that shows the variations is named product.variations, and this is actually the "Add to cart" form (since that is what I set the display widget to in the UI).
So I guess I need to print the "Add to cart" form twice, and in one instance show the submit button, and in the other instance show the select widget... But how do I do that?
I looked at the twig debug theme suggestions but they don't give me a template for the "Add to cart" form:


Ler arquivos de forma síncrona no Cordova

Question: Existe alguma forma de, no Apache Cordova, ler o conteúdo de um arquivo e salvar em uma variável de forma síncrona?
Isto porque, na API de Arquivos do Cordova você deve usar uma função de callback ao ler um arquivo para obter o resultado, e acaba sendo de certa forma um pouco inconveniente, ficar dividindo o código dentro de callbacks.
Então, teria alguma forma de ler um conteúdo do arquivo e salvar o resultado em uma variável, sem precisar de um callback?

Método com callbacks de exemplo do Apache Cordova:
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
    fs.root.getFile("arquivo.txt", { create: false, exclusive: false }, function (fileEntry) {
        fileEntry.file(function(file) {
            var reader = new FileReader();

            reader.onloadend = function() {
                console.log("Conteúdo do Arquivo: " + this.result);
            };

            reader.readAsText(file);
        }, onErrorReadFile);
    }, onErrorLoadFile);
}, onErrorLoadFs);

Método desejado, sem callbacks: (exemplo)
var texto = funcaoSincronaDeLerArquivo("arquivo.txt")

// manipulação do conteúdo, somente exemplo
if (texto == "admin") {
    window.location = "admin.html";
} else {
    window.location = "user.html";
}

Answer: Devido a natureza do Cordova, um framework que trabalha fazendo a mediação da comunicação do seu código com o aparelho em linguagem nativa, dificilmente você terá essa possibilidade, pois o próprio Cordova faz uma chamada assíncrona na linguagem nativa e aguarda resultado para passar para o callback que você define.
Você pode usar Promise para tornar o controle mais simples e o código mais limpo.
Usando callbacks seu código vai criando uma pirâmide e o chamado callback hell:
asyncFunc1(false, function(ret1){
    asyncFunc2(false, function(ret2){
        asyncFunc3(false, function(ret3){
            console.log(ret3);
        }, genericErrorHandler);
    }, genericErrorHandler);
}, genericErrorHandler);

Com promises você lineariza isso, tornando mais simples de ler e controlar:
new Promise(function(resolve, reject){
    asyncFunc1(false, resolve, reject);
}).then (function(ret1) {
    return new Promise(function(resolve,reject){
        asyncFunc2(false, resolve, reject);
    });
}).then (function(ret2){
    return new Promise(function(resolve,reject){
        asyncFunc3(false, resolve, reject);
    });
}).then(function(ret3) {
    console.log(ret3);
}, genericErrorHandler);

Por exemplo, capturar uma imagem da câmera com callbacks
function getPictureWithoutPromises(successCallback, errorCallback) {
    navigator.camera.getPicture(function (imagePath) {
        window.resolveLocalFileSystemURL(imagePath, function (imageFileEntry) {
            window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function (appDataDirEntry) {
                imageFileEntry.copyTo(appDataDirEntry, null, function (newImageFileEntry) {
                    successCallback(newImageFileEntry);
                }, errorCallback);
            }, errorCallback);
        }, errorCallback);
    }, errorCallback);
}

getPictureWithoutPromises(function (imageFileEntry) {
    image.src = imageFileEntry.toURL();
}, function (err) {
    console.log("Error : ", err);
});

E capturar a imagem da câmera usando Promise
function getPictureWithPromises() {
    var sourceImageFileEntry;

    return new Promise(function (returnResolve, returnReject) {
        new Promise(function (resolve, reject) {
            navigator.camera.getPicture(resolve, reject);
        }).then(function (imagePath) {
            return new Promise(function (resolve, reject) {
                window.resolveLocalFileSystemURL(imagePath, resolve, reject);
            });
        }).then(function (imageFileEntry) {
            sourceImageFileEntry = imageFileEntry;
            return new Promise(function (resolve, reject) {
                window.resolveLocalFileSystemURL(cordova.file.dataDirectory, resolve, reject);
            });
        }).then(function (appDataDirEntry) {
            return new Promise(function (resolve, reject) {
                sourceImageFileEntry.copyTo(appDataDirEntry, null, resolve, reject);
            });
        }).then(function (newImageFileEntry) {
                returnResolve(newImageFileEntry)
        });
    });
}

getPictureWithPromises().then(function (imageFileEntry) {
    image.src = imageFileEntry.toURL();
}, function (err) {
    console.log("Error : ", err);
});

Você pode usar a biblioteca cordova-promise-fs pra utilizar as funções do sistema de arquivos do cordova com promessas ou estudá-las para implementar no seu código, caso não atenda suas necessidades. Mas infelizmente não há como fazer este procedimento sem uma abordagem assíncrona.


Find maximum users in a network

Question: I have m lines with values x and y space separated that represent the user ids. This is like a user x follows user y on Facebook or Instagram etc. Now if we have a pair of z and y then since z follows y, as we already have a group [x,y] then we can merge z to form [x,y,z]
Example:
1 2
3 4
5 6
1 5

we can have below groups:
[1 2 5 6] and [3 4], the length of the largest group [1,2,5,6] is 4 will be the answer.
Here is my approach to this:
public int process(int m, int[][] arr) {
    List<Set<Integer>> list = new ArrayList<>();

    int ans = 0;
    for(int i=0; i<m; i++) {
        int x = arr[i][0], y = arr[i][1];
        if(j ==0) {
            Set<Integer> set = new HashSet<>();
            list.add(set);
            set.add(x);
            set.add(y);
            ans = 2;
            continue;
        }
        boolean found = false;
        for(Set<Integer> set : list) {
            if(set.contains(x) || set.contains(y)) {
                set.add(x);
                set.add(y);
                ans = Math.max(ans, set.size());
                found = true;
                break;
            }
        }
        if(!found) {
            Set<Integer> set = new HashSet<>();
            list.add(set);
            set.add(x);
            set.add(y);
        }
    }
    return ans;
}

My approach itself is wrong as my list generated is not grouping elements correctly. How to solve this problem. Also the input array length can be up to 100 000, so need to solve this in less time complexity.
Constraints:
x and y can range from 1 to 10^5
aray length can be up to 10^6

Comment: If 1 follows 2 and 1 follows 5, why do you/we assume 2 follows 5?
Comment: @גלעדברקן, basically I need to merge such items to provide suggestions to them.
Comment: Do you need to write all the code inside the `process` method?
Comment: @Unmitigated, that is just my method to start with, I can write classes and other methods also if needed.
Comment: Do you know the maximum user id?
Comment: @learner I understand your question. I'm asking if you know the bounds for the maximum user id or not.
Comment: @Unmitigated, I updated my question now with details under constraints.
Answer: You can use a disjoint set, starting with each group having size 1 and combining the sizes when merging.
public int process(int m, int[][] arr) {
    class DS {
        static int[] p = new int[100001];
        static int[] size = new int[100001];
        static int find(int x) {
            return x == p[x] ? x : (p[x] = find(p[x]));
        }
        static int merge(int x, int y) {
            int rx = find(x), ry = find(y);
            if (rx != ry) {
                p[rx] = ry;
                size[ry] += size[rx];
            }
            return size[ry];
        }
        static void init() {
            for (int i = 0; i < p.length; i++) {
                p[i] = i;
                size[i] = 1;
            }
        }
    }
    DS.init();
    int ans = 0;
    for (int[] pair: arr)
        ans = Math.max(ans, DS.merge(pair[0], pair[1]));
    return ans;
}

Answer: This data can be represented as a Disjointed Graph. And the problem boils down to finding the largest connected component in this graph.
For that, we need to iterate over the Vertices (which would represent Users) of the Graph. And for each vertex that hasn't been yet examined, we need to fire a traversal logic to find the size of the group to which this vertex belongs (for that purpose, DFS algorithm implementation is used in code below).
The time complexity of this approach would be linear O(n) (assuming there are n ids) because every Vertex would be examined only once.
class UserGraph {

    private Map<Integer, User> userById = new HashMap<>(); // contains all vertices of the graph

    private UserGraph() {} // no way and no need to invoke this constructor from the outside of the class

    public static UserGraph getInstance(int[][] arr) {
        UserGraph graph = new UserGraph();
        for (int[] connection: arr) {
            graph.addConnection(connection[0], connection[1]);
        }
        return graph;
    }

    public void addConnection(int id1, int id2) { // for simplicity connection would be mutual
        User user1 = userById.computeIfAbsent(id1, User::new);
        User user2 = userById.computeIfAbsent(id2, User::new);
        user1.addFollower(user2);
        user2.addFollower(user1);
    }

    public int getLargestGroupSize() {
        Set<User> seen = new HashSet<>();
        int maxSize = 0;
        for (User user: userById.values()) {
            if (seen.add(user)) {
                int groupSize = getGroupSize(seen, user);
                maxSize = Math.max(maxSize, groupSize);
            }
        }
        return maxSize;
    }

    public int getGroupSize(Set<User> seen, User user) {
        Deque<User> stack = new ArrayDeque<>();
        stack.add(user);
        int groupSize = 0;
        while (!stack.isEmpty()) {
            User current = stack.pop();
            groupSize++;

            for (User follower: current.getFollowers()) {
                if (seen.add(follower)) stack.push(follower);
            }
        }
        return groupSize;
    }

    private static class User {
        private int id;
        private List<User> followers = new ArrayList<>();

        public User(int id) {
            this.id = id;
        }

        public void addFollower(User user) {
            followers.add(user);
        }

        public List<User> getFollowers() {
            return followers;
        }
    }
}

main()
public static void main(String[] args) {
    int[][] arr = {
        {1, 2},
        {3, 4},
        {5, 6},
        {1, 5}
    };

    UserGraph graph = UserGraph.getInstance(arr);
    System.out.println(graph.getLargestGroupSize());
}

Output:
4

Find maximum users in a network


Ember create record with accepts_nested_attributes_for

Question: I've setup my application to work with accepts_nested_attributes_for by doing the following in a serializer:
App.FooSerializer = DS.ActiveModelSerializer.extend DS.EmbeddedRecordsMixin,
    serialize: (record, options) ->
        json = @_super(record, options)

        # re-write the keys for accepts_nested_attributes_for
        json.values_attributes = json.values
        delete json.values

        json

    attrs:
        values: {embedded: 'always'}

This works fine for existing records.
However when I have a new record it doesn't work as expected. In the Ember inspector I end up with 2 foo objects both with the same id for the record created by Rails. One has the unsaved value objects all with a null id the other has the saved value objects with their appropriate id.
Is there a better/more correct way to do this?
Edit:
I realised there was an issue with the JSON coming back from Rails due to the Serializer I was using, I changed that and now only have one record, however it still isn't populating the values association with the correct objects. Those Value objects do exist in the Ember inspector but the association on the Foo object just shows the unsaved records.
Here is a snippet from the JSON response:
{
    "values": [{"id":19582,"value":"9C5601","foo_id":1158,"option_id":2} ...],
    ""foo": {"id":1158,"value_ids":[19581,19582,19583,19584,19585,19586,19587,19588,19589,19590,19591,19592,19593,19594,19595,19596]}
}

There are some more objects in the JSON (for the options a value is associated to) but as I say the Value objects are populated fine in the inspector, just not associated with the updated Foo record.
Also if I go into the ember inspector for a value and click on it's foo relationship I get this error:
Uncaught Error: Assertion Failed: You looked up the 'foo' relationship on a 'value' with id 19596 but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.belongsTo({ async: true })`)

Answer: It turns out I needed to change embedded: 'always' to the following:
values: {
    serialize: 'records',
    deserialize: 'ids'
}

Because my Rails serializer was giving the ids in the response.


Delete a row from mongodb database in azure

Question: I am an azure newbie who has a mongodb database on Azure cloud storage. I am trying to delete a row with a specific value from the Query explorer in Azure, but I keep getting this error. Am I missing something?

delete from users where _id='...' doesnt work
neither does delete * from users where _id='' work
this works perfectly even if am doing SQL on a mongodb database while querying
Comment: If you have a MongoDB database don't you have to use mongo syntax and not SQL? https://docs.mongodb.com/v3.2/tutorial/remove-documents/
Comment: tried to write `delete` in small letters (it's not marked as a keyword in the explorer)? Just guessing at this point, don't know how Azure actually translates the queries.
Comment: @Erik check my update, the select query works perfectly in sql syntax
Comment: i also tried that, no luck
Answer: I think you are using Microsoft DocumentDB (not mongoDB). DocumentDB is available on Azure and supports SQL-like queries.
I suggest taking a look at the documentation: https://azure.microsoft.com/en-us/documentation/articles/documentdb-sql-query/
According to the docs INSERT, UPDATE, and DELETE are only available through the REST API and not in the query language.
Comment: Sami is correct - you're using a DocumentDB database, but with MongoDB compatibility enabled for your collection. The Query Explorer, via the portal, only supports DocumentDB SELECT queries.
Comment: i am using mongodb for sure as i selected it while creating the collection , also if i was using document db i would have the option to edit add remove documents through a visual editor that MS provides only for document db


Annualized Excess Return

Question: I have been given the following formula to calculated Annualized excess return:
<code>Annualized excess return = (1+Monthly excess return)^12-1
</code>
The answer is provided (by the text) as AER = (1-.0036)^12-1 = 4.41%
When I calculate this I get:
<code> (1-.0036)^12 = 0.957645178 therefore (1-.0036)^12 - 1 = -0.042354822
</code>
On this basis I think the answer should be -4.23% and not 4.41%? Can anyone help me confirm or contradict this assertion?
Comment: Plus versus minus: $(1+.0036)^{12}=1.044066...\approx1.0441$ --> return of $4.41\%$. Either you got the sign wrong or there is a typo in the source you are referring to.
Comment: Thanks Richard - it is a typo in the source. I should have seen it in the formula which correctly specifies it.
Comment: I tried, but not allowed to.
Answer: Plus versus minus: $(1+.0036)^{12}=1.044066...≈1.0441\rightarrow$ return of $4.41\%$.
Either you got the sign wrong or there is a typo in the source you are referring to.

Annualized Excess Return


Array is returning an Extra "1" in the end (Codeigniter)

Question: My array is returning an extra 1 in the end.
here is the array:
$item = array(
       'numberofitems' => $_POST['numberofitems']
     );

and here is the result:
Array (
 [numberofitems] => 4 ) 1

View Code:

  result() as $row): $i++; ?>
  customer_name
  ?> customer_address ?> ">

I have tried all ways to get this "4" but somehow it makes it to "41" by adding that "1" in the end. Please let me know whats i'm doing wrong
Comment: Show us more lines of your code. Something else is adding the `1`
Comment: try `print_r($item);` .... and not `echo print_r($item);`
Comment: SHow us how you output that array result
Comment: Are you using something like `echo print_r($item);`?
Comment: I think that "1" is array's length :)

How do you print them?
Comment: @RiggsFolly I'm using echo '',print_r($item),'';
Comment: I also tried getting this in another variable that makes it "41"
Answer: If you use print_r() and do something like :
echo '
', print_r($data), '
';

You will display print_r() $data and what print_r() returns too (eg. 1).
Like anyone, you just want display print_r() argument, so you must do :
echo '
';
print_r($data);
echo '
';

Or :
echo '
', print_r($data, TRUE), '
';


A Content Type with custom fields

Question: How would you suggest approach this using Drupal 7?
I'd like to create a 'Video' content type with the usual videos fields but I would also like each individual video content type to have many images attached, with each image having fields of it's own.
Basically, each content type would require one video and many images, with fields relevant for each image.
I've looked for duplicate questions and can't see anything that fits but if you know of something please point me in the right direction.
Thanks,
Answer: Field Collection is a good option if the images will not be re-used across multiple Video content types. If you need to re-use the Images (and their field values) across multiple Video nodes, another option is to create a separate "Image" content type and use the Entity Reference module to link the Image nodes to the relevant Video nodes.
Comment: This handled my problem perfectly. Cheers Sheena!
Answer: It sounds like the Field Collection module might help you out.

A Content Type with custom fields


Why stream created with Spliterators is not being processed in parallel?

Question: This is probably very basic, but I am not a Java person. Here is my processing code which simply prints and sleeps:
    private static void myProcessings(int value)
    {
        System.out.println("Processing " + value);

        try
        {
            Thread.sleep(2000);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }

        System.out.println("Finished processing " + value);
    }

Now, this parallel stream seems to work in parallel:
    IntStream iit = IntStream.rangeClosed(1,3);
    iit.parallel().forEach(Main::myProcessings);

    // output:

    // Processing 2
    // Processing 1
    // Processing 3
    // Finished processing 3
    // Finished processing 2
    // Finished processing 1

But this one (made from an Iterator) does not:
    static class MyIter implements Iterator<Integer>
    {
        private int max;
        private int current;

        public MyIter(int maxVal)
        {
            max = maxVal;
            current = 1;
        }

        @Override
        public boolean hasNext()
        {
            return current <= max;
        }

        @Override
        public Integer next()
        {
            return current++;
        }
    }

    MyIter it = new MyIter(3);
    StreamSupport.stream(Spliterators.spliteratorUnknownSize(it, 0), true)
                 .forEach(Main::myProcessings);

    // output:

    // Processing 1
    // Finished processing 1
    // Processing 2
    // Finished processing 2
    // Processing 3
    // Finished processing 3

What am I doing wrong in the custom Iterator version? (I am using Java 8)
Comment: https://stackoverflow.com/a/48308511/4949750 - check this answer - it explains exactly what is the problem here. Spliterators will split the work only with big enough collections, like 10000+ elements. If you decrease sleep time and increase amount of elements your code works just fine.
Comment: You have `parallel()` in the one but not in the other?
Comment: @akuzminykh I used `.parallel()` in the later one too, no use. Because the 2nd parameter in `StreamSupport.stream()` already makes it parallel.
Comment: @akuzminykh `stream(Spliterators.spliteratorUnknownSize(it, 0), true)` - second parameter - `true` is a flag whether or not the result stream have to be parallel.
Comment: related and possibly duplicate https://stackoverflow.com/questions/46709455/understanding-sequential-vs-parallel-stream-spliterators-in-java-8-and-java-9, it mentions that the `true` parameter DOES NOT MAKE the stream `parallel`
Comment: From javadocs for [Spliterators#spliteratorUnknownSize](https://docs.oracle.com/javase/8/docs/api/java/util/Spliterators.html#spliteratorUnknownSize-java.util.Iterator-int-) "The spliterator is not late-binding, inherits the fail-fast properties of the iterator, and implements trySplit to permit **limited** parallelism." It could be the factor here - the "limited parallelism" whatever it means in this case.
Comment: @Amongalen Can you suggest a way?
Answer: There was a flaw in Spliterators.spliteratorUnknownSize() implementation. I fixed it in Java 19, see JDK-8280915. Since 19-ea+19-1283 early access build the problem is not reproduced anymore, your code is parallelized correctly without explicit size specification:
Processing 2
Processing 3
Processing 1
Finished processing 3
Finished processing 1
Finished processing 2

Answer: One way is to give an estimate of the size of the stream:
Spliterators.spliterator(it, 3, 0);

The number (3 here) doesn't have to be precise, but if you give say 10000, only one thread will be used for an actual size of 3. If you give say 10, multiple threads will be used, even with a size of 3.
The estimate (3 in my example)  is used to determine the size of the batches (number of tasks sent to one thread before moving on to the next thread). If you provide a large estimated number and only submit a few tasks, they will probably all be grouped and run on the first thread and nothing will be sent to the second thread.
Comment: An `Iterator` doesn't have to be thread safe, which is part of the problem. The Stream has to build parallel processing atop a source that doesn't support parallel processing.
Comment: To my experience, with the reference implementation, specifying an entirely bogus number still works much better than streams of unknown size. E.g., being off by factor five usually is no problem. With unknown size, you're running into the problem described in [this comment](https://stackoverflow.com/questions/48307102/parallelism-with-streams-created-from-iterators/48308511#comment83607190_48308595). Even after all source elements have been buffered, the implementation will not understand that it know knows the exact size.
Comment: @mshsayem my understanding is that the number is used to determine the size of the batches (number of tasks sent to one thread before moving on to the next thread). If you provide a large estimated number and only submit a few tasks, they will probably all run on the same thread.
Comment: The advice to specify imprecise size is incorrect. `Spliterators.spliterator` accepts the exact size, rather than estimation, and subsequent stream operations may trust it. E.g., replace stream with `List result = StreamSupport.stream(Spliterators.spliterator(it, 10, 0), true).toList();` and you'll see that the list is oversized.
Comment: The problem is, my objects are a bit bulky; say, images stored in db, 80kB each. I can't use 10000, not even 1000. I am planning to fetch 250 objects from dB; the driver provides an iterator for memory-issues. I have a processor function which processes (CPU bound) those objects. Just wanted to use the CPU cores.
Comment: It seems, if I have `c` cpu-cores, for estimate, `n` and actual number of data, `m`: if `n>=m` it spawns `c` threads (or `n`, whichever is lower), and those threads complete processing all. But if `n<m`, `c` threads will continue to work up to `c*n` tasks. The rest `m-c*n` tasks will be handled by the main thread sequentially. So for the case mentioned in the question where `n=0`; all the tasks are being processed sequentially.
Comment: @assylias Now the question is, if I provide a large number as an estimate but actual number of data is much lower, will there be any negative impact (memory/perforrnamce)?
Comment: You are absolutely right! Now, that makes sense; Many thanks! You could update the answer to reflect this _batch_ issue.


Downvoting and Closing

Question: I've been noticing quite a few questions being downvoted as well as vote-closed. In pretty well every situation, the close votes are pretty fair. Many of these questions however are salvageable.
This question for example:
https://economics.stackexchange.com/questions/8350/determine-how-much-an-individual-will-save-depending-on-varying-values-in-their
As it is now, it is a basic copy paste homework question not formatted particularly well.
A close vote is preferred in this situation because it a lot easier to undo. A question will show up in the review queue as edited after closing and people can decide what to do. A down vote will remain their long after a question changes from a bad to a good question.
Don't downvote questions which could be simply closed.
Comment: Also the issue of downvoting and voting to close without any comments still persists, like it did earlier
http://meta.economics.stackexchange.com/questions/174/adding-comments-along-with-downvotes
http://meta.economics.stackexchange.com/questions/1239/more-downvoting-issues
I think if you have time enough to pass intelligent judgement you have time enough to write a short comment. Apologies if you think this might be better discussed in a separate question, I thought it appropriate because downvoting and closing are exactly the areas affected.
Answer: Down votes can be changed as well once the question has been edited. Though I confess that I agree that this is less likely to be reversed since the individual must see it again and then undownvote (or upvote) it as opposed to being handled by the community.
If an edited question that you think is appropriate for the site has downvotes then you should upvote it. IMO, we need more votes whether they are up or down votes.
Comment: I'd rather more of both. I think we should be saving the down votes for the bad, irrelevant questions and closing those the are salvageable.

Downvoting and Closing


Example of Baire Space

Question: Can anybody supply an example of a Baire Space, that is neither locally compact nor metrizable. I would be gratefull also for some references.
Comment: Some such examples were discussed in comments to [this question](http://math.stackexchange.com/questions/88483/every-space-is-almost-baire).
Answer: As a trivial example, let $X,Y$ be Baire spaces with $X$ not locally compact and $Y$ not metrizable, and consider the disjoint union of $X,Y$.
Answer: The Sorgenfrey line is one example. It is not locally compact nor is it metrizable. Here is a paper showing that it is a Baire space..

Example of Baire Space


Using AFL (Australian Rules Football) data to predict Brownlow votes

Question: First, let me set the scene.
For each AFL match played, the umpires of that match decide who they deem to be "best and fairest" players on the ground. They allocate 3 votes to the most deserving player, 2 votes to the next deserving and 1 vote to the 3rd most deserving player. Towards the end of the season these votes are tallied and the player with the highest wins the Brownlow Medal.
The problem I am trying to solve is to try and predict the allocation of these votes based on the match statistics which are publicly available. For example, see this game: http://afltables.com/afl/stats/games/2015/031420150402.html
I am taking the statistics of each match (marks, kicks, handballs, goals etc.) for each player and using them to try and predict the BR (Brownlow vote) value assigned to each player for the match.
Unfortunately, I'm fairly new to machine learning and not sure of the best way to structure my data and what algorithms to try etc. I am using this project as a means of learning more about machine learning. I'm currently working with a Python stack, using NumPy, Scikit Learn and also Keras.
Currently, each vector in my input data is the statistics table for each player for a given match, flattened. Since there are usually 44 players in each match, and I am only interested in 21 of the supplied stats, each vector is of length 44*21 = 924. I do perform some column-wise normalization on the input data, before flattening the table to reduce the impact of a low-activity vs high-activity match.
The target data is a vector which contains the brownlow vote assigned to the i-th player (e.g. [0, 0,....,3, 0, 2, 0, 0, 1]), and is of length 44.
I'm processing data from matches spanning years 1998-2015 inclusive, around 3200 matches.
My questions are:

Is my current approach for formulating the input data sound? Does it make sense to normalize and flatten the input data in this way? As far as I could tell, most machine learning classifiers require data to be flattened (i.e. they do not take a 2-d matrix input)
What would be some good candidate algorithms for me to use to solve this problem?

To me this seems to be a Multi-output classification problem, as the output is a vector with possible values 0, 1, 2 or 3. Thus I have tried using a MultiOutputClassifier with a RandomForestClassifier with terrible results - I get an accuracy of 0.0?
I've also tried using a Keras basic Sequential model, again with terrible results - my accuracy is around 0.15?
Here is the code I'm using to process Pipe-delimited files with stats in them (each file is one match):
<code>import sys
import os
import numpy as np
import fnmatch
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from keras.layers import Input, Dense
from keras.models import Model

AFL_STAT_HEADER = ["#", "S_ON", "S_OFF", "T_NM", "P_NM", "KI", "MK", "HB", "DI", "GL", "BH",
              "HO", "TK", "RB", "IF", "CL", "CG", "FF", "FA", "BR", "CP", "UP", "CM",
              "MI", "1%", "BO", "GA", "%P"]

AGG_STATS = set(["KI", "MK", "HB", "DI", "GL", "BH", "HO", "TK", "RB", "IF",
             "CL", "CG", "FF", "FA", "CP", "UP", "CM",
             "MI", "1%", "BO", "GA"])

NON_NUMERIC_STATS = set(["T_NM", "P_NM"])

EXTRACT_STATS = ["KI", "MK", "HB", "GL", "BH",
              "HO", "TK", "RB", "IF", "CL", "CG", "FF", "FA", "CP", "UP", "CM",
              "MI", "1%", "BO", "GA", "%P"]

POS_STATS = ["MK", "DI", "GL", "BH",
              "TK", "RB", "IF", "CL", "FF", "CP", "UP", "CM",
              "MI", "1%", "BO", "GA"]

NEG_STATS = ["CG", "FA"]

def parse_match_stats(psv_path):
    stats = []
    with open(psv_path, 'r') as f:
        lines = f.readlines()
        for line_num, line in enumerate(lines):
            if (line_num == 0):
                continue

            sp = line.split("|")
            player_stats = {}
            for i, elem in enumerate(sp):
                stat = AFL_STAT_HEADER[i]
                if stat in NON_NUMERIC_STATS:
                    player_stats[stat] = sp[i]
                else:
                    player_stats[stat] = float(sp[i])

            stats.append(player_stats)
    return stats

def preprocess_stats(stats):
    feature_matrix = []
    targets = []
    labels = []
    for p_stat in stats:
        row = map(lambda x: p_stat[x], EXTRACT_STATS)
        feature_matrix.append(row)
        targets.append(p_stat["BR"])
        labels.append(p_stat["T_NM"] + ": " + p_stat["P_NM"])

    f_norm = preprocessing.normalize(feature_matrix, axis=0)
    return (labels, f_norm, targets)

labels = []
features = []
targets = []
for root, dirnames, filenames in os.walk(path):
    for filename in fnmatch.filter(filenames, '*.psv'):
        psvpath = os.path.join(root, filename)
        stats = parse_match_stats(psvpath)
        preprocessed = preprocess_stats(stats)
        labels.append(preprocessed[0])
        features.append(np.array(preprocessed[1]).flatten())
        targets.append(preprocessed[2])
X = np.array(features)
y = np.array(targets)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=0)

forest = RandomForestClassifier(n_estimators=924, random_state=1)
clf = MultiOutputClassifier(forest, n_jobs=-1)
clf.fit(X_train, y_train)
clf.score(X_test, y_test)

model = Sequential([
    Dense(64, input_dim=924),
    Activation('relu'),
    Dense(44, init="normal"),
    Activation('softmax'),
])
model.compile(optimizer='adam',
              loss='mean_squared_error',
              metrics=['accuracy'])
model.fit(X_train, y_train, nb_epoch=50, batch_size=10)
score = model.evaluate(X_test, y_test, batch_size=10)
</code>
Answer: I find problematic 2nd and 3rd most deserving players, because those are ordinal; not nominal variables. You should use ordinal methods.
For example I would try to achieve a metric that maps statistics of each match. The metric should be capable to map all the players and rank them. The ranking should match with the votes.
I would first play around the data. I would drop 2nd and 3rd off or merge with 1st and use binary classifier for a start and see what happens.
Comment: Yes that sounds like a good idea. I had considered just a simple metric in the beginning - summing normalized statistics for each player.

I think another option is to train separate binary classifiers to find the players deserving of 3 votes, 2 votes and 1 vote. To train the classifier for 2 votes, simply remove the stats of the player who got 3 votes. Repeat for the next. Will have to try it out and report back :)
Comment: No, that is not what I meant. Training a binary classifier for each does not make sense. You would be evaluating 2nd bestness and 3rd bestness. If your research would be whether the 2nd and 3rd are evaluated based on different criterion to 1st, it would make sense. You need a metric that tells how good a player performed. That you can rank, and the ranking should match as well as possible to those top three. Binary classifier tells you what makes the top players distinct  from the rest.


UFW doesn't block the mongodb port

Question: I have blocked 27018 using ufw but still, I can connect to that port from my computer using mongo command line tool.
is there any solution to this?
I tried to run ufw reload but result is still the same
Comment: I can confirm a bug in docker and/or UFW. My MongoDB got hacked despite blocking the port  in UFW.
Answer: It is possible that traffic from localhost is not affected by ufw.
You might try to add from 127.0.0.1 to your rule and see if that canges anything.
Else, I would recommend to block that port directly in iptables.
EDIT: To completely block port 27018, run the following command:
iptables -I INPUT 1 -p tcp --dport 27018 -j DROP
(You might want to try iptables -I FORWARD 1 -p tcp --dport 27018 -j DROP too, to avoid forwarding anything on this port)
Note: This does block traffic to port 27018 from EVERYWHERE, even from 127.0.0.1. If the rule vanishes after a reboot, read up on how to preserve iptable rules across reboots (Which may not be advised because of ufw)
As a personal recommendation:
Though ufw is a really easy to learn and use firewall, I would recommend to learn using iptables directly, because it offers more fine-tunable options.
Comment: this is the remote machine i am connecting from my own computer so im not on local machine
Comment: @nikoss You said in your question that you still can connect to that port from your "local machine", so I thought you meant that you host mongodb on the same computer you are trying to connect from. Could you supply the output of `iptables -vnL` (sudo may be needed)? Also, what is the default for incoming packages sent to?
Comment: https://pastebin.com/yZUySjqG this is the output
Comment: It may be possible that Docker is tampering with your ufw rules. See my updated answer on how to block the port directly in iptables to bypass all other rules (like the ones from Docker)
Comment: can you advise me a real good guide for iptables ?
Comment: Those two helped me the most: https://help.ubuntu.com/community/IptablesHowTo for the commands and https://www.howtogeek.com/177621/the-beginners-guide-to-iptables-the-linux-firewall/ for understanding the technics behind iptables. Note: I have been using Solution #2 on the ubuntu page to make my iptables rules persistent. Also, you might want to remove ufw and reboot your machine before making your iptables changes persistent.
Comment: i just tried this now but still i can connect to mongodb
Comment: My advice: Disable Docker iptables with this Guide https://linuxconfig.org/how-to-disable-docker-s-iptables-on-systemd-linux-systems, uninstall ufw and reboot to start with clean iptables and try the iptables command from above again. Also, are you sure that the communication for mongodb only uses this single port?

UFW doesn't block the mongodb port


Speeding up full screen image drawing on iPhone 3G

Question: I am developing an app which plays interactive real time streaming video.  I use FFMPEG (don't worry, I'll be releasing my source code) to decode a MPEG2/H264 RTP stream.  I simply cannot get the iPhone 3G to draw a screen full of pixels faster than 5 times per second.
I've tried a OpenGL texture which was just a slow.  I've also tried an array of 2D vertexes covering the entire screen and using glDrawArrays but that yielded 5 FPS as well.  For now I've stuck to simply drawing a CGImage onto my view which gives me about 7-8 FPS.
From what I gathered, the private CoreSurface framework seems to be the only way.  Anyone have any tips or tricks to get at least 20-30 FPS?  I'd hate to restrict my app to only the 3GS and iPod touches.
Thanks,
Andrew
Comment: While nobble, sometimes people just have to upgrade. If you create a killer app for 3GS, you create market forces which lure more people into upgrading, which makes this a non-issue.
Comment: How are you uploading your textures to GL ES?
Comment: @genpfault My frame is 480x320 so I add padding to the right and bottom to make it 512x512 and then pass the pointer to glTexImage2D.  I've also tried with glTexSubImage2D with the same results.
Comment: Andrew: Run Instruments with the Time Profiler instrument and see where your app is bogging down.
Comment: Releasing the source is only part of the story - H.264 is covered by patents, which is a totally separate issue to the license of the implementation.
Answer: If you want to play H.264 and MPEG2 video on the iPhone, why are you doing the decoding yourself?  What do you need that MPMoviePlayer doesn't cover?
Comment: The only reason I do not use the MPMoviePlayerController is because I need to display the video in realtime.  Even with HTTP Live Streaming, the video is delayed too much.
Answer: If you are decoding in software, you're never going to get a good frame rate. Even on faster hardware (iPhone 3GS and 2nd/3rd gen iPod touches), you're going to drain the battery very quickly.


flutter_local_notifications onNotificationReceived method - Flutter

Question: Too long to read: The problem
Basically, I am looking for an onMessageReceived() callback but that works with flutter_local_notifications so I can handle and show the data to the user. This plugin only supports handling the onNotificationTap() action.

How am I expected to handle the message when the user receives it, for example, if they have Do Not Disturb on? Even if the local notification doesn't show, I need to show an Overlay at least, triggered by some onMessageReceived() function.
How can I update the notificationCount in my database when a local notification is received (scheduled)?

Description
In my project I am using:

Firebase Cloud Messaging (FCM)
flutter_local_notifications package.

When an event is scheduled in my app, the process is the following:

POST request to FCM with data only message.
My app receives the message through the onMessageReceived() callback.
Almost instantly I get 'Got a message whilst in the foreground!' message. This was triggered by the instant FCM data message.
The data inside the message triggers flutter_local_notifications to schedule a notification.
This scheduled local notification, received at a later date, cannot be handled (no OnMessage() function).

I don't schedule a notification directly on FCM because you can't do that from a post request (weird), but that would solve all my problems.
Problem

When the notification gets to the user's device, there is no way of handling the message (foreground or background)
I cannot display an Overlay with the notification, in case of the user being in the foreground
I cannot automatically update the notificationCount in my Firebase Realtime Database

Basically, I am looking for an onMessageReceived() callback but that works with flutter_local_notifications so I can handle and show the data to the user. This plugin only supports handling the onNotificationTap()` action.
Example of my process
This is what FCM has that flutter_local_notifications doesn't. Triggered when a notification is received by my app:
FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
print('Got a message whilst in the foreground!');

[...]

if (scheduledDate != null) {
//using flutter_local_notifications
  sendScheduledLocalNotification(itemTitle, 'Due Today', formattedDate);
//this notification, received at a later date, cannot be processed with this same function because it doesn't use FCM
}

//only shown with instant notifications (not scheduled)
if (notification != null) {
  showOverlayNotification((context) {
    return LocalNotificationOverlay(
      title: notification.title!,
      subtitle: notification.body!,
      imageUrl: notification.imageUrl!,
    );
  }, duration: Duration(seconds: 3));
}
  }

});

Comment: Do you get `Got a message whilst in the foreground!`? Why do you say you can't show an overlay?
Comment: @NoobN3rd The on message notification is triggered instantly when FCM sends the message to the device. My mechanism for Scheduled notifications is that I send a data only message with FCM (no overlay is shown because there is no notification), and instead I schedule one using sendScheduledLocalNotification(). THIS is the problem. When THAT scheduled notification gets to the device (at a later date), this onMessage function is not called. Let me know if you need anything else!
Comment: I've edited the code to make it clearer.
Answer: Yes, as far as I know we don't have the same stream option to listen to the notifications in the system tray for flutter_local_notifications as we have for FCM.
You can check this answer, It  might help you.
I guess in the end you'd better do it in the back-end, and again this scheduled message being send/received via FCM.
I don't know about the mechanism that you're using and the function that sends the notification to user, but you can ignore sending notification to user if it has information about scheduling. Based on your code, scheduledDate and formattedDate are aware of it. So in your cloud function that sends the notifications you can instead of sending a notification, doing some task or triggering something(similar to the attached answer) and this will schedule sending that notification based on its time. Then in front-end for example you can update your databases every time you get a notification from FCM, because you didn't send them in the first place and you actually scheduled sending them in the planed time.