Stochastic process over the expected time of tasting all $N$ dishes of a restaurant

Question: Exercise :

Every time you visit a certain restaurant, you choose randomly one of its $N$ dishes. What is the expected number of visits you have to make to the restaurant until you taste all of its dishes ?

Attempt / Question :
Picking randomly one of its $N$ dishes, obviously means that you have $1/N$ chance of picking every dish. Now, each time you visit the restaurant and you pick a different dish than all the others, the probability of picking a different dish again becomes smaller, as $1/(N-n)$, where $n$ is the number of different dishes you've picked.
Now, I know that expected time (hitting time) problems of such can be solved by modelling your process into a Boundary Value Problem (BVP) of the form (which will give an answer to the expected time $\mathbb{E}[T_A | X_0 = x] = \mathbb{E}_x[T_A]$) :
$$\begin{cases} Lg(x) = -1, x \notin A \\ g(x) = 0, x \in A\end{cases}$$
if $A \subset \mathbb{X}$ and $T_A = \inf\{k \geq 0 : X_k \in A\}$ the time of the first arrival at $A$.
On this particular problem, though, I find myself stuck on trying to model it into an boundary value problem.
I would really appreciate any explanation on how to proceed.
Comment: This is the [coupon collector problem](https://en.wikipedia.org/wiki/Coupon_collector%27s_problem).
Answer: Let $f(n)$ be the expected time to sample the remaining $n$ dishes, given that you have sampled $N-n$ dishes already. We are interested in calculating $f(N)$.
It is easy to see that $f$ satisfies the recursion
\begin{align*}
f(n) &= \frac{N-n}{N}[f(n)+1] + \frac{n}{N}[f(n-1)+1] \\
&= 1 + \frac{N-n}{N}f(n) + \frac{n}{N}f(n-1).
\end{align*}
We also have the boundary condition $f(0)=0$. We can simplify the equation above to find
$$f(n) = \frac{N}{n} + f(n-1).$$
This gives us that
$$ f(n) = \sum_{k=1}^{n}\frac{N}{k}, $$
so that
$$ f(N)= \sum_{k=1}^N \frac{N}{k}. $$


Unpacking interactions in LME4 with repeated measures design

Question: I am conducting a study where I look at the interaction of 3 categorical variables and 1 continuous variable. However, I want to be able to see all the possible comparisons of these 4 variables. In the past, I have used  emmeans but I noticed that  emmeans only takes the lowest and highest value of the continuous variable which does not make sense in repeated measures since it basically takes the lowest participant compared to the highest participant.

Linear mixed model fit by REML. t-tests use Satterthwaite's method ['lmerModLmerTest']
Formula: RT ~ Domain * ShiftType * TrialType * VA_k + (1 | Probe) + (1 |      Story_order) + (1 | Subject)
   Data: bsmu[bsmu$ACC == 1, ]

REML criterion at convergence: 79528.9

Scaled residuals:
    Min      1Q  Median      3Q     Max
-2.2523 -0.4384 -0.1779  0.1482 12.8338

Random effects:
 Groups      Name        Variance Std.Dev.
 Probe       (Intercept)  169631   411.9
 Subject     (Intercept)  545749   738.7
 Story_order (Intercept)  101769   319.0
 Residual                3042405  1744.2
Number of obs: 4472, groups:  Probe, 380; Subject, 60; Story_order, 8

Fixed effects:
                                                Estimate Std. Error      df t value Pr(>|t|)
(Intercept)                                      2254.31     228.51   80.13   9.865 1.74e-15 ***
DomainL2                                          268.94     188.33 4375.18   1.428   0.1534
ShiftTypeNo Shift                                 -30.19     200.03 1992.88  -0.151   0.8800
ShiftTypeUnchanged                                244.29     201.03 1959.52   1.215   0.2244
TrialTypeSpace                                    482.29     206.74 2100.11   2.333   0.0198 *
VA_k                                              150.41     105.24  170.10   1.429   0.1548
DomainL2:ShiftTypeNo Shift                       -132.44     264.37 4376.51  -0.501   0.6164
DomainL2:ShiftTypeUnchanged                      -193.74     265.03 4372.25  -0.731   0.4648
DomainL2:TrialTypeSpace                          -300.61     276.90 4372.10  -1.086   0.2777
ShiftTypeNo Shift:TrialTypeSpace                  -78.89     289.34 2148.38  -0.273   0.7851
ShiftTypeUnchanged:TrialTypeSpace                -444.28     289.46 2117.47  -1.535   0.1250
DomainL2:VA_k                                     -97.90     101.58 4222.47  -0.964   0.3352
ShiftTypeNo Shift:VA_k                             56.42     101.62 4242.86   0.555   0.5788
ShiftTypeUnchanged:VA_k                           -82.56     100.25 4236.84  -0.824   0.4103
TrialTypeSpace:VA_k                                39.49     104.60 4268.38   0.377   0.7058
DomainL2:ShiftTypeNo Shift:TrialTypeSpace         198.60     385.45 4374.32   0.515   0.6064
DomainL2:ShiftTypeUnchanged:TrialTypeSpace        446.45     385.71 4379.42   1.157   0.2471
DomainL2:ShiftTypeNo Shift:VA_k                    53.32     142.70 4224.51   0.374   0.7087
DomainL2:ShiftTypeUnchanged:VA_k                  292.02     142.67 4209.58   2.047   0.0407 *
DomainL2:TrialTypeSpace:VA_k                      164.48     148.53 4217.14   1.107   0.2682
ShiftTypeNo Shift:TrialTypeSpace:VA_k            -101.93     148.10 4262.76  -0.688   0.4913
ShiftTypeUnchanged:TrialTypeSpace:VA_k             55.99     145.95 4256.12   0.384   0.7013
DomainL2:ShiftTypeNo Shift:TrialTypeSpace:VA_k   -152.50     208.23 4232.78  -0.732   0.4640
DomainL2:ShiftTypeUnchanged:TrialTypeSpace:VA_k  -422.48     206.97 4219.86  -2.041   0.0413 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Correlation matrix not shown by default, as p = 24 > 12.
Use print(x, correlation=TRUE)  or
    vcov(x)        if you need it
```

Answer: I wasn't entirely sure about what you mean by all possible comparisons, but one thing you could do would be to compare the continuous predictor's slopes between different levels of your categorical predictors. For this, you can use emmeans emtrends:
(Va_k seems to be the continuous predictor. I'll use the Shifttype as the example categorical predictor):
library(emmeans)
em<-emtrends(model, "ShiftType", var="Va_k")
pairs(em)

Edited to add: for 3-way interactions you can similarly use
em2<-emtrends(model, ~ShiftType|TrialType, var="Va_k")
pairs(em2)

but I suspect there may be some better way to do the latter (better than just running all possible contrasts). For instance this and this response here might be useful.
Comment: This is exactly what I needed! Thank you so much!
Comment: Nice, I'm glad it helped!


Jquery popup in table not showing up

Question: I probably have a stupid error somewhere, but I am learning.
I have a table that is dynamicly loaded from DB and each row has it's own ID
Now in that table I have this:
<code><button type="button" class="btn preview" data-id="'.$var['id'].'">
<i class="fa fa-eye"></button>
</code>
then in script tags lower I have this
<code>$(document).ready(function() {

           $('#pop_up').dialog({
            title: "Title",
            resizable: true,
            autoOpen:false,
            modal: true,
            width:"350px",
            height:"350px",
            buttons: {
               text:"Close",
               click: function() {
               $( this ).dialog( "close" );
                                           }}
         });
         $('#table_id').on('click', '.preview', function() {
               var uid = $(this).attr('data-id');
               $('#pop_up').load("filename.php?uid="+uid, function(){
                   $('#pop_up').dialog('open');
               });
         });

   });
</code>
there is one other button in the same td as this button. And when I click on this one nothing happens, but if I this button a few times in succession quickly the other one opens. That is not the behavior I expected.
Answer: I realized what was my problem. I had my js in the wrong file and that file was not loaded in the view where I was clicking the button. Silly mistake.

Jquery popup in table not showing up


Hook for adding values to add node page

Question: I'm searching for a hook in Drupal 8 API for adding values to a add content form.
What hook can I use to alter values from /node/add/movies_movie page?
Answer: Think you are looking for the form alter hook here: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21form.api.php/function/hook_form_alter/8.2.x
Answer: Inside your module, there is a [your-module].module file where you can write hook_form_alter().
/**
 * Implements hook_form_alter().
 */
 function module_name_form_alter(&$form, FormStateInterface $form_state, $form_id) {
   if ($form_id == 'node_movies_movie_form') {
     // Your code goes here.
     ...
     ...
   }
 }

Comment: And of course don't forget to clear cache after implementing `hook_form_alter()`.

Hook for adding values to add node page


Diffable Data source with more than one section using core data

Question: WWDC 2019 was really packed with new stuff for iOS and the new data sources for TableViews and CollectionView which is UITableViewDiffableDataSource .
I have successfully integrate the above new data source with Core data , delete and insert new record working without any issue , unfortunately I have an issue with move items from section to another , the issue appears if I'm trying to move the last cell in the section .
Below is my code :
Table View Setup
private func setupTableView() {
       diffableDataSource = UITableViewDiffableDataSource<Int, Reminder>(tableView: remindersTableView) { (tableView, indexPath, reminder) -> UITableViewCell? in
           let cell = tableView.dequeueReusableCell(withIdentifier: "SYReminderCompactCell", for: indexPath) as! SYReminderCompactCell
        var reminderDateString = ""
        let reminderTitle = "\(reminder.emoji ?? "") \(reminder.title  ?? "")"

        if let date = reminder.date {// check if reminder has date or no , if yes check number of todos and if date in today
            let dateFormatter = SYDateFormatterManager.sharedManager.getDateFormaatter()
            dateFormatter.dateStyle = .none
            dateFormatter.timeStyle = .short
            reminderDateString = dateFormatter.string(from: date)
        }

            let toDosList = SYCoreDataManager.sharedManager.fetchAllToDosToOneReminder(reminder: reminder)
                 cell.indexPath = indexPath
                 cell.showMoreDelegate = self
                 cell.initializeToDosCompactView(toDoList: toDosList ?? [],reminderTitleText: reminderTitle,reminderDateText: reminderDateString)
                 cell.changeTextViewStyle(isChecked: reminder.isCompleted)

           return cell
       }

    setupSnapshot(animated: true)
   }

Create a NSDiffableDataSourceSnapshot with the table view data
private func setupSnapshot(animated: Bool) {
    diffableDataSourceSnapshot = NSDiffableDataSourceSnapshot<Int, Reminder>()

    for (i , section) in (fetchedResultsController.sections?.enumerated())! {
        diffableDataSourceSnapshot.appendSections([i])
        let items = section.objects
        diffableDataSourceSnapshot.appendItems(items as! [Reminder])
        diffableDataSource?.apply(self.diffableDataSourceSnapshot, animatingDifferences: animated, completion: nil)
    }

}

NSFetchedResultsControllerDelegate for sections and rows
     func controller(_ controller:
    NSFetchedResultsController<NSFetchRequestResult>, didChange
    anObject: Any, at indexPath: IndexPath?, for type:
    NSFetchedResultsChangeType,
   newIndexPath: IndexPath?) {

    switch type {
    case .insert:
        if let indexPath = newIndexPath {
            let section = fetchedResultsController.sections![indexPath.section]
            self.diffableDataSourceSnapshot.appendItems(section.objects as! [Reminder], toSection: indexPath.section)
            self.diffableDataSource?.apply(self.diffableDataSourceSnapshot, animatingDifferences: true)

        }
        break
    case .update:
        break
    case .delete:

        if let indexPath = indexPath {
            guard let item = self.diffableDataSource?.itemIdentifier(for: indexPath) else { return }
            self.diffableDataSourceSnapshot.deleteItems([item])
            self.diffableDataSource?.apply(self.diffableDataSourceSnapshot, animatingDifferences: true)
        }
        break
    case .move:
        if let indexPath = indexPath {
            guard let item = self.diffableDataSource?.itemIdentifier(for: indexPath) else { return }
            self.diffableDataSourceSnapshot.appendSections([indexPath.section])
            self.diffableDataSourceSnapshot.deleteItems([item])
            self.diffableDataSource?.apply(self.diffableDataSourceSnapshot, animatingDifferences: true)
        }
        if let newIndexPath = newIndexPath {
            let section = fetchedResultsController.sections![newIndexPath.section]

            // let items = fetchedResultsController.object(at: indexPath)
            print("snapppp" , diffableDataSourceSnapshot.sectionIdentifiers)
            let items = section.objects as! [Reminder]

            self.diffableDataSourceSnapshot.appendItems(items, toSection: newIndexPath.section)
            self.diffableDataSource?.apply(self.diffableDataSourceSnapshot, animatingDifferences: true)
        }
        break
    }
}

func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
    switch type {
    case .insert:
        setupSnapshot(animated: false)
        break
    case .update:
        break
    case .delete:
        let section = self.diffableDataSourceSnapshot.sectionIdentifiers[sectionIndex]
        self.diffableDataSourceSnapshot.deleteSections([section])
                self.diffableDataSource?.apply(self.diffableDataSourceSnapshot, animatingDifferences: true)
        //setupSnapshot(animated: false)

        break
    case .move:
        break
    }
}

Comment: "issue appears" - what issue? Please be more precise in describing what happens. also you have this line `diffableDataSource?.apply(self.diffableDataSourceSnapshot, animatingDifferences: animated, completion: nil)`, it should not be inside for loop. Are you sure you want to apply the snapshot changes in the for loop? I'm pretty sure it's not noticable by the user so i'm not sure it makes sense. i would recommend to move it out of the for loop.
Answer:
To work smoothly with Core Data the data source must be declared as
UITableViewDiffableDataSource<String,NSManagedObjectID>

In setupTableView rename the closure parameter labels with
(tableView, indexPath, objectID) -> UITableViewCell? in

and get the reminder with
let reminder = self.fetchedResultsController.object(at: indexPath)

or
let reminder = try! self.managedObjectContext.existingObject(with: objectID) as! Reminder

Then replace the entire methods
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>,
     didChange anObject: Any,
     at indexPath: IndexPath?,
     for type: NSFetchedResultsChangeType,
     newIndexPath: IndexPath?) { ... }

and
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>,
     didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int,
     for type: NSFetchedResultsChangeType) { ... }

just with
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChangeContentWith snapshot: NSDiffableDataSourceSnapshotReference) {
    self.diffableDataSource.apply(snapshot as NSDiffableDataSourceSnapshot<String, NSManagedObjectID>, animatingDifferences: true)
}

Delete also the method setupSnapshot, it is not needed. After calling performFetch and on any change in the managed object context the framework creates the snapshot properly and calls the delegate method.
Comment: Good answer I would only add that animatingDifferences should be true or false depending on if it is during the initial performFetch.
Comment: May I know do you have any reference source, to discuss why NSManagedObjectID should be used instead of NSManagedObject, in DiffableDataSource? Thanks.
Comment: @CheokYanCheng The related WWDC 2019 Videos.
Comment: Thanks. The closest I can get is https://developer.apple.com/videos/play/wwdc2019/230/ (Making Apps with Core Data). But it doesn't specifically discuss with NSManagedObjectID is used. If you are using NSManagedObjectID, isn't if there is content change, you are not able to detect such? As, 2 objects with different content can have same NSManagedObjectID.
Comment: The `NSManagedObjectID` is just a quick way to identify a specific record. The difference of the two snapshots is determined anyway


How to add dynamic base url in retrofit module with dagger2

Question: I am using dagger2 for my application. I have one module which provides some dependencies like Retrofit, Gson etc.
NetModule.java
@Module
public class NetModule {

    private String mBaseUrl;

    public NetModule(String baseUrl) {
        this.mBaseUrl = baseUrl;
    }

    @Provides
    @Singleton
    SharedPreferences providesSharedPreferences(Application application) {
        return PreferenceManager.getDefaultSharedPreferences(application);
    }

    @Provides
    @Singleton
    Cache provideOkHttpCache(Application application) {
        int cacheSize = 10 * 1024 * 1024; // 10 MiB
        Cache cache = new Cache(application.getCacheDir(), cacheSize);
        return cache;
    }

    @Provides
    @Singleton
    Gson provideGson() {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
        return gsonBuilder.create();
    }

    @Provides
    @Singleton
    OkHttpClient provideOkHttpClient(Cache cache) {
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newBuilder()
                //.addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
                .cache(cache)
                .build();
        return okHttpClient;
    }

    @Provides
    @Singleton
    Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create(gson))
                .baseUrl(mBaseUrl)
                .client(okHttpClient)
                .build();
        return retrofit;
    }
}

NetComponent.java
@Singleton
@Component(modules = {AppModule.class, NetModule.class, Validator.class})
public interface NetComponent {
    void inject(AuthenticationActivity authenticationActivity);
    void inject(PaymentActivity paymentActivity);
}

AppApplication.java
@Override
public void onCreate() {
    super.onCreate();

    mNetComponent = DaggerNetComponent.builder()
            .appModule(new AppModule(this))
            .netModule(new NetModule("https://corporateapiprojectwar.mybluemix.net/corporate_banking/mybank/"))
            .build();

}

This approach was working until I had only one base url for my complete application. Now I have different base Url for AuthenticationActivity and PaymentActivity so I can not send Url in constructor of NetModule in onCreate of Application
Can anyone help me how to add dynamic base Url of retrofit using dagger2.
Answer: You can use @Named annotation Dagger2 user guide (see 'Qualifiers' section'):
In your NetModule.java:
@Provides
@Singleton
@Named("authRetrofit")
public Retrofit provideAuthRetrofit() {
  // setup retrofit for authentication
  return retrofit;
}

@Provides
@Singleton
@Named("paymentRetrofit")
public Retrofit providePaymentRetrofit() {
  // setup retrofit for payments
  return retrofit;
}

In your AuthenticationActivity:
@Inject
@Named("authRetrofit")
Retrofit retrofit;

And finally in your PaymentActivity.java:
@Inject
@Named("paymentRetrofit")
Retrofit retrofit;

Then dagger shall automatically inject Retrofit configured for payments into PaymentActivity and Retrofit configured for authentication into AuthenticationActivity
Comment: Thanks a lot +1. I will try it tomorrow :)


Should I aim to have child documents stored in separate collection

Question: I've constructed some mongoose schemas with a not too complicated parent child structure. When I create my parents I include an array of jsons which match the child schema and the child documents get created ok but don't appear in a separate child collection in mongodb.
However, if I later append some more children then these do appear in the separate child collection in mongodb with a duplicate/reference in the parent (I create them using Model.create as I need to get access to their ObjectId)
As I'm new to NoSQL I'm not sure if I should still be trying to keep a separate collection of the child documents. Are there any negative impacts to having only some of my children appearing in the separate collection?
Minimal sample code
var mongoose = require('mongoose'),
    arrangementSchema = mongoose.Schema({
        abc: String
    }),
    tuneSchema = mongoose.Schema({
        name: String,
        arrangements: [arrangementSchema]
    });

mongoose.connect('mongodb://localhost/jnr_dev');

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {

});

var Arrangement = mongoose.model('Arr', arrangementSchema),
    Tune = mongoose.model('Tu', tuneSchema);

var tune = Tune.create({
    name: 'test'
}, function (err, newTune) {
    newTune.arrangements = [{abc:'abc1'}];
    newTune.save(function () {
        Arrangement.create({
            abc: 'abc2'
        }, function (err, arr) {
            newTune.arrangements.push(arr);
            newTune.save();
        });
    })
});

// and same behaviour with

var tune = Tune.create({
    name: 'test',
    arrangements: [{abc:'abc3'}]
}, function (err, newTune) {
    Arrangement.create({
        abc: 'abc4'
    }, function (err, arr) {
        newTune.arrangements.push(arr);
        newTune.save();
    });
});

Result in Tus collection
 {    "__v": NumberInt(2),    "_id": ObjectId("511037ef60e5af0000000002"),    "arrangements": {
     "0": {
       "abc": "abc1",
       "_id": ObjectId("511037ef60e5af0000000003")
    },
     "1": {
       "_id": ObjectId("511037ef60e5af0000000004"),
       "abc": "abc2"
    }   },    "name": "test" }

Result in Arrs collection
 {
   "abc": "abc2",
   "_id": ObjectId("511037ef60e5af0000000004"),
   "__v": NumberInt(0)
}

Comment: This sounds like an unexpected result. Can you post some complete, runnable, minimal example code here that reproduces the problem so we can help diagnose?
Comment: @A.JesseJiryuDavis Have attached sample. I should've mentioned in the original post I was using mongoose too
Answer: It's the Arrangement.create() call that creates documents in the second collection. I assume you want an array of subdocuments within the Tune collection, only. See:
http://mongoosejs.com/docs/subdocs.html
You should just do:
newTune.arrangements.push({
    abc: 'abc4'
});

newTune.save();

Comment: What about when I have documents of another type `parent2` that also need to reference arrangements. Should I aim to keep a separate collection of arrangements in this case and just reference from the parents using an objectId?
Comment: In that case, yes - if you have two kinds of documents that reference a third kind, it may makes sense to keep them all separate. Please see the discussion of "embedding" and "referencing" here:

http://docs.mongodb.org/manual/core/data-modeling/#data-modeling-decisions

Or this:

http://www.10gen.com/presentations/schema-design-1


FirebaseUI for Web — Auth - how to re-authenticate?

Question: I'm using FirebaseUI for Web — Auth widget to simplify the auth workflow, and I'm stuck with a problem. Everything works OK the first time. But, after I sign in, the widget contents clears away, and the 'Sign in with ...' buttons never come back. Trying to recreate the widget brings up the error "UI Widget is already initialized on the page. Only one widget instance can be initialized per page."
This means that users need to refresh the page to get the sign-in buttons back. Is there a more elegant way?
Answer: Are you rendering the widget in a single page application? If so, this currently won't work. You will have to render the sign in widget in a popup whenever you want the user to sign in.
Answer: As bojeil stated in the first answer (May 2016), there was really a problem using it in single page applications workflows. But in more recent versions of firebase-ui you can actually reset the widget so you won't need to initialize it again.
All you need to do is to keep the widgets instance reference in a variable. Then, when you want to render it again you use the same reference, reset it and then restart it.
<code>var ui;
if (ui) {
  ui.reset();
} else {
  ui = new firebaseui.auth.AuthUI(firebase.auth());
}
ui.start('#firebaseui-auth-container', uiConfig);
</code>


C++ Concepts : invalid reference to function concept

Question: I tried this small piece of code that I modified from the Concepts Technical Specification:
  template < typename T >
    concept bool C_Object() {
      return requires {
        T();
      };
    }

  template < typename Object >
  requires C_Object<Object>
  class  Foo {
    public:
      Object  test;
  };

struct Component {
  int data;
  Component() : data(0) {}
};

int main() {
  Foo<Component> test;
  return 0;
}

But I get this error :
test.cpp:10:12: error: invalid reference to function concept 'template<class T> concept bool C_Object()'
   requires C_Object<Object>
            ^~~~~~~~~~~~~~~~
test.cpp: In function 'int main()':
test.cpp:26:16: error: template constraint failure
   Foo<Component> test;
                ^
test.cpp:26:16: note:   constraints not satisfied
test.cpp:26:16: note: ill-formed constraint

First time I try the new version of C++ concepts, where I am missing?
Thanks
Have a great day
Answer: This definition:
template < typename T >
concept bool C_Object() {
  return requires {
    T();
  };
}

defines C_Object as a function concept. This one:
template < typename Object >
requires C_Object<Object>
class Foo {
public:
  Object test;
};

uses C_Object as if it were a variable concept. In a requires clause, you must use () to "invoke" function concepts:
template < typename Object >
requires C_Object<Object>()
class Foo {
public:
  Object test;
};

Alternatively, you could use the "terse" placeholder syntax to constrain Object which does not differentiate variable and function concepts:
template < C_Object Object >
class Foo {
public:
  Object test;
};

Comment: Your last code was something I was searching, big thanks :)


Shell script to extract string from a file and return the next chars until a whitespace

Question: We have an application that grabs it's setup parameters from a file. I want to extract one or two statements from the startup string and present them as a nice table.
An example string would be -Dmysql.host=mysql1.company.com  but it might also be an ipaddress or a machine name and not an fqdn.
I want locate the -Dmysql.host= but return the servername.
Any tips or pointers as to how to, once I've found the string "-Dmysql.host=" in the file, show everything to the next white space would be appreciated.
Perhaps there is a better method.  I plan on running this on a dozen machines or so eventually to return a list of which application machines are configured to talk to which db machine at a glance.
Thanks you for your time.
Comment: It would seem that sed is a popular answer. :)
Answer: Try this:
<code>grep mysql.host file.txt | sed -e 's/.*mysql.host=\(\S*\).*/\1/g'
</code>
You should end up with a value that is the value of mysql.host.  You can put the -D in the match also if you want, but I have left it out because it is a parameter to grep and you need to escape it.
Comment: You might want to escape the dot in mysql.host as dot is a regex atom in grep so would match "mysqlshost" or "mysql-host" as well as "mysql.host"
Comment: +1 good catch, although the assumption here was there would only be one occurrence in the parameters file.  If not, you might want a '| head -n 1' in there also!
Answer: From the information given, I would go about this by first splitting everything based on whitespace, and then split those tokens based on the = sign.  Pure bash solution would be something like what follows.
<code>  foo="bar=baz boo=zip"
  for keyvalue in $foo; do
     key=${keyvalue%%=*}
     value=${keyvalue##*=}
     echo $key $value
  done
</code>
Since IFS is probably whitespace, the shell takes care of splitting based on the whitespace.  You can then use Parameter (Variable) Expansion to handle spiting into key / value pairs  based on the equals sign.
Answer: How about feeding the files to good old sed:
<code>$ echo foo  -Dmysql.host=mysql1.company.com -bar | grep -- "-Dmysql.host=" | sed -e 's/^.*-Dmysql.host=//' -e 's/ .*//'
mysql1.company.com
</code>
So in your case you'd feed it the file like so:
<code>$ grep -- "-Dmysql.host=" FILENAME | sed -e 's/^.*-Dmysql.host=//' -e 's/ .*//'
</code>
I realize there's a grep in there that sed could handle but this is just easier to write, sed can be awkward.


Hohoner HG-13 strings

Question: I have an old Hohoner HG-13 which I would like to buy a new set of strings. One thing I saw on the subject was guitars which use vinyl you can't use metal, this one has seems to have 3 and 3. I have no idea if they are the original strings or not.
If someone can give me some direction I would appreciate it.
P.S. This for for self-teaching home use. Also, I am currently leaning to a low gauge set.
Thanks,
Aba
Comment: You most likely have 3 nylon (rather than vinyl), and the others atr nylon with metal winding around it. So, really, all nylon. It's better that they get replaced like for like, so don't go for steel, but get another classical guitar set of strings. However, Hohner did market this as an acoustic, and some one might have put nylon strings on for easy playing.
Comment: @Tim According to this source http://www.guitarcenter.com/Used/Hohner/HG13-Classical-Acoustic-Guitar.gc I would say this standard classical guitar
Comment: @teodozjan - looking at the pic, with the machine heads and bridge, you're correct. Not good for anything except nylon classical strings!
Answer: This was more than likely sold as purely a classical guitar. The strings should all be nylon. The 3 lower ones ought to be nylon with a winding of soft metal. That's the only set to use safely on this guitar. The machine heads are the kind that won't stand the strain of steel strings. The bridge is glued to the body - same story; and the neck would probably bow too much, and not be adjustable too.
Comment: Are you referring to http://www.musiciansfriend.com/accessories/daddario-ej43-pro-arte-light-tension-classical-guitar-strings?rNtt=classical%20strings&index=1#productDetail and/or http://www.musiciansfriend.com/accessories/daddario-ej47-pro-arte-80-20-bronze-normal-tension-classical-guitar-strings
Comment: Pretty well any set of nylon strings will do the trick.  Later, when you have more experience, you may get more fussy as to their tension.

Hohoner HG-13 strings


Show that $u+v$ bisects $u$ and $v$ only if $|u|=|v|$

Question: I want to show that if I have two Euclidian vectors in $\mathbb{R}^n$ than the sum of these two vectors bisects the angle between the two vectors. Said more mathematically.
Let  $(u,v) \in \mathbb{R}^n$
Then $\angle(u,v+u) = \angle(u+v,v)$ if and only if $|u|=|v|$
I tried using the fact that
$$ \angle(u,v) = \arccos \left( \frac{u \cdot v}{|u| |v|} \right) $$
Alas this attempt was futile
Now for $\mathbb{R}^2$ this is obviously true, as can bee seen from my illustration.

How do I prove this with some rigor? Thanks for all tips and advices, this is not a homework question.
Comment: The dot product formula looks helpful. What happens when you compute $u \cdot (u + v)$ and $v \cdot (u + v)$?
Comment: I think the first sentence is missing something, although the mathematical restatement looks good.
Comment: You obtain $u\cdot v + u^2$ and $u \cdot v + v^2$. Now am I supposed to use the fact that $|v|=\sqrt{v^2}$ ?
Comment: Is $u^2$ shorthand for $u \cdot u$? Then yes.
Answer: The first prove:
Two vectors form a parallelogram ABCD, we know that in a parallelogram diagonals bisect by their point of intersection. It means that segment from A to point of intersections of diagonals is a middle line of triangle ABD. There is a criteria that middle line is bisecting line if and only if the triangle is isosceles. That proves your problem.
The second prove:
Let $|u|=|v|$ is equal $u^2=v^2$ then $\cos(\phi_1)=\frac{(u+v,u)}{|u+v||u|}=\frac{u^2+(u,v)}{|u+v||u|}=\frac{v^2+(u,v)}{|u+v||v|}=\cos(\phi_2)$
Let $\cos(\phi_1)=\cos(\phi_2)$ then $\frac{u^2+(u,v)}{|u|}=\frac{v^2+(u,v)}{|v|}$ => $|u|+\frac{(u,v)}{|u|}=|v|+\frac{(u,v)}{|v|}$=>$(|u|-|v|)(1-\frac{(u,v)}{|u||v|})=0$ if $u$ and $v$ aren't collinear, it means that $|u|=|v|$ But if they are, it means that angle is zero. And angle $\phi_1$ and $\phi_2$ are also zero.
Comment: This criteria you can prove by considering areas of triangles ABO and ADO, where O is the midpoint of BD.


prove a subset of $l^2$ is closed?

Question: Let $\{f_i\}$ be a sequence of (nice) functions in $L^p[0,1],$ and $p>1, \frac{1}{p}+\frac{1}{q}=1.$
Define a subset $A$ of the space $l^2$ as
$$A=\left\{(a_1, a_2, \ldots)\in l^2: \text{ such that } a_i=\int_0^2g(x)f_i(x)dx, \text{ for }g\in L^q[0,1] \text{ and } \|g\|_q\leq1\right\}.$$
Here $\{f_i\}$ are good enough in order that for any $\|g\|_q\leq1,$ the resulting $(a_1, a_2, \ldots)\in l^2.$
Can we prove this subset $A$ is closed in $l^2$?
Have been working this for a while. Any suggestion is greatly appreciated. (more assumptions may be imposed on $\{f_i\},$ for instance, smoothness)
Answer: I will assume the limits of the integral should be $0$ and $1$, not $0$ and $2$. I also won't really comment on the requirements of the sequence $f_i$; the set you've provided is well-defined in any case. If we can establish that this set is always closed, regardless of the condition that $(a_1, a_2, \ldots) \in l^2$ for any $\lVert g \rVert \le 1$, then surely this will be of some use to you!
I also plan to generalise the result, for no other reason than to simplify the notation. We replace $L^p[0, 1]$ with a reflexive Banach space $X$, and $L^q[0, 1]$ with its dual $X^*$. The functions $f_i$ shall now be a sequence $x_i \in X$. We are therefore looking at the set
$$A = \left\lbrace (f(x_1), f(x_2), \ldots) \in l^2 : f \in B_{X^*} \right\rbrace.$$
Suppose we have a sequence $(f_i(x_1), f_i(x_2), \ldots)_{i=1}^\infty \in A$ that converges in $l^2$ to some sequence $(a_1, a_2, \ldots)$. That is,
$$\sum\limits_{j = 1}^\infty ~ \lvert f_i(x_j) - a_j \rvert^2 \rightarrow 0$$
as $i \rightarrow \infty$.
In order to prove $(a_1, a_2, \ldots) \in A$, we must construct its corresponding $f \in X^*$. Since $X$ is reflexive, so is $X^*$, hence $B_X^*$ is weakly compact. By the Eberlein-Smulian theorem, it's also sequentially weakly compact. Hence the sequence $f_i$ has a weakly convergent subsequence $f_{n_i}$, weakly converging to some $f \in B_{X^*}$. That is, for any $x \in X$,
$$f_{n_i}(x) \rightarrow f(x)$$
as $i \rightarrow \infty$. Now we must prove that $f(x_j) = a_j$ for all $i$.
But this is now straightforward. If $\sum\limits_{j = 1}^\infty ~ \lvert f_i(x_j) - a_j \rvert^2 \rightarrow 0$, then $\lvert f_i(x_j) - a_j \rvert \rightarrow 0$ for any fixed $j$. That is, $f_i(x_j) \rightarrow a_j$ as $i \rightarrow \infty$. Considering the subsequence $f_{n_i}(x_j)$ subsequence, which converges to $f(x_j)$, we see by the uniqueness of limits that $a_j = f(x_j)$ as required. Hence, the set $A$ is closed.

prove a subset of $l^2$ is closed?


Closing asyncio event loop in Python causes exception at end

Question: For https requests using asyncio and aiohttp in Python 3.4 on Windows I'll need to use 2 event loops. A ProactorEventLoop for running shell commands, and the default event loop for HTTPS requests. The ProactorEventLoop does not work for HTTPS commands, unfortunately.
The following code below shows what happens when I use a newly created default event loop and try to close it at the end on Windows. I get exceptions at the end if I call loop.close at the end as shown below:
> Traceback (most recent call last):
>  File "C:\BuildUtilities\p3.4env0\lib\site-packages\aiohttp\connector.py", line 56, in __del__
>    self.close()
>  File "C:\BuildUtilities\p3.4env0\lib\site-packages\aiohttp\connector.py", line 97, in close
>    transport.close()
>  File "C:\Python34\Lib\asyncio\selector_events.py", line 375, in close
>    self._loop.remove_reader(self._sock_fd)
>  File "C:\Python34\Lib\asyncio\selector_events.py", line 155, in remove_reader
>    key = self._selector.get_key(fd)
> AttributeError: 'NoneType' object has no attribute 'get_key'

Commenting it out removes the exception and I don't know why. The one and only
import asyncio
import aiohttp

@asyncio.coroutine
def get_body(url):
    response = yield from aiohttp.request('GET', url)
    return (yield from response.read_and_close())

#loop = asyncio.ProactorEventLoop()
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)

f = asyncio.async( get_body('https://www.google.com') )
try:
    loop.run_until_complete(f)
except Exception as e:
    print(e)

if f.result():
    print(f.result())

loop.close()

Thanks,
greenaj
Answer: Update: it looks like the issue is fixed in the github version (0.7.2). It doesn't produce the error. As @danj.py said, it is fixed by "Get rid of __del__ in connector" commit.

It is not ProactorEventLoop or Windows specific. I can reproduce the error on Ubuntu with the default event loop:
#!/usr/bin/env python3
import asyncio
import aiohttp # $ pip install aiohttp

@asyncio.coroutine
def get_body(url):
    response = yield from aiohttp.request('GET', url)
    return (yield from response.read_and_close())

loop = asyncio.get_event_loop()
body = loop.run_until_complete(get_body('https://stackoverflow.com/q/23283502'))
print(len(body), type(body), body[:200])
loop.close()

It might be a bug in aiohttp because the usage seems correct.
There is no error if the request is made without aiohttp:
#!/usr/bin/env python3
import asyncio
from contextlib import closing
from urllib.parse import urlsplit

@asyncio.coroutine
def get_body(url):
    # parse url
    url = urlsplit(url)
    path = '/' * (not url.path) + url.path + '?' * bool(url.query) + url.query
    # open connection
    reader, writer = yield from asyncio.open_connection(
        host=url.hostname,
        port=url.port or (443 if url.scheme == 'https' else 80),
        ssl=(url.scheme == 'https'))
    with closing(writer):
        # send request
        writer.write(b'GET ' + path.encode('ascii') + b' HTTP/1.1\r\n'
                     b'Host: ' + url.netloc.encode('ascii') + b'\r\n'
                     b'Connection: close\r\n\r\n')
        # read headers
        while True:
            line = yield from reader.readline()
            line = line.rstrip(b'\n\r')
            print(line.decode('latin-1'))
            if not line:
                break
        # read body
        body = yield from reader.read()
    return body

loop = asyncio.get_event_loop()
body = loop.run_until_complete(get_body('https://stackoverflow.com/q/23283502'))
print(len(body), type(body), body[:200])
loop.close()

Note: the examples are not completely equivalent e.g., the latter doesn't follow redirects.
Comment: I have verified that closing a SelectorEventLoop no longer crashes in Windows 7 64 bit. A `pip install aiohttp --upgrade` resolved the issue, upgrading aiohttp from 0.7.0 to 0.7.2.  Thank you.
Answer: J.F. Sebastian is correct that this is a bug with aiohttp.
It looks like this issue has been resolved via the following commit.
https://github.com/KeepSafe/aiohttp/commit/a229110539e93c21ae0198f6f883ae3e40ea866b#diff-7f25afde79f309e2f8722c26cf1f10ad
As of this writing, it does not appear that this has made its way into pypi.
Comment: you are correct. I can't reproduce the error starting with `a229110` commit.
Answer: Actually it's a (fixed) bug in Python 3.4 itself: http://bugs.python.org/issue21435
As temporary solution (and for sake of Python 3.3 support ) I made pull request https://github.com/KeepSafe/aiohttp/pull/48
But, say again, the root of problem is garbage collector in Python 3.4.0 (fixed by upcoming Python 3.4.1 bugfix release).


update existing infrastructure on heroku using terraform

Question: I've got this infrastructure description
variable "HEROKU_API_KEY" {}

provider "heroku" {
    email = "email@example.com"
    api_key = "${var.HEROKU_API_KEY}"
}

resource "heroku_app" "default" {
    name = "judge-re"
    region = "us"
}

Originally I forgot to specify buildpack. It created the application on heroku. I decided to add it to resource entry
    buildpacks = [
        "heroku/java"
    ]

But when I try to apply the plan in terraform I get this error
Error: Error applying plan:
1 error(s) occurred:
* heroku_app.default: 1 error(s) occurred:
* heroku_app.default: Post https://api.heroku.com/apps: Name is already taken
Terraform does not automatically rollback in the face of errors.
Instead, your Terraform state file has been partially updated with
any resources that successfully completed. Please address the error
above and apply again to incrementally change your infrastructure.

Terraform plan looks like this
Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.

------------------------------------------------------------------------

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  + heroku_app.judge_re
      id:                <computed>
      all_config_vars.%: <computed>
      buildpacks.#:      "1"
      buildpacks.0:      "heroku/java"
      config_vars.#:     <computed>
      git_url:           <computed>
      heroku_hostname:   <computed>
      name:              "judge-re"
      region:            "us"
      stack:             <computed>
      web_url:           <computed>

Plan: 1 to add, 0 to change, 0 to destroy.

------------------------------------------------------------------------

Note: You didn't specify an "-out" parameter to save this plan, so Terraform
can't guarantee that exactly these actions will be performed if
"terraform apply" is subsequently run.

As a workaround I tried to add destroy in my deploy.sh script
terraform init
terraform plan

terraform destroy -force

terraform apply -auto-approve

But it does not destroy the resource as I get the message Destroy complete! Resources: 0 destroyed.
What is the problem?
Link to build
Answer: It looks like you also changed the name of the resource. Your original example has the resource name heroku_app.default while your plan has heroku_app.judge_re.
To point your state to the remote resource, so Terraform knows you are editing and not trying to recreate the resource, use terraform import:
terraform import heroku_app.judge_re judge-re
Answer: In terraform, normally you needn't destroy the whole stack, which you just want to re-build one or several resources in it.
terraform taint does this trick.  The terraform taint command manually marks a Terraform-managed resource as tainted, forcing it to be destroyed and recreated on the next apply.
terraform taint heroku_app.default

Second, when you troubleshooting why the resource isn't list in destroy resource, please make sure you point to the right terraform tfstate file.
when you run terraform plan, did you see any resources which already was created?
Comment: yeah, it seemed strange to me that I needed to destroy the stack. I presumed that there should a be command to update the stack instead of destroying it. So usually `taint` is used instead of `destroy`?
Comment: "when you run terraform plan, did you see any resources which already was created" what do you mean by that? it just showed `terraform will perform the following actions` with the list of resource parameters
Comment: If you point to right tfstate file, and run with `terraform plan`, you should see the resources which are created and a list which will be created/updated/or deleted. Did you get any thing, can you update in your original question with the output of  `terraform plan`?
Comment: But I don't have `tfstate` file. Update with `plan`
Comment: It seems I have some other problem. When I try to create and delete from local machine it works fine.


How to get the Solr index sizes via a curl command

Question: How to get the Solr cluster index sizes via a curl command?
(without getting the data folder size)
Answer: The easiest way to find the API endpoint for a specific set of data is to use the Solr UI while looking at the "Network" tab of your browser's development tools. This will show all requests being made to the backend Solr service, and you can then look at the response from each endpoint when you've navigated to the page showing the index size.
The core overview shows the index size under the "Replication" header, and that is populated from a request to /replication:
<code>http://localhost:8983/solr/corename/replication?command=details&wt=json
</code>
If we look at the response from that endpoint, we can see that the JSON contains the following key and value:
<code>"details":{
  "indexSize":"6.49 KB",
  ...
</code>


Prove that, for any two positive integers $x$ and $y$, the value of $x \pmod y$ equals $x$ or is less than $ \frac{x}{2}$.

Question: I started by taking three cases viz $x<y$, $x=y$ and $x>y$. The proofs for the former two cases were pretty easy but I can't figure the same out for the remaining case. I have an intuition but it isn't too solid for formal proof.
Answer: For $x>y$: you can say $x=yq+r$, where $q$ is the quotient in division of $x$ by $y$.
We can see that $q\ge 1$ (as $x\gt y$), and $r=x\mod y$ is the remainder in that division, so $0\le r\lt y$.
Now we have $x=yq+r\ge y+r\gt 2r$, therefore $r\lt x/2$.
Comment: Shouldn't r be less than or "equal" to x/2? Or is the question statement incorrect?
Comment: @AbhinavRawal If it is always less, then you can argue that it is also always "less or equal". I hope, with a bit of luck, that I've proven a slightly stronger statement than requested in the question, that is!
Comment: So there won't be any case where r is exactly x/2?
Comment: @AbhinavRawal Unless I am somehow mistaken in the above proof, no, there won't be such a case.
Comment: There won't be any case where r is exactly equal to x/2. I solved it using the gint inequality just now.
Answer: If $y\geqslant x$ then clearly the claim is true.
Otherwise assume that $x=ay+b$ form some non-negative integers $a,b$ such that $y\geq b$. Then for the sake of the contradiction assume that $b\geqslant x/2$. Then, $ay$ is less than or equal to $x/2$ and so is $y$ itself. Then we will have $b\geqslant (x/2)\geqslant y$ but this contradicts $y\geq b$.
Answer: Let$$r \equiv x \pmod y$$
If $y > x$, clearly $r = x$. Now, assume $y < x$. Then
$$r \equiv x \equiv \underbrace{x - \left[\frac xy \right]y}_{<y} \pmod y$$  So, what we need to prove is $$r=x - \left[\frac xy \right]y \le \frac x2 $$or$$ \left[\frac xy \right]y \ge \frac x2$$
Since $x - 1 < [x] \le x$, it is enough to show that
$$\left(\frac xy - 1\right) y \ge \frac x2 $$or$$ xy - y \ge \frac x2 $$or$$ y \ge \frac {x}{2(x-1)}$$ which is obvious since $$\mathbb N \ni y > \frac 12 \ge \frac {x}{2(x-1)}$$
Answer: First case $ : x<y$
$$x\mod y =x$$
Second case $ : x=y $
$$x\mod y =0$$
Third case $ : x>y $
$$x=ny+r \; with\; 0\le r <y \; and\; n\ge1$$
$$\implies x< (n+1)y$$
$$\implies x<2ny $$
$$\implies \frac x2 < ny$$
$$\implies \frac x2 < x-r$$
$$\implies r < \frac x2$$
$$\implies x\mod y < \frac x2$$
Comment: Sir, I couldn't understand the implication x ≤ 2ny. Can you please elaborate?
Comment: @AbhinavRawal $n\ge 1 $ thus $ n+n\ge 1+n$.
Comment: @AbhinavRawal Is it Ok, or should i clarify.
Comment: I've understood, sir. I was a little confused whether there will be any case where r is exactly = x/2. Turns out there isn't, right? One can easily argue if r<x/2 then r ≤ x/2.
Comment: @AbhinavRawal Yes . Thank you for your message.


Issue finding "Column IDs" inside report

Question: I want to be able to send a row, from a report, via email with only specific columns via the API.
The API docs clearly show you how to send a row via email however, I'm unable to get the column ids inside the report in order to send those specific columns. I'm using the following to try and output the column Title and Id. The title will show successfully however the IDs show blank. Is there a reason for this?
<code>        Report report = ss.ReportResources.GetReport(
          reportid,           // long reportId
          null,                       // IEnumerable<ReportInclusion>
          null,                       // int pageSize
          null                        // int page
        );

        foreach(var Col in report.Columns)
        {
            Console.WriteLine($"Title:{Col.Title} ID:{Col.Id}");
        }
</code>
Answer: You should call virtualId
<code> Console.WriteLine($"Title:{Col.Title} ID:{Col.VirtualId}");
</code>
base on https://smartsheet-platform.github.io/api-docs/#reportcolumn-object

A report column is a "virtual" column, in that it appears identical to
  source sheet columns, but is in fact a different column belonging to
  the report. Cells in the report refer to this column via their
  virtualColumnId attribute, and to their actual column from their
  source sheet via their columnId attribute.

base on https://smartsheet-platform.github.io/api-docs/?csharp#get-report
<code>{
  "id": 4583173393803140,
  "name": "My Report",
  "totalRowCount": 4,
  "accessLevel": "OWNER",
  "permalink": "https://app.smartsheet.com/b/home?lx=pWNSDH9itjBXxBzFmyf-5w",
  "createdAt": "2012-07-24T18:22:29-07:00",
  "modifiedAt": "2012-07-24T18:30:52-07:00",
  "columns": [
    {
      "virtualId": 4583173393803140,
      "version": 0,
      "index": 0,
      "primary": true,
      "title": "Sheet Name",
      "type": "TEXT_NUMBER",
      "validation": false,
      "sheetNameColumn": true
    },
    {
      "virtualId": 2331373580117892,
      "version": 0,
      "index": 1,
      "title": "Status",
      "type": "TEXT_NUMBER",
      "validation": false
    }
  ],
  "rows": [
    {
      "id": 1732835527681924,
      "sheetId": 1060338138408836,
      "rowNumber": 1,
      "expanded": true,
      "accessLevel": "OWNER",
      "createdAt": "2014-10-02T15:05:35-07:00",
      "modifiedAt": "2014-10-02T15:05:35-07:00",
      "cells": [
        {
          "virtualColumnId": 4583173393803140,
          "type": "TEXT_NUMBER",
          "value": "My Sheet",
          "displayValue": "My Sheet"
        },
        {
          "columnId": 8467747974735748,
          "virtualColumnId": 2331373580117892,
          "type": "TEXT_NUMBER",
          "value": "In Progress",
          "displayValue": "In Progress"
        }
      ]
    }

  ]
}
</code>


Line integral work done by the force F

Question: I have a problem that I just don't get.
I am supposed to evaluate the line integral for the work done by the two-dimensional force F = (y, 2x) going from the origin O to the point P = (1,1). The path goes from O to Q = (1,0) along the x-axis, and from Q straight up to P = (1,1) along the y-axis. The textbook define the integrals as follow (this is an example in the book):
$\int_{0}^{1} F_x(x,0)$ $dx$ + $\int_{0}^{1} F_y(1,y)$ $dy$
= 0 + 2 $\int_{0}^{1} dy$ = 2
I understand how they get $F_x(x,0)$ and $F_y(1,y)$ (I think). What I don't understand is how this becomes 0 and 2.
Answer: When u r going from 0,0 to 1,0 the coordinate y is constant and hence become f(0,2x) and u r displacing the mass in x direction so u want the force in x direction only which is 0 so integration becomes.
Same way in 1,0 to 1,1 x is constant and we want force in y direction to find work which is constant equal to 2.
Comment: To rephrase: $F_x$ is the $x$-component of the force, which on the first path is 0, because your equation defining $F$ has $F_x = y$ (the $x$-component of the force is the y coordinate of the position). On the second path, $F_y=2$, because the $y$-component of the force is given by $F_y=2x$, which on the second path is 2.
Answer: Notation can be very confusing. Your force is given by the function: $F(x,y) = \langle y, 2x \rangle$.
Therefore, the components of the force are given by the functions:
$F_x(x,y)= y$, and $F_y(x,y)= 2x$
On the first path, $x$ is varying but y is constantly 0, so:
$F_x(x,y)= F_x(x,0)= 0$
On the second path, $y$ is varying but x is constantly 1, so:
$F_y(x,y)= F_y(1,y)= 2(1)=2$

Line integral work done by the force F


Ubuntu: Postfix, maps permissions?

Question: I just loaded up Postfix on Ubuntu 12.04 (following several guides), and most said to change the file permissions in the /etc/postfix/maps (user.cf, alias.cf, domain.cf) to 700 and owned by the postfix user.
Yet, when I do this, those files can't be read. I had to chmod 777 the whole folder for postfix to work. Any ideas on how I can troubleshoot this so I don't have to use 777 for the whole directory?
I know it's a permission issue, and postfix should be running under the postfix account, I just thought I might ask you guys for your recommendations.
Asked for information:
ps aux | grep postfix
root      1839  0.0  0.1 158844   864 ?        Ss   Dec28   0:00 /usr/sbin/saslauthd -a pam -r -c -m /var/spool/postfix/var/run/saslauthd -n 5
root      1840  0.0  0.2 158844  1040 ?        S    Dec28   0:00 /usr/sbin/saslauthd -a pam -r -c -m /var/spool/postfix/var/run/saslauthd -n 5
root      1841  0.0  0.1 158844   912 ?        S    Dec28   0:00 /usr/sbin/saslauthd -a pam -r -c -m /var/spool/postfix/var/run/saslauthd -n 5
root      1842  0.0  0.1 158844   844 ?        S    Dec28   0:00 /usr/sbin/saslauthd -a pam -r -c -m /var/spool/postfix/var/run/saslauthd -n 5
root      1844  0.0  0.1 158844   924 ?        S    Dec28   0:00 /usr/sbin/saslauthd -a pam -r -c -m /var/spool/postfix/var/run/saslauthd -n 5
root      2633  0.0  0.0  25108   356 ?        Ss   Dec28   0:00 /usr/lib/postfix/master
postfix   2637  0.0  0.0  27336   368 ?        S    Dec28   0:00 qmgr -l -t fifo -u
postfix   2697  0.0  0.1  38244   980 ?        S    Dec28   0:00 tlsmgr -l -t unix -u -c
root     18742  0.0  0.1   9388   884 pts/1    S+   00:11   0:00 grep --color=auto     postfix

ls -al /etc/postfix
drwxr-xr-x   4 root root     4096 Dec 28 16:29 .
drwxr-xr-x 117 root root     4096 Dec 28 17:24 ..
-rw-r--r--   1 root root      329 Dec 24 21:33 dynamicmaps.cf
-rw-r--r--   1 root root     2216 Dec 28 16:29 main.cf
-rw-r--r--   1 root root     1370 Dec 24 21:44 main.cf.old
drwxrwxrwx   2 root postfix  4096 Dec 28 17:10 maps
-rw-r--r--   1 root root     4797 Dec 24 21:46 master.cf
-rw-r--r--   1 root root    19707 Oct 23 10:10 postfix-files
-rwxr-xr-x   1 root root     8729 Oct 23 10:10 postfix-script
-rwxr-xr-x   1 root root    26498 Oct 23 10:10 post-install
drwxr-xr-x   2 root root     4096 Dec 24 21:55 sasl

When I would receive error messages, they would be:
Dec 28 17:04:43 prodserv1 postfix/virtual[7194]: error: open /etc/postfix/maps/user.cf: Permission denied
Dec 28 17:04:43 prodserv1 postfix/virtual[7194]: warning: mysql:/etc/postfix/maps/user.cf is unavailable. open /etc/postfix/maps/user.cf: Permission denied
Dec 28 17:04:43 prodserv1 postfix/virtual[7194]: warning: table virtual_mailbox_maps: lookup firstname.lastname@example.com: Permission denied

Comment: Could you add `ps aux | grep postfix` and `ls -la /etc/postfix/` to your question?  Also, are you getting an error message?  If so, add it too.
Comment: Done! I'm not receiving error messages at the moment, however when I was they would appear as above.
Answer: The postfix master process manager runs as root.
This process can therefore access anything it pleases, and hence is not the issue.
However, any service in master.cf that has the 2nd column of its service definition ("Unprivileged") set to "y", runs under the user account set with mail_owner in main.cf.
This user, or its primary group, must have read access to all map files:
chmod 0640 /etc/postfix/maps/* && chgrp <postfixgroup> /etc/postfix/maps/*

Comment: That worked, thanks! I had the ownership set to postfix, but the guide I had followed had the permissions set to 700, which didn't work, but 640 did.

Ubuntu: Postfix, maps permissions?


Does ball in test cricket actually swing more and batting is actually difficult?

Question: Note: Below, I might present some statements based on what I feel rather than facts. Please correct me in the answer so I understand it better. But I'm writing it anyway to explain my doubts and ask question.

This question is bugging me for a long time.
Usually, what do I notice in test cricket? :

A lot of slips because a lot of catches go there
Batsmen afraid to even look for a single run. Sometimes they are even afraid of leaving a ball
Overall, often there are situations where it seems so difficult to score runs. Teams collapse often even if they are playing defensive
Lastly, I've personally observed the ball swinging a lot in test cricket rather than ODI cricket

Usually, what do I notice in limited overs cricket? :

Runs come so easily! Hitting 3 sixes in a row isn't a big deal these days especially in T20 cricket
Don't notice that much swing (except the first 3-4 overs)
Batsman don't look that much afraid (except the first 3-4 overs)
In England, in ODI cricket in past few years, their batsmen wreak havoc on bowlers. But in test cricket I feel like getting runs is so difficult

However, this answer totally contradicts what I have stated. According to it, ball (white ball) swings more in limited overs cricket.
So my question is:
How much is truth of this swing in what I have stated above? And if there's truth about this swing, why does it happen? Does the color of ball has to do with this?
Comment: Several of these observations have nothing to do with the amount of swing, but the resources available for scoring. Limited overs cricket is much more about making runs per ball (because ten wickets tends to take as long as the entire allocation of overs) while test cricket is about making runs per wicket (because there will be hundreds of overs faced per team).
Comment: One aspect that you may have missed is that, while it could be argued the white ball may swing more on a one-to-one comparison, the red ball tends to swing for a much longer period of time. In England, it is not uncommon to see the red Dukes ball still swing after 30/40/50 overs, whereas with the white ball you'd be lucky to still get meaningful swing after the end of the 1st Powerplay (6 / 10 overs for T20 / 50-over cricket respectively)
Comment: @ImClarky that makes sense. I think that is why I observe swing more in test cricket.
Answer: There are several reasons for this:  (this more answers why runs are harder to come by)

The pitches tend to be prepared differently. Test wickets tend to be more bowler favoured vs limited overs cricket which favours batters more.
The fielding rules are different.  In test matches you can (almost) put fielders anywhere, while in limited overs cricket the field positions are quite limited, so if a batsman are trying to dominate the bowling, then you move your fielders to the outer ring and they are more likely to be caught.
The bowling rules are different. Wides are called a lot more leniently, allowing bowlers to really put in everything and even if it goes wrong it's less likely to be called wide.
Because overs are not a limited resource (or almost unlimited) wickets' value goes up. This means more defensive batting in general.

As for swing, the red balls are just a bit different, and perhaps teams spend more time shining it, and it takes less of a beating. Some teams infamously also make the ball more irregular by cheating.


Does $L^2$ strong convergence and bounded $L^\infty$ imply convergence in $L^\infty$ along subsequences?

Question: Take a sequence of functions $f_n \in L^2([0,1])$ such that
$f_n \rightarrow f$ in $L^2([0,1])$ (convergence in $L^2$ norm) and
$|f_n|_{L^\infty},|f|_{L^\infty} <R$ (uniformly bounded in $L^\infty$ norm).
Question:
Do we get from this that there is a subsequence $f_{n_k}$ such that
$f_{n_k} \rightarrow f$ in $L^\infty$ norm?
If not:
Are there any assumptions such that this is true?
Answer: Let $f_n = 1_{[0,{1 \over n}]}$. Then $f_n \to f=0$ in $L_2$ (since $\|f_n-f\|_2 = { 1 \over \sqrt{n}}$), and $\|f_n\|_\infty = 1, |f\|_\infty = 0$, so we can take $R=2$. However no subsequence can converge uniformly to zero since $\|f_n-f\|_\infty = 1$ for all $n$.
Comment: By slightly modifying your answer, a more interesting example is obtained.
$$
f_n(x)=
\begin{cases}
1-nx &0 \leq x \leq \frac{1}{n}\\
0 & \frac{1}{n} \leq x \leq 1
\end{cases}
$$
Answer: If you do have convergent subsequences they will all have to converge to the $L_2$ limit, because convergence in $L_\infty$ implies convergence in $L_2$. In other words, your sequence would have to converge in $L_\infty$. Boundedness in $L_\infty$ only gives you a weak$^*$ convergent subsequence. To get strong convergence in $L_\infty$ you need boundedness in a space that's compactly embedded into $L_\infty$, e.g. $W^{2,1}([0,1])$.
Answer: Let $f_{n}(t)$ be $0$ on $(-\infty,0]$, climb linearly to $1$ on $[0,1/n]$, remain $1$ on $[1/n,1-1/n]$, ramp linearly back down to $0$ on $[1-1/n,1]$ and remain $0$ on $[1,\infty)$. Then $\{ f_{n}\}_{n=1}^{\infty}$ converges in $L^{2}(\mathbb{R})$ to the characteristic function $\chi_{(0,1)}$. There is no subsequence $\{ f_{n_{k}}\}_{k=1}^{\infty}$ of $\{ f_{n}\}_{n=1}^{\infty}$ which can converge in $L^{\infty}$ because the limit function would have to be continuous in order for the sequence of continuous functions $\{ f_{n_{k}}\}_{k=1}^{\infty}$ to converge in $L^{\infty}(\mathbb{R})$.


What's the proper way to check in a Model's save() method if a FileField was committed in Django?

Question: In Django, if you are overriding the save method of a model with a FileField, you can do something like this:
class MyModel(models.Model):
    my_file = models.FileField()

    def save(self, *args, **kwargs):
        if self.my_file and not self.my_file._committed:
            # The file changed

This lets you detect anytime a new file is uploaded. This can either happen if a new instance of MyModel is being created, or one is being modified, and a new file is replacing an old file (or no file).
This is very convenient for cases where you need to read the file, and do something, but only if the file changed.
This works, but the slight problem is that the my_file._committed attribute starts with an underscore, indicating that it's not meant to be used outside of the class it's defined in.
Is there a proper way to detect if the file in the FileField changed during the current save() operation without using the private _.committed attribute?
Answer: Maybe you can check the self.my_file.instance.attname of the instance.
From Django source code of FileField.save method:
    def save(self, name, content, save=True):
        name = self.field.generate_filename(self.instance, name)
        self.name = self.storage.save(name, content, max_length=self.field.max_length)
        setattr(self.instance, self.field.attname, self.name)  # <- check the attribute
        self._committed = True

        # Save the object because it has changed, unless save is False
        if save:
            self.instance.save()


Como fazer uma class interferir em outra com python

Question: Estou querendo fazer um botão no estilo interruptor com kivy, quando um é verdadeiro, o outro é falso, porém, quando vou alterar uma variável na class do primeiro, ela não é alterada no segundo, e permanece com o valor original. Exemplicando:
c = 'NADA'

class A():

        c = 'CLASS A'

class B():

        print(c)
        c = 'CLASS B'
        print(c)

x = A()
x = B()
print(c)

Tem como output:
NADA
CLASS B
NADA

Comment: Qual é o resultado que você espera?
Comment: Desculpe, acabei não deixando explícito, mas é como o amigo de baixo mostrou,
`CLASS A `
`CLASS B `
Answer: Será necessário identificar que a variável c que se deseja alterar é da classe A(). Ao utilizar do jeito que você fez, está alterando a variável global criada no inicio do código.
Ficaria assim:
c = 'NADA'

class A():
    c = 'CLASS A'
    print(c)

class B():
    A.c = 'CLASS B'
    print(A.c)

x = A()
x = B()

Resultando em:
CLASS A
CLASS B


How far in future is call center workload accurate

Question: I am working on call center load forecasting. I have daily call volume for past 24 months along with few variables which does affect call load. Though none of these variables have come significant in ARIMA model.
My management has asked me to create forecast for two months in advance. I am concerned that just by using call center daily call volumes in Arima model my prediction will not be accurate so far in future.
Autocorrelation of daily call volume deteriorates drops to less than 0.5 in 5 days. I don't think that it will be very accurate for predicting values 2 months from now. What are your thoughts on this.
Comment: It sounds like you are well on top of the analysis side of your problem. Now you need to need to ask at explainingstatstodummies.stackexchange.com about how to communicate that effectively to management!
Comment: I am no expert on time-series, but assuming that you and @Bogdanovist are correct, which seems likely, what you could do is make a plot, based on predicting from the past, of how accurate the predictions are.
Answer: Whatever method you use - be it ARIMA forecasting, or a plain, old exponential smoothing - be sure to place confidence limits around your forecasts. This will show management how accuracy diminishes as you move into the future.
Answer: In addition to confidence intervals, you could also examine the peaks in volume and hypothesize causes that are not quantified in your existing data.  Examples will depend on your industry, but could be new product launches, recalls, updates to partner products, or Mondays.  This is where I usually find a subject matter expert in the business to help brainstorm if I don't have sufficient visibility. These could then be codified into a generic "event" variable, or simply layer on top of a volume graph to help illustrate how other factors really drive the variation in call volume.


Vector differential equation problem

Question: I was trying to do this question from a past paper, but I'm not sure how to proceed. The question is:
A particle of mass $m$ moves subject to a force $\mathbf F = A(y\mathbf i + x\mathbf j)$ where $\mathbf r = x\mathbf i + y\mathbf j + z\mathbf k$. Find the general solution $\mathbf r(t)$ to the equations of motion.
I wrote down the equation of motion:
$$ m\ddot{ \mathbf r} = \mathbf F = A(y\mathbf i + x\mathbf j)$$
And dotted with $\dot{\mathbf r}$ to get and integrated to get:
$$ \frac{1}{2} m |\dot{\mathbf r}|^2 +Axy = E $$
Where $E$ is a constant of energy. But I'm unsure how to continue from here. Normally I would substitute back in to the original equation of motion, but there's no $\dot{\mathbf r}$ for me to sub with. I tried to substitute the $Axy$ back in, writing the force as $\nabla(Axy)$, but I have no idea how to solve the resulting differential equation.
Answer: $\ddot{\mathbf{r}} = \ddot{x}\mathbf{i} + \ddot{y} \mathbf{j} + \ddot{z} \mathbf{k}$. Therefore you need to solve the following system of differential equations, where $\omega =A/m$,
$$ \ddot{x} = \omega y $$
$$ \ddot{y} = \omega x $$
$$ \ddot{z} = 0 $$
For $z(t)$ the solution is $z(t) = z_0 + v_{z0} t$. For $x(t)$ and $y(t)$ differentiate twice the 1st equation to get
$$ \frac{d^4}{dt^t}x = \omega \ddot{y} = \omega^2 x $$
where we substituted the second equation.
This is a linear equation of order 4 with constant coefficients,
so the general soltion is
$$ x(t) = A_1 \exp( \sqrt{\omega}t ) + A_2 \exp( -\sqrt{\omega}t ) + A_3 \exp( \sqrt{-\omega}t ) + A_4 \exp( -\sqrt{-\omega}t )   $$
where $\sqrt{-\omega} = \sqrt{-1}\sqrt{\omega} = i \omega$.
For $y(t)$ the solution is similar.
Comment: That makes sense, thanks for your help.

Vector differential equation problem


change all dates but not the time in mysql using sql

Question: I have a lot of rows, which are in a mysql db table, and they are in datetime format. Is there a way that i could change the year of the dates without changing their time?
Ex.

2000-05-01 11:00:00
2000-01-01 06:30:00
2000-01-01 07:00:00

changing them to

2050-05-01 11:00:00
2050-01-01 06:30:00
2050-01-01 07:00:00
Answer: if you want to add them by 50 years,
UPDATE tableName
SET columnName = columnName + INTERVAL 50 YEAR

MySQL DATE_ADD()
Answer: You can try this also:-
UPDATE table_name SET columnName = concat('2011-01-12 ', time(columnName))

Answer: Or You can use DATE_FORMAT function
UPDATE tableName
SET field = DATE_FORMAT(field, '2050-%m-%d %H:%i:%s')

In this case you change all years to same date. You can set similar months, days or time part.
Comment: The `'%T '` format returns hours minutes and seconds ("hh:mm:ss"). The `':%i:%s'` in the format string is unneeded.


Unique $C = \operatorname{hash}(A, B)$

Question: I want to derive a non-associative operation $\circ$ such that $C = A \circ B$ and that same $C$ can not be obtained by any other combination(s) of $A$ and $B$ e.g. much like $C = \operatorname{hash}(A, B)$
Comment: That's not a hash. A hash is meant not to be injective.
Comment: What kind of things are $A$ and $B$?
Comment: You should give some more information. What are $A,B$? Since you included the operator theory tag, I assume they are operators on some Banach space? Is "hash" some well known function? If so include a link. Otherwise say explicitly what you mean by $C = \text{hash}(A,B)$.
Comment: `A` and `B` are positive integers
Answer: You can take $C=2^A3^B$. This is injective and not associative, since e.g. $(1\circ1)\circ1=2^13^1\circ1=6\circ1=2^63^1=192$, whereas $1\circ(1\circ1)=1\circ6=2^13^6=1458$.
[Edit in response to the comment:]
Almost all operations are not associative, and it's straightforward to make them injective, so examples of such operations abound. Another example would be: Form $C$ by interleaving the digits of $A$ and $B$ (adding zeros where necessary). That is, if $A=7354$ and $B=81$, then $C=70305841$. You get a whole family of operations by doing this in different bases. Another example would be $C=2\left(\max(A,B)^2+\min(A,B)\right)+[A\gt B]$, where the Iverson bracket $[A\gt B]$ is $1$ if $A>B$ and $0$ otherwise.
Comment: But is this unique ? e.g. $C=2^A3^B$ But is there any possibility that $C=2^M3^N$ is also true where $M \not= A$ and $N \not= B$ and can the same be done with any operator other than `^` ?
Comment: What you call "unique" is what I more precisely referred to as "injective". Different $A$ and $B$ yield different $C$ by the [fundamental theorem of arithmetic](http://en.wikipedia.org/wiki/Fundamental_theorem_of_arithmetic). And yes, there are gazillions of operations with which you can do this. Another one would be interleaving the digits of the numbers, for example.
Comment: Oh! I see. I am not from Mathematics Background actually :( However can I see another example of the same operation ? with another operator ?
Comment: I don't know how there could be another example of the same operation, but I added another example of an operation with the same property.

Unique $C = \operatorname{hash}(A, B)$


Customizing taxonomy Term page with sticky articles

Question: I am trying to create an educational website. I have created terms as
History, Science, Biology, Mathematics
and Mathematics term, sub-term as Algebra, Trigonometry
I want to create a separate page like frontpage for each term with few posts sticky at top. For example When someone clicks on History then a page with teaser view of Articles like "About history", "Books for history", " Preparation Guide" will be top on that page list and all other nodes tagged with History term will come below these three posts.
And how can I set no of total posts of History term page as 10?
I am new to drupal and not able to find right modules. Stuck in this issue for 2 days, any help will be appreciated.
Answer: You can create a custom module and implement hook_menu_alter for taxonomy terms.
In your custom callback you then filter by your taxonomy and intercept the ones you want and pass the rest to the default handler.
On the ones that you intercept you then render a custom view for that taxonomy. That view will just be a normal default view (no page) with an attachment as well. You set the attachment to the top of the other view and show teasers. The other view will show links only with an offset to not show the teaser nodes as well. Your view will be constructed with appropriate contextual filters that you will pass.
Your MODULE.module file:
function MODULE_menu_alter(&$items){
  // change taxonomy view path for certain vocabularies
  $items['taxonomy/term/%taxonomy_term']['page arguments'][] =   $items['taxonomy/term/%taxonomy_term']['page callback'];
  $items['taxonomy/term/%taxonomy_term']['page callback'] = 'MODULE_taxonomy_term_callback';
  $items['taxonomy/term/%taxonomy_term']['file path'] = drupal_get_path('module', 'MODULE') . '/includes';
  $items['taxonomy/term/%taxonomy_term']['file'] = 'MODULE_callbacks.inc';
}

Your MODULE_callbacks.inc file (located at MODULE/includes):
function MODULE_taxonomy_term_callback($term, $callback) {
  $function = __FUNCTION__ . '_' . $term->vocabulary_machine_name;
  if (function_exists($function)) {
    return $function($term);
  }

  module_load_include('inc', 'taxonomy', 'taxonomy.pages');
  return $callback($term);
}

// one for each vocabulary
function MODULE_taxonomy_term_callback_TAXONOMYVOCABULARYMACHINENAME($term){
  $view = views_get_view('VIEW_MACHINE_NAME');
  $view->set_display('default');
  $view->set_arguments(array($term->tid));
  $view->pre_execute();
  $view->execute();
  return $view->render();
}

You View(s) will be as follows:
Contextual filter: Content (taxonomy in question)
When the filter value is not available

Provide default value: Taxonomy term ID from URL
Load default filter from term page.
Comment: Will try this and update.


Replace multiple parts of URL

Question: I want to replace multiple parts of URL including its domain. Like for instance if something is found in url then replace it with something else. in below example only first part works, why not second?
window.location = url.replace('.jpg', '.mp4');
window.location = url.replace('abc', 'def');

What if I want to replace 3 things? this is only an example
www.youtube.com/watch?v=voMOmKMXZXM
www.google.com/hide?v=voMOmKMXABC
Comment: Your question is unclear. What do you mean by "What if I want to replace 3 things?"? Please clarify.
Comment: Updated the question
Answer: Since replace() takes a string as its only parameter and also returns a string, you can chain multiple replace statements together, like this:
window.location = url.replace('.jpg', '.mp4').replace('abc', 'def');

So, if the value of url were to be this: www.google.com/abc.jpg, after calling the above, window.location would be set to www.google.com/def.mp4.

Replace multiple parts of URL


Problemas com barra de navegação

Question: Bom dia. Tenho uma tela com angular material em que simulo a flexnav do material design.

e quando desço o scroll fica:

Contudo, somente no momento em que a tela é carregada fica assim:

Já mexi bastante no Javascript e não consegui solucionar este problema. Desta forma, venho ver se alguém pode dar uma luz.
HTML

    <md-toolbar scroll id="toolbar">

            <md-button class="md-tools" aria-label="Voltar">

            </md-button>

            <md-button aria-label="E-mail" class="md-fab md-primary">

            </md-button>

    </md-toolbar>

JS
app.directive("scroll", function ($window) {

    return function(scope, element, attrs) {

      /* header DOM element with md-page-header attribute */
      var header         = document.querySelector('[md-page-header]');
      /* Store header dimensions to initialize header styling */
      var baseDimensions = header.getBoundingClientRect();
      /* DOM element with md-header-title attribute (title in toolbar) */
      var title          = angular.element(document.querySelector('[md-header-title]'));
      /* DOM element with md-header-picture attribute (picture in header) */
      var picture        = angular.element(document.querySelector('[md-header-picture]'));
      /* DOM element with main-fab class (a DOM element which contains the main float action button element) */
      var fab            = angular.element(document.querySelector('.main-fab'));
      /* The height of a toolbar by default in Angular Material */
      var legacyToolbarH = 50;
      /* The mid-height of a float action button by default in Angular Material */
      var legacyFabMid   = 56/2;
      /* The zoom scale of the toolbar title when it's placed at the bottom of the header picture */
      var titleZoom      = 1.5;
      /* The primary color palette used by Angular Material */
      var primaryColor   = [255,202,50];

      function styleInit () {
        title.css('padding-left','16px');
        title.css('position','relative');
        title.css('transform-origin', '24px');
      }

      function handleStyle(dim) {
        fab.css('top',(dim.height - legacyFabMid)+'px');

        if ((dim.bottom-baseDimensions.top) > legacyToolbarH) {
            title.css('top', ((dim.bottom-baseDimensions.top)-legacyToolbarH)+'px');
            element.css('height', (dim.bottom-baseDimensions.top)+'px');
            title.css('transform','scale('+((titleZoom-1)*ratio(dim)+1)+','+((titleZoom-1)*ratio(dim)+1)+')');
        } else {
            title.css('top', '0px');
            element.css('height', legacyToolbarH+'px');
            title.css('transform','scale(1,1)');
        }

        if ((dim.bottom - baseDimensions.top) < legacyToolbarH * 5.8 && !fab.hasClass('hide')) {
            fab.css('top','30%');

            document.getElementById("buttonEmail").style.WebkitTransition = "all 1s"; // Code for Safari 3.1 to 6.0
            document.getElementById("buttonEmail").style.transition = "all 1s";       // Standard syntax
        }

        if((dim.bottom - baseDimensions.top) > legacyToolbarH * 0.3 && fab.hasClass('hide')) {
            fab.css('top',(dim.height - legacyFabMid)+'px');
        }

        element.css('background-color','rgba('+primaryColor[0]+','+primaryColor[1]+','+primaryColor[2]+','+(1-ratio(dim))+')');
        picture.css('background-position','50% '+(ratio(dim)*50)+'%');
        /* Uncomment the line below if you want shadow inside picture (low performance) */
        //element.css('box-shadow', '0 -'+(dim.height*3/4)+'px '+(dim.height/2)+'px -'+(dim.height/2)+'px rgba(0,0,0,'+(ratio(dim))+') inset');
      }

      function ratio(dim) {
        var r = (dim.bottom-baseDimensions.top)/dim.height;

        if(r < 0) return 0;
        if(r > 1) return 1;
        return Number(r.toString().match(/^\d+(?:\.\d{0,2})?/));
      }

      styleInit();
      handleStyle(baseDimensions);

      /* Scroll event listener */
      angular.element($window).bind("scroll", function() {
        var dimensions = header.getBoundingClientRect();
        handleStyle(dimensions);
        scope.$apply();
      });

      /* Resize event listener */
      angular.element($window).bind('resize',function () {
        baseDimensions = header.getBoundingClientRect();
        var dimensions = header.getBoundingClientRect();
        handleStyle(dimensions);
        scope.$apply();
      });

    };
});

Fiz baseado neste tutorial.
Comment: Quando digo "Somente no momento em que ela é carregada" é porque quando eu movimento o scroll ele fica normal.
Answer: Você poderia tentar ocultar com css:

seu-elemento {
  overflow-x: hidden;
  overflow-Y: hidden;
}
Answer: Fiz alterações na minha diretiva e funcionou.
app.directive("scroll", function ($window) {

    return function(scope, element, attrs) {
        angular.element(document).ready(function(){
          /* header DOM element with md-page-header attribute */
          var header         = document.querySelector('[md-page-header]');
          /* Store header dimensions to initialize header styling */
          var baseDimensions = header.getBoundingClientRect();
          /* DOM element with md-header-title attribute (title in toolbar) */
          var title          = angular.element(document.querySelector('[md-header-title]'));
          /* DOM element with md-header-picture attribute (picture in header) */
          var picture        = angular.element(document.querySelector('[md-header-picture]'));
          /* DOM element with main-fab class (a DOM element which contains the main float action button element) */
          var fab            = angular.element(document.querySelector('.main-fab'));
          /* The height of a toolbar by default in Angular Material */
          var legacyToolbarH = 50;
          /* The mid-height of a float action button by default in Angular Material */
          var legacyFabMid   = legacyToolbarH/2;
          /* The zoom scale of the toolbar title when it's placed at the bottom of the header picture */
          var titleZoom      = 1.5;
          /* The primary color palette used by Angular Material */
          var primaryColor   = [255,202,50];

          function handleStyle(dim) {
            //fab.css('top',(dim.height - legacyFabMid)+'px');
            //fab.css('top', '90%');

            var dif = dim.bottom - baseDimensions.top;
            var difMeio = dim.height - legacyFabMid;

            console.log("Diferenca "+dif);
            console.log("toolbar "+legacyToolbarH);

            if (dif > legacyToolbarH) {
                element.css('height', dif+'px');
                fab.css({'top': difMeio+'px','position':'absolute'});
            } else {
                element.css('height', legacyToolbarH+'px');
                fab.css({'top':'20px','position':'fixed'});
            }

            element.css('background-color','rgba('+primaryColor[0]+','+primaryColor[1]+','+primaryColor[2]+','+(1-ratio(dim))+')');
            picture.css('background-position','50% '+(ratio(dim)*50)+'%');
            /* Uncomment the line below if you want shadow inside picture (low performance) */
            //element.css('box-shadow', '0 -'+(dim.height*3/4)+'px '+(dim.height/2)+'px -'+(dim.height/2)+'px rgba(0,0,0,'+(ratio(dim))+') inset');
          }

          function ratio(dim) {
            var r = (dim.bottom-baseDimensions.top)/dim.height;

            if(r < 0) return 0;
            if(r > 1) return 1;
            return Number(r.toString().match(/^\d+(?:\.\d{0,2})?/));
          }

          handleStyle(baseDimensions);

          /* Scroll event listener */
          angular.element($window).bind("scroll", function() {
            var dimensions = header.getBoundingClientRect();
            handleStyle(dimensions);
            scope.$apply();
          });

          /* Resize event listener */
          angular.element($window).bind('resize',function () {
            baseDimensions = header.getBoundingClientRect();
            var dimensions = header.getBoundingClientRect();
            handleStyle(dimensions);
            scope.$apply();
          });
        });
    };
});

Problemas com barra de navegação


how to insert negative value without minus symbol in mysql database?

Question: My question is that .. i want to insert negative value for eg: -456 into my DB with out the "-" minus symbol...
Comment: I do not understand the quesion. What's the problem with the minus sign?
Comment: you can have binary no and convert it to integer .
Comment: So a positive value?
Comment: ya .. i got the answer by the way ... INSERT INTO Table VALUES(ABS(-456))
Answer: Use ABS function. That is
INSERT INTO Table VALUES(ABS(-456))
Answer: :) DOnt know what is your perpose, but
 Use two column, one for the value and another one for value type

my_value (int) | value_type (tinyint, default: 1)  // consider 1 for + and o for -
456            | 0 //false or 0 for -456
456            | 1 // true or 1 for +456
.. :,)
Comment: Thank you ... @Jayanta Baishya
Answer: A very bizarre question. But if still you want a solution for this then here it is -
Solution 1
As suggested by the others that you can use ABS() to remove your '-' sign from the data. BUT, I think in this case you will loose your valuable information.
Solution 2
You can use a Benchmark number according to your max negative value. According to your example, for -456, if it is max negative value then you can use 1000 as a Benchmark number. And in the logic just use
INSERT INTO Table VALUES( <YourData> + 1000 )

Hence, you will save 544 in your table. Like wise, in case of positive value, for example 456, data will be saved as 1456.
Remember, it will avoid you to create an extra column to save your number sign ('-' or '+'), BUT, in each DQL query (select *) you have to use your Benchmark number by calculating difference to get the correct data.
SELECT <YourStoredDataColumnName> - 1000 FROM Table


Consuming ASMX Web Service With WCF

Question: I have to write a WCF service that consumes a third party 'Web Service'. They provided WSDL and  the URL so that I can post the transaction. Can some body please help me how to achieve this, with some code example.
Thanks in advance
BB
Answer: Would this help?
How to convert WSDL file to class file
Answer: I just used the normal method and they worked fine for me. Just add a web reference to the project and go from there.

Consuming ASMX Web Service With WCF


Problema com os Paths dos arquivos no meu projeto

Question: Uma certa vez eu criei uma pasta e copiei todos os arquivos do meu projeto para ela, porém a partir disto o meu projeto original está com os caminhos form1.cs, form1.designer.cs e form1.resx especificados para a pasta cópia.
Não estou conseguindo voltar com as configurações originais, como eu altero o caminho dos arquivos para deixar tudo em uma única pasta?
Nota

Tentei alterar pelas propriedades, porém fica bloqueado.

LOCALIZAÇÃO DO ARQUIVO .sln
D:\Felipe Pen Drive\arquivos...\Aplicativo...

LOCALIZAÇÃO DOS ARQUIVOS form1.cs, form1.designer.cs e form1.resx
D:\Felipe Pen Drive\copia

CONFIGURAÇÃO DA PROPRIEDADE
Answer: Você pode adicionar os forms existentes (que estão na pasta correta) "de volta" ao projeto. Para isso, clique com o botão direito no projeto e vá em: Adicionar -> Item existente (Shift + Alt + A) e selecione os arquivos form1.cs, form1.designer.cs e form1.resx. O VS irá substituir automaticamente os caminhos desses itens em suas respectivas propriedades.


Logistic Regression models with two or more response variables in R/SAS

Question: There are a lot of inconsistencies in the literature over what should be the appropriate term(s) for the regression models involving two or more responses, and if they are binary/continuous, for more than one predictor variable.
I have three questions/clarifications regarding these:

Multivariate Logistic Regression is one where we have more than one response variable and they are all binary. The predictors could be categorial or continuous.
I also found that this is aka Mixed Effect Logistic Regression by some. Though I still think it is up for debate.

Multinomial Logistic Regression is one where we have only one response variable which has more than two classes. The predictors could be categorial or continuous.

Multivariate Linear Regression is when we have more than one response variable and they are all continuous. The predictors could be categorial or continuous.

Can somebody please confirm if these definitions are appropriate and point me in the right direction to execute these regression models in R/SAS/Python with right commands...
Comment: The term "multivariable" is also used (multiple regression = multivariable regression). [Explain the difference between multiple regression and multivariate regression, with minimal use of symbols/math](https://stats.stackexchange.com/q/2358/237901).
Comment: The paper https://journals.sagepub.com/doi/abs/10.1177/1094428106287455 may have what you want. It has SAS code too.
Answer: I agree with you that the distinction between multiple and multivariate is typically fishy for novices.
However rest assured that, multiple regression is one which considers more than one explanatory variable (aka features). On the other hand, multivariate regression is a model which considers many response variables at a time. As a rule of thumb to distinguish between them

MULTIPLE are the features you include
MULTIVARIATE is the response you deal with

Thus, regarding the models listed

Your description is correct. In addition, Mixed models could be multiple or multivariate or both.

Your description is correct. Multinomial logistic regression has necessarily a multivariate response, e.g. realizations from a multinomial random vector.

This is also correct.

To perform multivariate or univariate multiple regression in R use lm. To perform logistic regression you may consider glm.
Multivariate logistic regression is more elaborate because you have to setup a model yoursel depending on the context of study (e.g. longitudinal data analysis, etc.).
For multinomial logistic regression, there is multinom from the nnet package (see here for an example)
Comment: Unfortunately, I'm not a SAS user so I can't help you with it. I'm very familiar with `python` but `statsmodel` module may be one direction.


Text with unicode CODES not displaying correctly in Python 3.7

Question: After being hours checking every stackoverflow post related to this, I'm pulling my hair to solve what should be a very simple thing...
I have a text file with unicode codes (not characters, codes), for example:

"Edward escribi\u00c3\u00b3 la biograf\u00c3\u00ada de su autor
  favorito"

This string should be displayed as:

"Edward escribió la biografía de su autor favorito"

If I load the file as I normally do, I will just see the unicode strings when I print the loaded text:
import io
chars = io.open(fb_json_path, encoding='utf-8').read().strip()

This prints: "Edward escribi\u00c3\u00b3 la biograf\u00c3\u00ada de su autor favorito". It's the same if I remove the encoding parameter.
I guess I need to tell Python to interprete the codes in the string and display them as utf-8 characters, but I don't get how to do that.
Thanks in advance!
Comment: Are the quotes in the file?
Comment: @SergeBallesta no, the file does not contain those quotes.
Answer: We can do that in two steps:
First, we read the file with encoding='unicode_escape' to convert all of the \uxxxx.
Then, we convert this to utf-8 by encoding it transparently to a bytes object (with latin-1 codec) and convert it to text again, decoding as utf-8
with open('text.txt', encoding='unicode-escape') as f:
    text = f.read()
    print(text)
    #Edward escribió la biografía de su autor favorito

    # Now we convert it to utf-8
    text = text.encode('latin1').decode('utf8')
    print(text)
    # Edward escribió la biografía de su autor favorito

Comment: Beautiful !! Thanks so much @Thierry !
Answer: I believe the input is somehow garbled by wrong encoding.
C3 93 are the UTF-8 encoding bytes for the ó(LATIN CAPITAL LETTER O WITH ACUTE).
run in Python 3 console
>>> text = "Edward escribi\u00c3\u00b3 la biograf\u00c3\u00ada de su autor favorito"
>>> text.encode('cp1252').decode('utf8')
'Edward escribió la biografía de su autor favorito'


Can't retrieve forecast cost using Azure Cost Management API for Month range (start date to last date) if the request happen in 1st date of month

Question: I'm using Azure Forecast Cost Management API to try to retrieve the forecast cost shown in the azure portal like below.

This is the API I'm using -> https://learn.microsoft.com/en-us/rest/api/cost-management/forecast/usage?tabs=HTTP
This is my request body looks like
<code>{
"Dataset": {
        "Aggregation": {
            "TotalCost": {
                "Function": "Sum",
                "Name": "Cost"
            }
        },
        "Granularity": "Monthly"
    },
    "TimePeriod": {
        "From": "2023-02-01",
        "To": "2023-02-28"
    },
    "Timeframe": "Custom",
    "Type": "Usage"
}
</code>
Everything is working if i did the request not in the 1st day of month. But when i make a request to API in 1st day of month, the request is success and the API give me a response, but i can't find any information related to forecast cost amount.
I can see the forecast cost from the Azure portal, so i believe there must be a way to retrieve the data. Help me please?
Thanks.
I have try to modify the timeframe, granularity, and others in the request body. But still can't get the data.
Answer: Check the datetime you are using is the same as what is being used on Azure for the service/plan/account or whatever, these can differ on both sides.It could also be that Azure requires the datetime in GMT or a US format.
So it may be that your request is being read as last month, but azure is only providing data for this in the upcoming month.
To test this try switching to prior dates and see if any dates in the past give you the same data as what you are getting on the 1st. If so I would say that is what is happening.
The fact it only occurs on the first but the data is available in the portal would indicate to me it is definitely something to do with the timezone, but I could be wrong.
Answer: Personally I use Azure Cost Management connector in Power BI Desktop to retrieve the data. I scheduled a daily refresh and I never had problems.
I know for sure that there are problems with calculation in the early days of the month and I have a colleague that withdraw the last month after the first week.
I suggest you to open a ticket with the Azure Billing support.


Docking a WPF window to left/right sides of the screen windows 7/8

Question: In both Window Forms and WPF there is this .WindowState which I can set to
Minimized,
maximized or Normal
I wonder if there is anything similar already implemented for docking the window to the left/right sides of the screen like with the Win + <- / -> keys for Windows 7/8?
I've googled and it seems people call Win32 APIs and implement this on their own
Am I supposed to write a custom docking code or is there a simple flag I can set somewhere like the WindowState ?
Comment: @TFD your manners are broken?
Comment: Related: http://stackoverflow.com/questions/8368540/save-and-restore-aero-snap-position-on-windows-7
Answer: No, there isn't a flag that you can set.  Windows changes the rectangle of the window, and the WPF Window has no knowledge of what is happening except that the rectangle has changed.
It is quite simple to change the rectangle on your own. (Actually replacing the functionality of Windows is a bit more challenging.)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace StackOverflowWPF
{
   ///
   /// Interaction logic for MainWindow.xaml
   ///
   public partial class MainWindow : Window
   {
      public MainWindow()
      {
         InitializeComponent();
      }

      private void Button_Click_1(object sender, RoutedEventArgs e)
      {
         this.Top = 0;
         this.Left = 0;
         System.Drawing.Rectangle screenBounds = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
         this.Width = screenBounds.Width / 2;
         this.Height = screenBounds.Height;
      }
   }
}

Comment: Window maximized state is more than just different bounds.
Comment: Not from the point of view of the WPF window.  Windows tracks the rectangles on its own.  The WPF Window has no knowledge of what is happening except that the rectangle has changed.
Comment: I improved my answer a bit based on what @Banana said.


Can a point of inflection exist where the first derivative is undefined?

Question: In Thomas's Calculus book, an inflection point is defined as:
"A point where the graph of a function has a tangent line and where the concavity changes". Then the definition is followed by this example:
$f(x)= x^{1/3}$ where $x=0$ is a point of inflection. But the 1st derivative is undefined at $x=0$ (i.e. there is no tangent line), which contradicts the definition. How can this be possible?
Comment: Use LaTeX please.
Comment: Welcome to MathSE.  This [tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) explains how to typeset mathematics on this site.
Comment: I suspect "tangent line" is being used in such a way that a point at which both unilateral derivatives are infinite at the point (there are four possibilities for the sign permutations) has a vertical tangent line at that point.
Answer: There is no contradiction. A graph of a function can have a tangent without being differentiable. Note that $x = 0$ (the $y$-axis) is a tangent to $f$ at $(0,0)$.
Answer: The notion of  inflection point is a geometric idea that should not be restricted to graphs $y=f(x)$. We are talking about regular curves
$$\gamma:\quad t\mapsto\bigl(x(t),y(t)\bigr)\qquad(a\leq t\leq b)\ .\tag{1}$$
Regular means that $\gamma$ is continuously differentiable, and that $\bigl(x'(t),y'(t)\bigr)\ne(0,0)$ on $[a,b]$. The tangent vector $\bigl(x'(t),y'(t)\bigr)$ has for all $t$ a well defined argument (polar angle)
$$\theta(t):={\rm arg}\bigl(x'(t),y'(t)\bigr)\ .$$
To be precise, this $\theta(t)$ is only defined up to multiples of $2\pi$, but this does not need to bother us here. If $x'(t)>0$ then we may put $$\theta(t)=\arctan{y'(t)\over x'(t)}\ .$$
Now let $t_0$ be an interior point of the interval $[a,b]$. Then $\gamma$ has an inflection point at $P_0:=\gamma(t_0)$ if the function $t\mapsto\theta(t)$ is strictly increasing for $t\leq t_0$ and is strictly decreasing for $t\geq t_0$, or conversely.
If $\gamma$ is presented as graph $y=f(x)$ of a $C^2$-function then the above definition translates into the well known condition that $f''$ should change sign at $x_0$. In order to do Thomas' example correctly you should present the cubic parabola in the form $x=f(y):=y^3$ or by means of the parametrization $y\mapsto(y^3,y)$.
Answer: There is a problem in what you are claiming to be a definition,tangent may exist but derivative not at a point on a curve.