Trying to properly shape tensors in tensorflow. Can't get the dimensions correct

Question: I'm running a simple univariate logistic regression program written in Tensorflow.  I can't, however, get my shapes properly from my training set to the x placeholder.  I've been trying various methods to do so, I'm always getting the error:
ValueError: Cannot feed value of shape (70,) for Tensor 'Placeholder_1:0', which has shape '(?, 1)'

This is from the tf.matmul command.
Printing the shapes of the relevant variables:
w =  <tf.Variable 'Variable:0' shape=(1, 1) dtype=float32_ref>
x =  Tensor("Reshape:0", shape=(?, 1), dtype=float32)
train_x =  (70, 1)

The problem seems to be that even through the train_x array has a shape of (70, 1) TF doesn't seem to recognize this.
How do I fix this problem?  I've been trying the reshape command, but without success.
Here's the code.
#!/usr/bin/env python3
import tensorflow as tf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import model_selection
import sys

gender_df = pd.read_csv('data/binary_data.csv',dtype = {col: np.float32 for col in ['HEIGHT'] })
print (gender_df.info())

# Shuffle our data
gender_df = gender_df.sample(frac=1).reset_index(drop=True)

num_features = 1
num_classes = 1
# We'll go ahead and split the data set into training and testing parts.
# 70 per cent will go to training, the rest to testing.
train_x,test_x, train_y, test_y = model_selection.train_test_split(gender_df['HEIGHT'],gender_df['GENDER'],test_size = 0.3)

n_samples = train_x.shape[0]

# These will be the placeholders for the testing and training data
x = tf.placeholder('float',[None,num_features+1])
y = tf.placeholder('float',[None,num_classes])

# Variables for the weight and bias.
W = tf.Variable(tf.zeros([num_features, num_classes]))
b = tf.Variable(tf.zeros([num_classes]))

x = tf.reshape(x,[-1, num_features])
train_x = train_x.values.reshape(-n_samples,num_classes)
print ('w = ',W)
print ('x = ',x)
print ('train_x = ', train_x.shape)
# This is our activation function to determine the probability
# of our gender based on height.
#activation = tf.nn.sigmoid((W * x) + b)
activation = tf.nn.softmax(tf.add(tf.matmul(x,W), b))

# Set our alpha value for the optimizer.
learning_rate = 0.001

# cross_entropy is our cost function.
cross_entropy = tf.reduce_mean(-(y*tf.log(activation) + (1 - y) * tf.log(1-activation)))

# We'll use a standard gradient descent optimizer.
train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

# Now train our jodel.
    for epoch in range(1000):
        _,l = sess.run([train_step, cross_entropy], feed_dict = {x: train_x, y:train_y})
        if epoch % 50 == 0:
            print ('loss = %f' %(l))

# Now let's see how our model performed on the test data.
    correct = tf.equal(tf.argmax(activation,1), tf.argmax(y,1))
    accuracy = tf.reduce_mean(tf.cast(correct,'float'))
 print ('Accuracy: ', sess.run(accuracy,feed_dict = {x: test_x, y:test_y}))

Answer: You are printing the shape of your x placeholder and train_x batch, but what about labels? Your x placeholder is of the shape (?, 2), so it seems that the error is not referring to x, it is referring to y, which is (?, 1). Check the shape of your train_y variable.


What should be used for executing a task repeatedly at fixed intervals in android?

Question: In my android application the scenario is this -
I have several images stored in the SD card.
Now in my app I have an Image view and I have to update this image view continuously
like a slide show is running. This has to be done by fetching images one by one from SD card and setting them in the same ImageView. Also the interval of image change in ImageView is fixed.
So I have a cursor which stores the information for fetching these images.
Now I am wondering what should be my approach for moving the cursor one by one and fetching images from SD card and setting them in my ImageView.
Should I use Timer Task and Timer or should I go with Handler or something else?
Please help as this is initial point of my app and I  want to start in the right direction.
Answer: Since you're retrieving large data from the SD card, it might be best to use a thread to retrieve/decode the bitmap.
In this case, a Timer would be useful because it runs on it's own Java thread for scheduled periods of time.  However, you have to keep in mind that you can't update a UI element from a non-UI thread.  Thus, you'd need a syncing element in place for when the bitmap is fully loaded to finally put the decoded bitmap in to the ImageView.  In which case, you would need to use Handler anyway to send message queues to the UI thread.
Thus, I'd probably recommend using a combination of Handler and AsyncTask.  Create an AsyncTask class that retrieves and decodes the bitmap in doInBackground().  Update the ImageView in onPostExecute().  Use a Handler to create and execute a new AsyncTask ever Nth milliesecond (whenever you update the view).
One advantage to this is it keeps all image retrieval in one class.  You can open the cursor, retrieve, close it.  This is safer than keeping a long-running cursor open.


Deplhi with Indy and TLS, problems with https://testesmoleculares.com.br/ (Cloudflare)

Question: I'm not have expertise with Delphi and TLS using Indy.
Maybe it's not a problem, just config, I need examples.
I tried some questions on Stackoverflow too, all unsuccessfully.
Page: https://testesmoleculares.com.br/
Errors:
---------------------------
Debugger Exception Notification
---------------------------
Project IntegradorApoiado.exe raised exception
 class EIdOSSLUnderlyingCryptoError with message 'Error connecting with SSL.
error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure'.
---------------------------
Break   Continue   Help
---------------------------

Actual config:
LHandler.SSLOptions.Method := sslvSSLv2;
LHandler.SSLOptions.Mode := sslmClient;
LHandler.SSLOptions.SSLVersions := [sslvSSLv2];

Tried:
IdSSLIOHandlerSocketOpenSSL1.SSLOptions.Method := sslvTLSv1_2;
IdSSLIOHandlerSocketOpenSSL1.SSLOptions.SSLVersions := [sslvTLSv1_2];

Someone can help?
Maybe providing an example of POST? I'm using Delphi XE4
Thanks!
Github issue:
https://github.com/IndySockets/Indy/issues/317
Tried:

https://stackoverflow.com/a/49061252
ssl v3 poodle and move to tls with indy
Using Indy 10 IdHTTP with TLS 1.2
https://indy.fulgan.com/SSL/?C=M;O=A
Others
Answer: Without seeing the actual handshake data, it is difficult to say for sure why it is failing.
However, I will mention that sslvSSLv2 is for SSL v2.0, which nobody uses anymore, as it is no longer secure.  Same with sslvSSLv3 (SSL v3.0).  So, never use sslvSSLv2 and sslvSSLv3 (unless you HAVE to, for legacy purposes).
sslvTLSv1_2 is for TLS v1.2.  A lot of servers are now migrating to this.  But many servers haven't fully migrated yet.  So, you should enable TLS v1.0 and v1.1 as well for wider acceptance, eg (do not use SSLOptions.Method at all, just use SSLOptions.SSLVersions):
LHandler.SSLOptions.Mode := sslmClient;
LHandler.SSLOptions.SSLVersions := [sslvTLSv1, sslvTLSv1_1, sslvTLSv1_2];

By specifying multiple TLS versions, that will allow OpenSSL to negotiate an available version that both peers support.
Also, make sure you are using an up-to-date version of Indy (if you are not already) so that you have all of its fixes for TLS support, such as use of SNI (which many servers now require TLS clients to use).
I can connect to https://testesmoleculares.com.br/ in a web browser using TLS 1.2, so it should be possible to connect to it using TLS 1.2 in Indy as well.

UPDATE: based on additional comments you have posted for this same issue in Indy's issue tracker (#317: TLS - Problems with https://testesmoleculares.com.br/ on Cloudflare), you are using an outdated version of Indy (10.6.0.4975), which does not fully handle TLS 1.2.  You need to upgrade to the latest version (10.6.2) in order to use TLS 1.2 properly.
Comment: CDNs like Cloudflare, which this site uses, are especially likely to require SNI.
Comment: (Solved) More info in: https://github.com/IndySockets/Indy/issues/317#issuecomment-672207978 Thanks! @remy-lebeau


Rust compilation error: failed to run custom build command for `clang-sys v1.6.1`

Question: I am trying to build a Rust program on Centos with kernel 6.20. When trying to compile a Rust file I keep getting the following error messages.
cargo build --manifest-path=atropos/Cargo.toml --release
   Compiling proc-macro2 v1.0.56
   Compiling unicode-ident v1.0.8
   Compiling quote v1.0.26
   Compiling libc v0.2.141
   Compiling autocfg v1.1.0
   Compiling version_check v0.9.4
   Compiling syn v1.0.109
   Compiling serde_derive v1.0.159
   Compiling cc v1.0.79
   Compiling bitflags v1.3.2
   Compiling hashbrown v0.12.3
   Compiling serde v1.0.159
   Compiling pkg-config v0.3.26
   Compiling memchr v2.5.0
   Compiling toml_datetime v0.6.1
   Compiling thiserror v1.0.40
   Compiling winnow v0.4.1
   Compiling once_cell v1.17.1
   Compiling io-lifetimes v1.0.10
   Compiling cfg-if v1.0.0
   Compiling rustix v0.37.7
   Compiling proc-macro-error-attr v1.0.4
   Compiling proc-macro-error v1.0.4
   Compiling indexmap v1.9.3
   Compiling glob v0.3.1
   Compiling heck v0.4.1
   Compiling anyhow v1.0.70
   Compiling memoffset v0.6.5
   Compiling camino v1.1.4
   Compiling linux-raw-sys v0.3.1
   Compiling serde_json v1.0.95
   Compiling clang-sys v1.6.1
   Compiling semver v1.0.17
   Compiling aho-corasick v0.7.20
   Compiling syn v2.0.13
   Compiling regex-syntax v0.6.29
   Compiling itoa v1.0.6
   Compiling log v0.4.17
   Compiling libbpf-sys v1.1.1+v1.1.0
   Compiling minimal-lexical v0.2.1
   Compiling os_str_bytes v6.5.0
   Compiling ryu v1.0.13
   Compiling nom v7.1.3
   Compiling toml_edit v0.19.8
   Compiling clap_lex v0.2.4
error: failed to run custom build command for `clang-sys v1.6.1`

Caused by:
  process didn't exit successfully: `/root/sched_ext/tools/sched_ext/atropos/target/release/build/clang-sys-eaa3a1b9c03ac901/build-script-build` (exit status: 101)
  --- stderr
  thread 'main' panicked at 'could not find any static libraries', /root/.cargo/registry/src/github.com-1ecc6299db9ec823/clang-sys-1.6.1/build/static.rs:92:9
  note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
warning: build failed, waiting for other jobs to finish...
make: *** [Makefile:201: atropos] Error 101

When I run with RUST_BACKTRACE=1 environment variable to display a backtrace, I get the following information.
or: failed to run custom build command for `clang-sys v1.6.1`

Caused by:
  process didn't exit successfully: `/root/sched_ext/tools/sched_ext/atropos/target/release/build/clang-sys-eaa3a1b9c03ac901/build-script-build` (exit status: 101)
  --- stderr
  thread 'main' panicked at 'could not find any static libraries', /root/.cargo/registry/src/github.com-1ecc6299db9ec823/clang-sys-1.6.1/build/static.rs:92:9
  stack backtrace:
     0: std::panicking::begin_panic
     1: build_script_build::static::find
     2: build_script_build::static::link
     3: build_script_build::main
     4: core::ops::function::FnOnce::call_once

Why does this error occur and How do I fix this error? Thanks.
Comment: Looks like you don't have `clang` (maybe it's `libclang`, `clang-dev` or `libclang-dev` not sure on the correct package name for CentOS) installed.
Answer: Had similar problem when working with crate opencv, error:
Compiling clang-sys v1.6.1
The following warnings were emitted during compilation:

warning: could not execute `llvm-config` one or more times, if the LLVM_CONFIG_PATH environment variable is set to a full path to valid `llvm-config` executable it will be used to try to find an instance of `libclang` on your system: "couldn't execute `llvm-config --prefix` (path=llvm-config) (error: No such file or directory (os error 2))"

error: failed to run custom build command for `clang-sys v1.6.1`

I'm building on Ubuntu machine so it was solved by installing: apt install libopencv-dev clang libclang-dev


Enable/Disable Button based on selected value

Question: I have a button in my view
<v-menu offset-y>
  <v-btn>
    Action Items
  </v-btn>
  <v-list>
   <v-list-tile
    v-for="(item, index) in items"
    :key="index"
   :disabled="item.disabled"
  >
   <v-list-tile-title>{{ item.title }}</v-list-tile-title>
   </v-list-tile>
  </v-list>
 </v-menu>

<v-data-table
         v-model="selected">

my data looks like


PHP CURL How to GET cookie like POSTMAN?

Question: Hi I'm trying to setup a PHP CURL call using OAuth1 authorization method.
I've tried with POSTMAN 1st, to generate the PHP code. I've completed it with the necessary datas
<?php
$conskey = 'XXXXXXX';
$conssec = 'XXXXXXX';
$nonce     = mt_rand();
$timestamp = time();
$url = 'https://some-website/api/project/subproject';
$method = 'POST';

$oauth = new OAuth($conskey, $conssec, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION);
$oauth->setNonce($nonce);
$oauth->setTimestamp($timestamp);
$signatureOAuth = $oauth->generateSignature($method,  $url);

$curl = curl_init($url);

curl_setopt_array($curl, array(
    CURLOPT_URL => $url.'?oauth_consumer_key='.$conskey.
        '&oauth_signature_method=HMAC-SHA1&oauth_timestamp='.$timestamp.
        '&oauth_nonce='.$nonce.
        '&oauth_version=1.0&oauth_signature='.$signatureOAuth,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => $jsonDatas,
    CURLOPT_HTTPHEADER => array(
        'Content-Type: application/json',
// THE COOKIE I WANNA GET
        'Cookie: SSESSd4f3e89d4699e1d1a071aa37eab4fcEd=DWS4UqpaykI2y7q-HJXEzGN82AKHQYnWo5hbsqkAqiQ'
    ),
));

$result = curl_exec($curl);
curl_close($curl);

But I've noticed that there's the cookie in the CURLOPT_HTTPHEADER entry but I don't have any idea how POSTMAN generate this cookie.
Without this cookie or with a dumb string, the CURL response is always Invalid Signature
Comment: Maybe use a [cookie jar](https://stackoverflow.com/questions/30760213/save-cookies-between-two-curl-requests)?
Comment: I've take a look at it but I don't understand how I can send the request without having the cookies 1st ?
Comment: https://learning.postman.com/docs/sending-requests/cookies/ If you read this it might be helpful
Comment: @İbrahim thanks, I did! but i dont see any part concerning the retrieve/generation of the cookie value. Just how to set cookie using POSTMAN. Did I miss something in the doc ?
Comment: I'm not really sure if postman is generating those cookies on their own. I would say that you had to do the call to the API previously and within that previous response cookie was created. For each subsequent request Postman is adding this cookie, as the browser would do. It's server that is asking to create a cookie on a client side by [Set-Cookie header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie).
Comment: Postman doesn't generate cookies for you. you either did some prior GET requests to the website where postman recieved cookies, or gave the cookies to postman somehow.
Comment: show us the actual url and we can probably help you.
Answer: Postman is not generating cookies for you, and neither is curl/php. you either did some prior requests (usually GET to get cookies) requests to the website where you received some cookies, or gave the cookies to postman some other way.
since you're not showing us the real url, we can only speculate, but to take an example, here is how to get a session cookie for stackoverflow.com:
<?php
$ch=curl_init();
curl_setopt_array($ch,array(
  CURLOPT_COOKIEFILE => "", // setting it to empty activates the curl cookie engine (its disabled by default.),
  CURLOPT_URL => "https://stackoverflow.com/",
  CURLOPT_RETURNTRANSFER => true,
));
$html=curl_exec($ch);
$cookies = (function($cookielist):array{
  $cookies = array();
  foreach($cookielist as $cookie_raw) {
      $chunks = explode("\t", $cookie_raw);
      //var_dump($chunks);
      $cookie['domain'] = $chunks[0];
      $cookie['secure'] = $chunks[1];
      $cookie['path'] = $chunks[2];
      $cookie['???todo_wtf_is_this'] = $chunks[3];
      $cookie['expiration'] = $chunks[4];
      $cookie['name'] = $chunks[5];
      $cookie['value'] = $chunks[6];
      $cookies[] = $cookie;
  }
  return $cookies;
})(curl_getinfo($ch, CURLINFO_COOKIELIST));
var_export($cookies);

prints something like
array (
  0 =>
  array (
    'domain' => '#HttpOnly_.stackoverflow.com',
    'secure' => 'TRUE',
    'path' => '/',
    '???todo_wtf_is_this' => 'FALSE',
    'expiration' => '2682374400',
    'name' => 'prov',
    'value' => '9c06f038-9f70-bee8-2a64-b095656175d1',
  ),
)

which could be used like
// THE COOKIE I WANNA GENERATE
        'Cookie: '. $cookies[0]["name"].'='.$cookies[0]["value"]

but this is very rarely done, usually you'd just use curl's built-in cookie engine to handle cookies automatically..


Why my subject observable subscriber is calling multiple times in angular?

Question: In angular i have a service like this
  private subject = new Subject<any>();
  private  vehicleSubject = new Subject<any>();

  sendData = (data: any) => this.subject.next({ data });

  sendVehicleData = (data: any) => this.vehicleSubject.next({ data });

  getData = (): Observable<any> => this.subject.asObservable();

  getVehicleData = (): Observable<any> => this.vehicleSubject.asObservable();

Now i have my sidebar(parent) component like this with tab view both of primeng in my sidebar.component.html

    {{user?.fullName}}

                Services & Inspections
 -->

                Inspection works
 -->

in my sidebar.component.ts when sidebar is opened and user click on outside of sidebar so i will pas data to my child component like this
  onSidebarOutside(e) {
   if (this.index === 0 && this.sideBarVisible &&
     !this.isCustomerCancelBtnClicked) {
     e.target.value = true;
     this.verifyCustomer = e;
  } else if(this.index === 1){
      console.log('in index 1');
      this.dataService.sendVehicleData(true);
  }
  if (this.isCustomerCancelBtnClicked) {
    this.isCustomerCancelBtnClicked = false;
   }
  }

Inside my vehicle-side-list.component i have a subscriber in ngOnInit to get data like this
ngOnInit() {
   this.dataService.getVehicleData().subscribe(obj => {
     console.log('in vehicle item subscruber', obj);
    });
}

but problem is this that subscriber inside my vehicle-side-list.component called multiple times and i got this log console.log('in vehicle item subscruber', obj); multiple times. I am noet getting that why is it calling multiple times. I am sending value only once and by sending value from sidebar component it is calling multiple times.
My component calling structure is like this
sidebar
  -customer-component
    -appointment-component
  -vehicle-component
    -appointment-component
  -inspection-component
    -appointment-component

And i want to pass data from sidebar to appointment-component
What am i doing wrong here?
Comment: I am thinking that you have memory leak. You are subscribing to that Observable many times and you don't unsubscribe. Give it a test, refresh the website and check the functionality. The issue will happen only if you navigate between pages and the subscribe happens multiple times.
Comment: @ahsan Did you find any solution for this? i am also facing similar issue and i am blocked.
Answer: Seems like you have not unsubscribed the observable inside ngDestroy method.
Whenever you are clicking you are adding new component which is adding more listeners to that observable. Just unsubscribe the observable in ngDestroy of child component and it should work.
You need following changes in child component. Create a private property and use it to unsubscribe.
private destroy:Subject = new Subject();

ngOnInit() {
   this.dataService.getVehicleData().pipe(
     takeUntil(this.destroy)     // import takeUntil from rxjs/operators.
      ).subscribe(obj => {
     console.log('in vehicle item subscruber', obj);
    });
}

ngOnDestroy() {
  this.destroy.next();
}

[post edited]
Comment: I am not adding new component on clicking. Basically i have `sidebar` as my parent component and in that `sidebar` i have tab view and in each `tab` there is a separate component is calling you can see in my `sidebar.component.html`. I am passing data to my child component only when user is on the tab and click outside of the sidebar. So i am sending data only once but subscriber in my child component calls multiple times
Comment: Are you doing unsubscribing inside the vehicle-side-list.component.ts? I am assuming it is not happening. Does it console multiple times when you click outside the sidebar for first time? I don't think so, It must be happening from second time click outside the sidebar. Please tell?
Comment: I implemented your solution in the way you mentioned. But now the issue is happening that when on first time i click outside of `sidebar` so `subscriber` inside my `vehicle-side-list` component is not calling. And yes i am unsubscribing in my `vehicle-side-list` component. Please not that i have multiple tabs in my sidebar. I just showed my one tab in my question post. And you know that  when tab is switched so component will not destroy.
Comment: can you suggest me a very simple way of sharing data from parent component to child component with observable and without Input?
Comment: If you want to pass data from parent to children without Input then you have to use a share service, is it fine? Can you give more context of your code? Do we have same component for every tab?
Comment: Basically i have `sidebar` my parent component and in `sidebar` i have 4 tabs. And in each tab i am calling separate component. Like in tab1 i am calling component1, in tab2  i am calling component2 like so on. And inside my each tab's component i am calling another common component which is calling in each tab's component. And i want to pass data from `sidebar` to that common component.
Comment: Is it possible for you to create a stackblitz instance? Else please post your complete parent HTML and TScode.
Comment: i have updated my complete Html of `sidebar` component and i also updated the `function` code which is calling when i click outside of `sidebar` and pass data to my `child` component.
Comment: The issue is with unsubscribing inside child components. Subject multicast their values, whenever you are call next method it send values all the listeners subscribed upto that point. You need to unsubscribe the observables inside all children components.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/211851/discussion-between-ahsan-and-prince).
Comment: @JasdeepSingh Could  you please provide solution for this question? I have mutiple tabs in same routing. my subscriber is called n times if n tabs are open.
Comment: @ahsan please let me know if we can connect on this, if you found any solution?
Answer: This is due to the memory leak caused by the subject observable. You can simple solve this by unsubscribing it on ngOnDestroy. It is good practice to unsubscribe the subjects and behavior subject on component destroying to avoid unexpected results.
vehicleDataRef !:Subscription;

  ngOnInit() {
    this.vehicleDataRef = this.dataService.getVehicleData().subscribe(obj => {
    console.log('in vehicle item subscruber', obj);
    });
   }

   ngOnDestroy() {
    this.vehicleDataRef.unsubscribe();
   }


Random slopes -- parsimonious mixed-effects models

Question: This is a beginner level question, and I apologise in advance if the answer is obvious.
If a by-subject random slope for a predictor "X" improves the model fit*, but the predictor "X" is not significant (with and without the by-subject random slope for predictor "X"), is there any point in adding the random slope for predictor "X"? The reason why I am asking this is because I always thought that the point of adding random slopes was to minimise the risk of Type I error, but there is no risk of Type I error with regards to predictor "X" if it is not significant in the first place.
*as judged by the pairwise comparisons using the LRT
Here is an illustration of what I mean:

ordinal_Eiii <- clmm(Understanding ~  zAge + EnglishProficiency + zSTOFHLA+Education + zFRES + zRDL2 + (1|Text) + (1|Subject), data = Study2.pairs,
                link = "probit", threshold = "flexible")

In the above model:
                               Estimate Std. Error z value Pr(>|z|)
zRDL2                          -0.02217    0.13923  -0.159  0.87350

After the addition of a random slope:

ordinal_Eii <- clmm(Understanding ~  zAge + EnglishProficiency + zSTOFHLA+Education + zFRES + zRDL2 + (1|Text) + (zRDL2 + 1|Subject), data = Study2.pairs,
                link = "probit", threshold = "flexible")

                               Estimate Std. Error z value Pr(>|z|)
zRDL2                          -0.18864    0.18454  -1.022  0.30669

Pairwise comparisons using the LRT:

         no.par    AIC  logLik LR.stat df Pr(>Chisq)

ordinal_Eiii     19 1440.1 -701.06
  ordinal_Eii      21 1430.6 -694.31  13.503  2   0.001169 **

In addition to the above, the inclusion of the random slope for zRDL2 changes the estimates of the other predictors. Thus, is the inclusion of random slope for zRDL2 warranted since it decreases the risk of committing a Type I error with regards to the remaining predictors? Am I understanding this right?
Answer: I'm a little bit confused by your use of "pairwise comparisons" to refer to a nested model comparison using the likelihood ratio test.
The likelihood ratio is testing to see if: (a) the variance of the slopes is greater than zero, or (b) the covariance between the random slopes and intercepts is different from zero.
I would first adjust your p-value for the fact that it is testing one hypothesis bounded at zero (i.e., variances cannot dip below zero).
What you have is a significant slope. The fact that this changes the fixed estimate part of zRDL2 doesn't matter much. When I run mixed/multilevel/hierarchical models, I do a top-down approach: I start with a saturated random-effects structure. Then, I start picking away at the random effects and doing nested model comparisons along the way. If there is no significant change when I take something out, then I leave it out.
Then I move onto the fixed effects, doing the same thing.
I think your model with the random slope is an appropriate model, given what you have presented. To the best of my knowledge, this is not because it decreases the risk of committing a Type I error, but because it is the best way to model the variance in your dependent variable. I find that graphing random slopes or showing a spaghetti plot is very, very telling in how the random effects structure looks.
EDIT:
From the comment below:

What I am wondering is: does it make sense to add a random slope of a variable, if that variable is not significant in the first place?

Yes, this makes sense. What it tells you is that the average slope does not differ significantly from zero (i.e., the coefficient's p-value > $\alpha$); however, there is significant variance in slopes among people (i.e., the random slope is statistically significant). What would this look like?
The thick red line represents the average slope: It is not significantly different from zero. The thinner black lines represent the slopes for each person. Note that these vary wildly from positive to negative: The variance is significantly different from zero. This is like what you have in your model.
What is interesting here is that, if you were interested, you could look at moderators at the individual level that might explain when someone has a positive or negative slope.
Comment: Hi Mark. Thank you for your answer and for the useful link on how to adjust my p-value. All my fixed effects are variables of theoretical interest, so a finding that one is not significant is a finding in itself. I started from the fixed-effects, and then I moved onto the random effects. What I am wondering is: does it make sense to add a random slope of a variable, if that variable is not significant in the first place? From your answer it seems that the answer to my question is yes, as long as the random slope improves the model fit -- is my interpretation of your answer correct? Thanks.
Comment: I wanted to include a picture, so I replied above by editing my original answer.


Weird variable initialization when using jQuery.when

Question: I find this very counterintuitive:
var bar = 2;
$.when(function(){bar = 1}).then(function(){
  console.log('print ' + bar)
})
// => print 2

It returns 2 in the console instead of 1. But isn't the callback only supposed to be executed once function(){bar=1} is resolved (i.e., bar = 1)? bar was declared as a global variable as well.
Thanks for your help.
Answer: It's an illusion.
The anon function function(){bar = 1} is not actually executed with this syntax. As per the documentation of $.when, if one of its argument is not a promise then it is treated as a promise that has been resolved with the argument itself as the resolution value.
That is, the code is equivalent to
var f = function(){bar = 1};     // obviously not executed yet
var d = $.Deferred().resolve(f); // still not executed

$.when(d).then(function(){
  console.log('print ' + bar)
})

You can check that this is in fact what happens by making the callback do something visible and having your chained success handler accept an argument:
$.when(function(){alert("invoked!")}).then(function(result){
  result(); // only now is the alert displayed
})

Answer: I think this will explain it better:
var bar = 2;
$.when(function(){bar = 1}).then(function(f){
  f(); // The function is 'resolved' and passed to the `then` as the first argument.
       // The execution happens here, when we explicitly call it.
  console.log('print ' + bar)
})
// print 1


Is Banach space a correct context to study sequences and series?

Question: Recently, I have reviewed elementary analysis and I realized that every theorem in the text(Rudin-PMA) about series can be generalized to Banach space.
Here is an example.
Below is the theorem stated in the text:

Let $\sum a_n,  \sum b_n$ be convergent series in $\mathbb{C}$.
If $\sum a_n$ is absolutely convergent, then $\sum \sum_{k=0}^n a_k b_{n-k} = \sum a_n \sum b_n$.

I realized that this theorem can be generalized in the context of Banach space. That is,

Let $(V,\| \cdot \|)$ be a Banach space over $\mathbb{K}$
Let $\sum v_n$ be a convergent series in $V$
Let $\sum c_n$ be a convergent series in $\mathbb{K}$.
If one of those series is absolutely convergent, then $\sum \sum_{k=0}^n c_k v_{n-k} = \sum c_n \sum v_n$.

Just like the example, i found that ratio test, comparison test, Drichlet test etc. can be generalized into Banach space.
Is Banach space the right generalization to study series or is there another well-known context to study series?
Comment: There are a lot of ways to generalize series. You can go beyond countable sums and consider uncountable series (though they are not so different); you can consider series with values in different algebraic structures (e. g. Banach spaces, lattices etc); you can construct continuous series aka integrals. There is so much room for generalization, that I consider thi squestion as too broad.
Answer: You observe correctly that many results about series of real or complex numbers generalize to Banach spaces. Since $\mathbb R$ and $\mathbb C$ are examples of Banach spaces it should not be surprising that some (or even a lot) of what is taught about real or complex analysis generalizes to general Banach spaces. Moreover, in many cases the true nature of a particular result may be obscured by irrelevant peculiarities of the real or complex number systems and it thus becomes illuminated when considered as a result of Banach spaces. Having said that, to say that Banach spaces is the correct context to study series would be to miss the mark by quite a bit. Series is just one aspect of analysis. Banach spaces have an extremely rich geometry and series are more of a tool. An important tool. Banach spaces were not designed to study series. In fact, I'm not even sure what the theory of series might look like. What would the important questions in such a theory be? If you can formulate such an objective better, then a suitable context can be found.


Can't find "starts with" for Filter criteria In Views (indexed field for taxonomy)

Question: I created a view using indexed fields (search api) to list a taxonomy. I used the rest export checkbox so I have an api endpoint for my view. I am not able to find a filter criteria "starts with" for a field (indexed) that is a string. I don't understand why, the field is behaving like an integer and showing greater than, less than etc..
I am trying to use the hook_views_query_alter but I am getting an error from the line $query->where :
Error: Cannot access protected property Drupal\search_api\Plugin\views\query\SearchApiQuery::$where

In my view , I can see in the "Preview" section the query :
Index: books
Keys: NULL
Options: array (
    'search_api_view' => 'object (Drupal\\views\\ViewExecutable)',
    'search_api_base_path' => 'api/books',
  )

How do I add a filter criteria "starts with" for an indexed field which is a string? Thanks for your help
Comment: Apparently, this is a known and old issue since there was a Drupal 7 module specifically for that need. I had an index where I had to filter on author names and I did use the trick mentioned here: https://www.drupal.org/project/search_api/issues/3114833#comment-13528391. Perhaps it may help you as well.
Comment: @misterdidi thanks for your help! I will try that
Answer: See the full thread linked by @misterdidi here: https://www.drupal.org/project/search_api/issues/3114833#comment-13528391
This is the gist of it:

If it's "starts with" you are interested in, you could conceivably
emulate this using "greater than": field STARTS WITH 'abc' is pretty
much the same as field >= 'abc' AND field < 'abd' (unless the field is
multi-valued – then you'd have to use IS BETWEEN

If you're using Solr index fields, this field has to be of type string (not fulltext). The letter to be filtered on can be set on the url parameters: url.tld?initial=a for example.
You can implement this filter using hook_views_query_alter. Here "surname" is the machine name of the field as set in solr index fields.
function my_module_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->id() === 'my_view') {
    // Get filter value from URL.
    $initial = strtoupper(\Drupal::request()->query->get('initial'));
    if (!empty($initial)) {
      $query->addWhere(0, 'surname', $initial, '>=');
      $query->addWhere(0, 'surname', ++$initial, '<');
    }
  }
}


NodeJS: Como fazer um 'system("pause")' ou um 'ReadKey()'?

Question: Estou executando um código JS utilizando o Sublime Text, o cmd fecha automaticamente após a execução do código JS, logo não vejo os resultados então pensei em usar algo semelhante a função system("pause") ou a função getch() do C/C++ também existe a ReadKey() do C#.
Uns exemplos básicos de que procuro no JavaScript em outras linguagens:
C#

using System;

class Exe{
    static void Main(){
        // Apesar de Não estar no Padrão .NET o Código funciona Perfeitamente
        Console.Write("Olá Mundo!\nPressione Qualquer tecla para Encerrar a Execução do Programa...");
        Console.ReadKey();
    }
}

Python 3

print('Olá Mundo!\nPressione Enter para Encerrar a Execução do Programa...', end='')
sysPause = str(input(''))       # Precisa pressionar Enter, diferente dos Outros exemplos...

C

#include <stdio.h>
#include <stdlib.h>

int main(){
    printf("Olá Mundo!\n");
    system("pause");

    return 0;
}

C++

#include <iostream>
#include <conio.h>

using namespace std;
int main(){
    cout << "Olá Mundo!\nPressione Qualquer tecla para Encerrar a Execução do Programa...";
    getch();        // ou getche()

    return 0;
}

Answer: bom não sei se interpretei sua pergunta da forma correta mas vou tentar te ajudar.
No Javascript puro não se pensava em receber input pelo terminal (alias nem se pensava em executar o javascript pelo terminal);
Por isso você não encontra um método nativo como em outras linguagens, durante a evolução do javascript foi criado alguns módulos que trabalham coisas como o fluxo de input.

Talvez o mais notável deles seja o readline, que faz parte do próprio conjuto de módulos internos do node hoje em dia.
const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question('Qual sua idade? ', (answer) => {
  console.log(`Sua idade é ${answer}`);
  rl.close();
});

Observe o exemplo acima, fragmento retirado e adaptado da documentação do readline

Caso esteja usando o npm ou algum outro gerenciador de dependências, você pode optar por opções mais simples como:
readline-sync ( isso mesmo de síncrono )
const readline = require('readline-sync');

// resto do seu codigo.

readline.question('\npress any key!');

eu particularmente gosto bastante, por ser mais simples que o readline e não precisar encadear 'promises'.

Bom lembrando que existem outros modulos que trabalham em cima do input 'readline', uma pesquisa no npmjs com a keyword readline revela umas bibliotecas interessantes.
Resultados da Pesquisa

Basicamente é isso, só fiquei com uma dúvida você diz estar executando pelo sublime... não conheço muito a ferramenta.. mas dependendo como você executa o processo é invocado por segundo plano (assim não tem como você dar input)... de qualquer forma faça um teste no terminal / CMD se ficar em dúvidas...
espero ter ajudado, abraços.
Comment: ajudou mesmo cara valeu, no caso do sublime criei 2 build para o JS, um que apenas executa o comando "node", "$file_name" e executa o código JS no console do sublime (que não funciona para ler dados do teclado, mesmo no python, java porém exibe todos os prints definidos, então vejo os resultados, o que tu disse, não aceita os input do usuário), e o "start", "node", "$file_name" que executa o script no cmd do Windows, porém após execução do código o cmd é automaticamente fechado pelo SO.
Comment: mais uma vez obrigado


Power rules: $x ^ {(y^z)}$

Question: I know about $(x^y)^z$ = $x^{yz}$ but what about $x^{(y^z)}$? Are there any rules for this?
Let's consider the power of power rule: $(x^y)^z$ = $x^{yz}$:

$(2^3)^4$ = $8^4$ = 4096
$2^{3\times 4}$ = $2^{12}$ = 4096

But same can't work for $x^{(y^z)}$. Is there really no rule for this?
I'm not good with calculus so I didn't check those discussions really. If there is such a rule, please explain it.
Comment: There is no such rule.
Comment: Just FYI, $2$ is a misleading number in that sense. I'd recommend not using $2$ because it might lead you to believe things that are not true. Not only for exponentials.
Comment: @BrianBlumberg: Reminiscent of Richard Guy's Strong Law of Small Numbers.
Comment: @BrianBlumberg & BrianTung, power of power is a proven rule. Besides, I'm not a math person. The Strong Law is a nice read though.
Answer: It all depends on what you consider "a rule". There are many ways to calculate with things, from which many rules stem. One not unimportant rule would be
$$ x^{(y^z)} = (x^y)^{(y^{z-1})} = ((\ldots(x^y)^y)\ldots)^y $$
This will matter if you for example want to calculate such a power in some group. Suppose we have some element $x$ of some finite group (let's say an elliptic curve) and suitable integers $y,z$ and we want to calculate $x^{(y^z)}$. Then $y^z$ might be so large that it does not fit into memory. But instead of calculating $y^z$ we can turn the whole thing into taking $z$ times the $y$th power.

Power rules: $x ^ {(y^z)}$


Automatically authenticate using Linkedin's REST api

Question: I'm trying to build a win8 javascript app and automatically authenticate myself to show my linkedin info in the app.
However I've only been able to find info on how to authenticate a user manually (enter pass/user). I would like to make an automatic request as the "user" will always be me and send a request with my login token/info in it.
Is this possible?
Thanks for your help!
Answer: Yes, it is possible. Let's say you have a LinkdInAuth method that takes user and password as parameters. All you have to do is, on your default js:
ready: function (element, options) {
LinkdInAuth("yourUser","yourPass");
};

If you don't have that method, it is easily adaptable from the examples you find on the web.
Comment: -1 How does this answere the question? What do you mean with `default.js`, what is the `ready` function? Where is `LinkdInAuth` defined?
Comment: I'm not a fan of providing the whole code, but guidelines. Anyway, the `ready` function is defined in evey JS file related with an HTML page, inside the "namespace" definition.

The `LinkdInAuth` is pretty clear with "Lets say..." and "if you don't have that..."


Redirect certain HTTPS url with squid

Question: When passing all http and https traffic through squid3, is it possible if a user requests http://www.example.com I could redirect to a different url?
Would this only be possible for HTTP or HTTPS too?
Thanks
Answer: http://servercomputing.blogspot.com/2012/03/squid-proxy-redirect-url.html describes how to do it for HTTP.  HTTPs is probably not going to be possible unless you have squid set up to MITM all HTTPS sites, as you can't 30x a CONNECT request and squid is also unaware of the full request url. HTTPS hides that from the proxy.

Redirect certain HTTPS url with squid


Hide field label with hook_form_alter()

Question: In hook_form_alter(), I am trying to disable/hide a field label in a custom form. I know I could use $form['my_field']['#enableLabel'] = FALSE;.
Is there a way without unsetting the title?
Answer: Unsetting not really, hide yes : use #title_display and its get accessible to screenreader :
$form['my_field']['#title_display'] = 'invisible';

Comment: Just to mention that if you're using, say a *List (text)* field, you need to refer to the widget to hide the title: `$form['my_field']['widget']['#title_display'] = 'invisible';`
Comment: Every field has a different array structure to set invisible values. I didn't find #title_display with dropdown widget,
Answer: In my case I was trying to hide the label on quantity field provided by Drupal Commerce cart module and the following wasn't working:
$form['my_field']['#title_display'] = 'invisible';

I had to do this inside my hook_form_alter
$form['quantity']['widget'][0]['value']['#title_display'] = 'invisible';

Comment: Thank u. That's also works for me.
Answer: you can try:
function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

    $form['title']['widget']['0']['value']['#title_display']=none;

 }

Note: change "title" by your machine name field.
Comment: I do not understand how they put votes down if the code works well for me. Could you explain this to me? They should prohibit putting votes down if an explanation is not given.
Comment: Downvotes are anonymous by design, that's not going to change. You can avoid them quite easily, though. For example, you said _the code works well for me_, when any PHP developer will be able to tell you that's simply not true, just by glancing at your answer. First of all, it's invalid PHP. You haven't quoted a string. Second of all, it's invalid in the context of hiding a title in Drupal. The correct string to hide a title is "invisible", as you can see in the accepted answer above. It's always a good idea to check your work before trying to lay blame at the feet of others

Hide field label with hook_form_alter()


Can I bounce the ball off defender to resume my dribble?

Question: Let's say I pick up my dribble accidentally. Can I bounce the ball off the defenders leg and resume my dribble or is that an illegal move?
Answer: You aren't bouncing it off the opposition, you are making a pass.   As long as your pass doesn't infringe on sportsmanship it is perfectly legal.   You would be possibly called for a tech if you throw it at an opponents face or overly hard at the upper part of their body.   This is a judgment call by the referee.   I have never seen someone called for a foul when they throw it off an opponents legs or lower body or bouncing it off their back.
Comment: I see. Appreciate the response.


Thousand separator conditioned by next word with regex

Question: I'm trying to add a thousand separator (e.g ",") to large numbers in a given string conditioned by the next word.
This regex works for any number :
re.sub(r'\d{1,3}(?=(\d{3})+(?!\d))', r"\g<0>,", my_string)

But I only want to apply it for specific cases, this one is ok (euros/dollars) :
re.sub(r'\d{1,3}(?=(\d{3})+(?!\d))', r"\g<0>,", "1000 euros")
> "1,000 euros"

This one isn't :
re.sub(r'\d{1,3}(?=(\d{3})+(?!\d))', r"\g<0>,", "n° 1234 f")
> "n° 1,234 f"

How to properly add a condition ?
Thanks
Comment: Try adding a negative lookbehind `(?<!n° )\d{1,3}(?=(\d{3})+(?!\d))`  https://regex101.com/r/Ndzddy/1 See https://ideone.com/uX0HfN
Answer: You can include the group of words you want to apply the change to in the lookahead e.g.
\d{1,3}(?=(\d{3})+\s*(euros|dollars))

In python:
print(re.sub(r'\d{1,3}(?=(\d{3})+\s*(euros|dollars))', r"\g<0>,", "1000 euros"))
print(re.sub(r'\d{1,3}(?=(\d{3})+\s*(euros|dollars))', r"\g<0>,", "n° 1234 f"))
print(re.sub(r'\d{1,3}(?=(\d{3})+\s*(euros|dollars))', r"\g<0>,", "1234567 dollars"))

Output:
1,000 euros
n° 1234 f
1,234,567 dollars


How to find unhandled promises that only happen on Android?

Question: I'm developing an app that works just fine in iOS, but when we run it on Android we get warnings like the one I paste here and the execution halts:
Possible Unhandled Promise Rejection (id: 0):
Error: Callback was already called.
Error: Callback was already called.
    at blob:http://localhost:8081/3d1448ea-4625-468e-8c56-527626fd00b2:86472:36
    at tryCallOne (blob:http://localhost:8081/3d1448ea-4625-468e-8c56-527626fd00b2:16064:14)
    at blob:http://localhost:8081/3d1448ea-4625-468e-8c56-527626fd00b2:16165:17
    at blob:http://localhost:8081/3d1448ea-4625-468e-8c56-527626fd00b2:2892:21
    at _callTimer (blob:http://localhost:8081/3d1448ea-4625-468e-8c56-527626fd00b2:2781:9)
    at _callImmediatesPass (blob:http://localhost:8081/3d1448ea-4625-468e-8c56-527626fd00b2:2817:9)
    at Object.callImmediates (blob:http://localhost:8081/3d1448ea-4625-468e-8c56-527626fd00b2:3036:14)
    at MessageQueue.__callImmediates (blob:http://localhost:8081/3d1448ea-4625-468e-8c56-527626fd00b2:2370:18)
    at blob:http://localhost:8081/3d1448ea-4625-468e-8c56-527626fd00b2:2197:18
    at MessageQueue.__guardSafe (blob:http://localhost:8081/3d1448ea-4625-468e-8c56-527626fd00b2:2354:11)
    at MessageQueue.flushedQueue (blob:http://localhost:8081/3d1448ea-4625-468e-8c56-527626fd00b2:2196:14)
    at MessageQueue.callFunctionReturnFlushedQueue (blob:http://localhost:8081/3d1448ea-4625-468e-8c56-527626fd00b2:2165:21)
    at http://localhost:8081/debugger-ui/debuggerWorker.js:70:58
console.warn    @   blob:http://localhos…-527626fd00b2:54586
onUnhandled @   blob:http://localhos…-527626fd00b2:15912
onUnhandled @   blob:http://localhos…-527626fd00b2:16324
(anonymous) @   blob:http://localhos…6-527626fd00b2:2864
_callTimer  @   blob:http://localhos…6-527626fd00b2:2781
callTimers  @   blob:http://localhos…6-527626fd00b2:2988
__callFunction  @   blob:http://localhos…6-527626fd00b2:2392
(anonymous) @   blob:http://localhos…6-527626fd00b2:2162
__guardSafe @   blob:http://localhos…6-527626fd00b2:2354
callFunctionReturnFlushedQueue  @   blob:http://localhos…6-527626fd00b2:2161
(anonymous) @   debuggerWorker.js:70

The main problem is that as I don't get a line where the error is triggered I can not find where the error is. Also, I am not quite sure what should I fix, as the app works without this warnings in iOS.
I managed to isolate a line causing troubles, but I'm not sure what should I fix:
async connectChatEngine(chatEngine) {
      const response = await new Promise(resolve => chatEngine.on('$.ready', (data) => {
        resolve(data);
      }));
      console.log('ChatEngine ready to go!');
      return response;
    },

Answer: wrap await new Promise() in a try{} catch(e){}:
async connectChatEngine(chatEngine) {
  try{
    const response = await new Promise(resolve => chatEngine.on('$.ready', (data) => {
      resolve(data);
    }));
    console.log('ChatEngine ready to go!');
    return response;
  } catch(e){
    //handle failure here

    return false;
  }

},

Comment: thanks!

And how can I find out where the other promises are defined?


Question on the definition of the category of elements of a presheaf.

Question: I am new in Topos theory. I have actually just started learning. I am reading MacLane-Moerdijk's book, as it was suggested to me as the best introduction to the subject. Unfortunately I can not make sense of the following.
In section 5 of Chapter I, (page 41) they build what is needed to prove that in the presheaf category $[\mathcal{C}^{\textrm{op}},\mathbf{Set}]$, any object is the colimit of a diagram of representable objects. They define the category of elements of $P$ as follows: The objects are all pairs $(C,p)$ where $C$ is an object of $\mathcal{C}$ and $p$ is an element $p\in P(C)$. Its morphisms $(C',p')\to (C,p)$ are those morphisms $u:C'\to C$ of $\mathcal{C}$ for which $pu=p'$. I do not understand the morphisms of this category. $p$ is a set and $u$ a morphism in $\mathcal{C}$ so what does $pu$ mean? Do they mean $P(u)(p)=p'$ maybe?
Thanks for any help.
Answer: $u:C'\to C$ is a morphism, and $P$ is a presheaf, thus $P(u):P(C)\to P(C')$ is just a function between two sets, which you can apply to $p\in P(C)$ and get an element in $P(C')$, that is simply the element $P(u)(p)$, and the requirement is, as you write, just $P(u)(p)=p'$.
Notice that there is no guess work involved here and really there is no other way to interpret it. Also, notice that they introduce this shorthand notation a few pages earlier when they introduce presheaf categories.
Comment: Thanks. I guess I skipped the material until this section because it seemed like things I knew. But apparently there were some things I missed.
Answer: Yes, that's what they mean.
Writing $up$ or $u(p)$ would seem to make more intuitive sense, as this feels more like $u$ is "acting" on $p$ (and since we only have one gadget, $P$, for turning $u$ into a function on sets, your definition is really the only way), but since we are using contravariant functors, these definitions would cause composition to look backwards.
If if $u' : C'' \to C'$ is another morphism, then writing this action as $u(p)$ would give:
$$u'(u(p)) = (uu')(p)$$
If we use the definition from the text, however, we get the much more reasonable-looking:
$$p(uu') = (pu)u'$$
Comment: Ok thanks! Your explanation on the notation was much appreciated, makes much more sense now.


Entity Framework: Erro ao criar o banco

Question: estou utilizando o EF6 e estou com um problema ao utilizar o comando Update-Database -Verbose -Force. Da o seguinte erro:

PM> Update-Database -Verbose -Force
Using StartUp project 'PersonalTrainer.Presentation'.
Using NuGet project 'PersonalTrainer.Infra.Data'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'TesteDb' (DataSource: PC-RAPHAEL\SQLEXPRESS, Provider: System.Data.SqlClient, Origin: Configuration).
No pending explicit migrations.
Applying automatic migration: 201607061619096_AutomaticMigration.
IF object_id(N'[dbo].[FK_dbo.Cliente_dbo.Endereco_EnderecoId]', N'F') IS NOT NULL
    ALTER TABLE [dbo].[Cliente] DROP CONSTRAINT [FK_dbo.Cliente_dbo.Endereco_EnderecoId]
IF object_id(N'[dbo].[FK_dbo.Endereco_dbo.Cliente_Cliente_Id]', N'F') IS NOT NULL
    ALTER TABLE [dbo].[Endereco] DROP CONSTRAINT [FK_dbo.Endereco_dbo.Cliente_Cliente_Id]
IF object_id(N'[dbo].[FK_dbo.ClienteAgenda_dbo.Cliente_ClienteId]', N'F') IS NOT NULL
    ALTER TABLE [dbo].[ClienteAgenda] DROP CONSTRAINT [FK_dbo.ClienteAgenda_dbo.Cliente_ClienteId]
IF object_id(N'[dbo].[FK_dbo.Treino_dbo.Cliente_Cliente_Id]', N'F') IS NOT NULL
    ALTER TABLE [dbo].[Treino] DROP CONSTRAINT [FK_dbo.Treino_dbo.Cliente_Cliente_Id]
IF object_id(N'[dbo].[FK_dbo.AnamneseAtividadeFisica_dbo.Cliente_Cliente_Id]', N'F') IS NOT NULL
    ALTER TABLE [dbo].[AnamneseAtividadeFisica] DROP CONSTRAINT [FK_dbo.AnamneseAtividadeFisica_dbo.Cliente_Cliente_Id]
IF object_id(N'[dbo].[FK_dbo.AnamneseNutricional_dbo.Cliente_Cliente_Id]', N'F') IS NOT NULL
    ALTER TABLE [dbo].[AnamneseNutricional] DROP CONSTRAINT [FK_dbo.AnamneseNutricional_dbo.Cliente_Cliente_Id]
IF object_id(N'[dbo].[FK_dbo.AnamneseGeral_dbo.Cliente_Cliente_Id]', N'F') IS NOT NULL
    ALTER TABLE [dbo].[AnamneseGeral] DROP CONSTRAINT [FK_dbo.AnamneseGeral_dbo.Cliente_Cliente_Id]
IF object_id(N'[dbo].[FK_dbo.ComposicaoCorporal_dbo.Cliente_Cliente_Id]', N'F') IS NOT NULL
    ALTER TABLE [dbo].[ComposicaoCorporal] DROP CONSTRAINT [FK_dbo.ComposicaoCorporal_dbo.Cliente_Cliente_Id]
IF object_id(N'[dbo].[FK_dbo.Financeiro_dbo.Cliente_Cliente_Id]', N'F') IS NOT NULL
    ALTER TABLE [dbo].[Financeiro] DROP CONSTRAINT [FK_dbo.Financeiro_dbo.Cliente_Cliente_Id]
IF object_id(N'[dbo].[FK_dbo.Imc_dbo.Cliente_Cliente_Id]', N'F') IS NOT NULL
    ALTER TABLE [dbo].[Imc] DROP CONSTRAINT [FK_dbo.Imc_dbo.Cliente_Cliente_Id]
IF object_id(N'[dbo].[FK_dbo.Parq_dbo.Cliente_Cliente_Id]', N'F') IS NOT NULL
    ALTER TABLE [dbo].[Parq] DROP CONSTRAINT [FK_dbo.Parq_dbo.Cliente_Cliente_Id]
IF object_id(N'[dbo].[FK_dbo.Perimetria_dbo.Cliente_Cliente_Id]', N'F') IS NOT NULL
    ALTER TABLE [dbo].[Perimetria] DROP CONSTRAINT [FK_dbo.Perimetria_dbo.Cliente_Cliente_Id]
IF object_id(N'[dbo].[FK_dbo.RiscoCardiaco_dbo.Cliente_Cliente_Id]', N'F') IS NOT NULL
    ALTER TABLE [dbo].[RiscoCardiaco] DROP CONSTRAINT [FK_dbo.RiscoCardiaco_dbo.Cliente_Cliente_Id]
IF object_id(N'[dbo].[FK_dbo.Endereco_dbo.Cidade_Cidade_Id]', N'F') IS NOT NULL
    ALTER TABLE [dbo].[Endereco] DROP CONSTRAINT [FK_dbo.Endereco_dbo.Cidade_Cidade_Id]
IF object_id(N'[dbo].[FK_dbo.Cidade_dbo.Estado_Estado_Id]', N'F') IS NOT NULL
    ALTER TABLE [dbo].[Cidade] DROP CONSTRAINT [FK_dbo.Cidade_dbo.Estado_Estado_Id]
IF object_id(N'[dbo].[FK_dbo.ClienteAgenda_dbo.Agenda_AgendaId]', N'F') IS NOT NULL
    ALTER TABLE [dbo].[ClienteAgenda] DROP CONSTRAINT [FK_dbo.ClienteAgenda_dbo.Agenda_AgendaId]
IF object_id(N'[dbo].[FK_dbo.TreinoAgenda_dbo.Agenda_AgendaId]', N'F') IS NOT NULL
    ALTER TABLE [dbo].[TreinoAgenda] DROP CONSTRAINT [FK_dbo.TreinoAgenda_dbo.Agenda_AgendaId]
IF object_id(N'[dbo].[FK_dbo.TreinoAgenda_dbo.Treino_ClienteId]', N'F') IS NOT NULL
    ALTER TABLE [dbo].[TreinoAgenda] DROP CONSTRAINT [FK_dbo.TreinoAgenda_dbo.Treino_ClienteId]
IF object_id(N'[dbo].[FK_dbo.AnamneseNutricional_dbo.Nutricionista_Nutricionista_Id]', N'F') IS NOT NULL
    ALTER TABLE [dbo].[AnamneseNutricional] DROP CONSTRAINT [FK_dbo.AnamneseNutricional_dbo.Nutricionista_Nutricionista_Id]
IF EXISTS (SELECT name FROM sys.indexes WHERE name = N'IX_EnderecoId' AND object_id = object_id(N'[dbo].[Cliente]', N'U'))
    DROP INDEX [IX_EnderecoId] ON [dbo].[Cliente]
EXECUTE sp_rename @objname = N'dbo.AnamneseAtividadeFisica.Cliente_Id', @newname = N'Cliente_ClienteId', @objtype = N'COLUMN'
Caution: Changing any part of an object name could break scripts and stored procedures.
EXECUTE sp_rename @objname = N'dbo.AnamneseNutricional.Cliente_Id', @newname = N'Cliente_ClienteId', @objtype = N'COLUMN'
EXECUTE sp_rename @objname = N'dbo.AnamneseGeral.Cliente_Id', @newname = N'Cliente_ClienteId', @objtype = N'COLUMN'
EXECUTE sp_rename @objname = N'dbo.ComposicaoCorporal.Cliente_Id', @newname = N'Cliente_ClienteId', @objtype = N'COLUMN'
EXECUTE sp_rename @objname = N'dbo.Financeiro.Cliente_Id', @newname = N'Cliente_ClienteId', @objtype = N'COLUMN'
EXECUTE sp_rename @objname = N'dbo.Imc.Cliente_Id', @newname = N'Cliente_ClienteId', @objtype = N'COLUMN'
EXECUTE sp_rename @objname = N'dbo.Parq.Cliente_Id', @newname = N'Cliente_ClienteId', @objtype = N'COLUMN'
EXECUTE sp_rename @objname = N'dbo.Perimetria.Cliente_Id', @newname = N'Cliente_ClienteId', @objtype = N'COLUMN'
EXECUTE sp_rename @objname = N'dbo.RiscoCardiaco.Cliente_Id', @newname = N'Cliente_ClienteId', @objtype = N'COLUMN'
EXECUTE sp_rename @objname = N'dbo.Endereco.Cidade_Id', @newname = N'Cidade_CidadeId', @objtype = N'COLUMN'
EXECUTE sp_rename @objname = N'dbo.Endereco.Cliente_Id', @newname = N'Cliente_ClienteId', @objtype = N'COLUMN'
System.Data.SqlClient.SqlException (0x80131904): Either the parameter @objname is ambiguous or the claimed @objtype (COLUMN) is wrong.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c)
   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
   at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
   at System.Data.Entity.Migrations.DbMigrator.ExecuteSql(MigrationStatement migrationStatement, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ExecuteSql(MigrationStatement migrationStatement, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinTransaction(IEnumerable`1 migrationStatements, DbTransaction transaction, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinNewTransaction(IEnumerable`1 migrationStatements, DbConnection connection, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection)
   at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClass30.<ExecuteStatements>b__2e()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements, DbTransaction existingTransaction)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteStatements(IEnumerable`1 migrationStatements)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, VersionedModel targetModel, IEnumerable`1 operations, IEnumerable`1 systemOperations, Boolean downgrading, Boolean auto)
   at System.Data.Entity.Migrations.DbMigrator.AutoMigrate(String migrationId, VersionedModel sourceModel, VersionedModel targetModel, Boolean downgrading)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.AutoMigrate(String migrationId, VersionedModel sourceModel, VersionedModel targetModel, Boolean downgrading)
   at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
   at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
   at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClassc.<Update>b__b()
   at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
   at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
   at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run()
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
   at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force)
   at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0()
   at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
ClientConnectionId:d0dc8877-45a7-47c1-a868-1aca4f274208
Error Number:15248,State:1,Class:11
Either the parameter @objname is ambiguous or the claimed @objtype (COLUMN) is wrong.
PM>

Não sei qual objeto e nem qual coluna ele está se referindo.
Obrigado!
Comment: Pode por favor editar sua pergunta colocando o conteúdo da última Migration executada? Edite usando texto. Evite imagens.
Comment: Pronto, Cigano.
Answer: O problema está aqui:
EXECUTE sp_rename @objname = N'dbo.RiscoCardiaco.Cliente_Id', @newname = N'Cliente_ClienteId', @objtype = N'COLUMN'
...
EXECUTE sp_rename @objname = N'dbo.Endereco.Cliente_Id', @newname = N'Cliente_ClienteId', @objtype = N'COLUMN'

São dois objetos diferentes com o mesmo nome.
Você vai precisar ajustar manualmente sua Migration para que os @newname sejam diferentes entre eles.
Faça o ajuste e execute novamente. Ou ainda, derrubar o banco, apagar todas as Migrations e gerar uma nova Migration inicial pode ser uma opção.
Comment: Muito Obrigado Cigano! Estou aprendendo ainda EF. Aonde eu configuro isso? hehe
Na EntityTypeConfiguration?
Comment: Na própria Migration gerada. Se estiver usando Migrations automáticas, exclua o database.

Entity Framework: Erro ao criar o banco


Let $f(x)=30-2 x-x^{2}$ and $f_{n}$

Question:
Let $f(x)=30-2 x-x^{2}$ and $f_{n}(x)=\underbrace{f \circ f \circ \cdots \circ  f}_\text{$n$ times}$. Then, find the number of positive integral values of $x$ which satisfy $f_{2014}(x)$ < $f_{2013}(-x)$.

The answer is $2$.
My doubt is should the question have given $x^3$ instead of $x^2$? Else the given question is not monotonic? So how should one proceed.
Comment: I rather suspect that the less-than sign is the wrong way
Answer: As $f(x)=29-(x+1)^2$, we see that $f$ is strictly increasing on $(-\infty,-1]$.
Also,
$$f(x)-x=(4-x)(7+x)<0$$
and hence $$f(x)< x\qquad \text{for }x<-7.$$
Then $f_n$ maps $(-\infty,-7]$ strictly increasingly to itself.
Thus if $x$ is a positive integer with $$\tag1f(x)<-x\le -7,$$ then by applying $f_{2013}$ on both sides, we get $$\tag2f_{2014}(x)<f_{2013}(-x),$$ as desired.
More generally, if instead of $(1)$, we have
$$\tag3 f_{k+1}(x)<f_k(-x)\le -7$$
for some integer $0\le k\le 2013$, then by applying $f_{2013-k}$ to both sides, we also arrive at $(2)$.
As
$$f(x)+x=\frac{113}4-(x+\tfrac12)^2<0\qquad\text{for }x\ge5, $$
we see that $(1)$ ans therefore $(2)$ holds at least for all integers $x\ge 7$.
For $x=6$, we have $f(x)=-20$ and hence certainly $f_{2014}(x)<-7$, whereas $f(-x)=4$ and therefore (as $f(4)=4$) $f_{2013}(-x)=4$. So $(2)$ holds here.
For $x=5$, we have $f(x)=-7$ and hence $f_{2014}(x)=-7$, whereas $-5\mapsto 13\mapsto -167$ and hence $f_{2013}(-x)<-7$ and $(2)$ does not hold.
For $x=4$, we find $f(x)=4$ and hence $f_{2014}(x)=4$, whereas $f(-4)=20$, $f(20)=-412<-7$ and hence $f_{2013}(-x)<-7$ and $(2)$ does not hold.
For $x=3$, we find $3\mapsto 13\mapsto-167\mapsto -27527$, whereas $-3\mapsto 25\mapsto -647$.
For $x=2$, we find $2\mapsto20\mapsto-412\mapsto-168892$, whereas $-2\mapsto 28\mapsto -812$.
For $x=1$, we find $1\mapsto 25\mapsto -647\mapsto -417287$ whereas $-1\mapsto 29\mapsto -871$. Hence in these three cases, $(3)$ holds with $k=2$ and therefore $(2)$ holds.
Conclusion.
$$f_{2014}(x)<f_{2013}(-x)$$
holds for every $x\in\Bbb Z_{>0}\setminus\{4,5\}$.
Comment: f(x) = 31 - (x+1)^2 instead of 29-(x+1)^2 in first line.
Comment: There is calculation mistake in first line.
Comment: Does this help : $f-{n+1}(x)=31-(1+f_n(x))^2, f_0(x)=x$ ?
Comment: This will not solve.

Let $f(x)=30-2 x-x^{2}$ and $f_{n}$


Trying to replace 1 value with a conditional replaces the whole column

Question: Dim WB As Workbook
Set WB = ThisWorkbook

Dim lrow As Long
lrow = WB.Sheets("Updated Sheet").Range("B" & Rows.Count).End(xlUp).row

Dim myrange As Range
Set myrange = WB.Sheets("Updated Sheet").Range("R2:R" & lrow)
Dim row As Long
Dim col As Long

row = WB.Sheets("Updated Sheet").Range("AJ2").row
col = WB.Sheets("Updated Sheet").Range("AJ2").Column

For Each cl In myrange  'myrange is basically column "R"

If wb.Sheets("Updated Sheet").Cells(row, col) = "Paid" Then
cl.value = "Paid"
Else
End If
row = row + 1
Next cl

This is the code I currently have for an if statement where I want to replace the value in column R with the string "Paid" if the value in (row, col) is "Paid" as well.
However, the function currently replaces all values in column R even if there is only one "Paid" match, even though running through with f8/adding a msgbox line shows that the value in cell(row, col) is not "paid" for every line.
How should I go about fixing this?
Comment: Where does the `cl` fit into it as it's not used in your loop? Also `col` never changes. @JohnBustos - that's just another way of saying the same thing?
Comment: Try changing this: `.Cells(row, "R").` to this: `.Range("R" & row)`
Comment: you're right, I initially used cl to go through row R which was the range of myrange, but I tried an alternate method without taking out the cl part. I have updated the code, and added the rest of it as well. Thanks for the feedback!
Answer: Add .value to your cell reference. Currrently you are comparing a string with a cell object. That could lead to strange results.
If wb.Sheets("Updated Sheet").Cells(row, col).value = "Paid" Then

Comment: it didn't work in this case, but I'll definitely keep that in mind!
Comment: Hm, strange. Could you add a boolean variable to your code and set it equal to the expression in the IF clause. Then step through the code and check if it even comes back false in any of the lines.
Answer: Try Autofilter instead of looping through cells.
Please give this a try...
Sub David()
Dim WB As Workbook
Dim WS As Worksheet
Dim lrow As Long
Set WB = ThisWorkbook
Set WS = WB.Sheets("Updated Sheet")
WS.AutoFilterMode = False
lrow = WB.Sheets("Updated Sheet").Range("B" & Rows.Count).End(xlUp).row
With WS.Range("AJ1:AJ" & lrow)
    .AutoFilter field:=1, Criteria1:="Paid"
    If WS.Range("R1:R" & lrow).SpecialCells(xlCellTypeVisible).Cells.Count > 1 Then
        WS.Range("R2:R" & lrow).SpecialCells(xlCellTypeVisible).Value = "Paid"
    End If
    .AutoFilter
End With
End Sub

Comment: thanks, this worked! I've never used autofilter before, could you possibly run through your code for me?


Como navegar entre as abas do bootstrap através de um botão?

Question: Bom dia, colegas.
Como eu posso realizar a navegação entre as abas do bootstrap utilizando um botão javascript(preferencia)/jquery?
Possuo uma aba desenvolvida em bootstrap:

No final de cada aba possui um botão:

Como eu posso avançar entre as abas clicando neste botão?
Partes do código ->
Lista com os links para navegar nas abas:

  Dados da Empresa

  Cadastro de Clientes e Fornecedores

  Contas Financeiras

Exemplo de conteúdo dentro da aba:

<form action="#" method="POST">

Dados da Empresa

      CNPJ
      <input>
      Exemplo "01.234.567/8901-23"

Botão:
</form>
<button type="button" class="btn btn-light waves-effect">Prosseguir para Próxima Aba</button>

Answer: Use o gatilho .click() na aba seguinte da que está ativa. Você consegue selecionar a aba seguinte utilizando o id da div onde está o conteúdo da aba ativa, já que o atributo href do botão da aba está relacionado ao id da div onde está seu conteúdo:
<a href="#cadastro"...
             ↓
<div id="cadastro"...

Basta colocar uma classe no botão "Prosseguir para Próxima Aba" para usar como seletor:
<button type="button" class="btn btn-light waves-effect prox_aba">Prosseguir para Próxima Aba</button>
                                                            ↑

E usar o seguinte código:
$(function(){

   $(".prox_aba").on("click", function(){

      var id = $(this).closest(".tab-pane").attr("id"); // seleciona a div da aba ativa
                                                        // e pega o id

      $("ul.nav-tabs [href='#"+id+"']") // seleciona o link da aba ativa
      .closest("li")                    // seleciona a li da aba ativa
      .next()                           // seleciona a li seguinte
      .find("a")                        // busca o link
      .click();                         // dispara o click no link

   });

});

Exemplo: (execute em tela cheia)

$(function(){

   $(".prox_aba").on("click", function(){

      var id = $(this).closest(".tab-pane").attr("id");

      $("ul.nav-tabs [href='#"+id+"']")
      .closest("li")
      .next()
      .find("a")
      .click();

   });

});

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">

        Dados da Empresa

        Cadastro de Clientes e Fornecedores

        Contas Financeiras

   <form action="#" method="POST">

Dados da Empresa

         CNPJ
         <input>
         Exemplo "01.234.567/8901-23"

   </form>
   <button type="button" class="btn btn-light waves-effect prox_aba">Prosseguir para Próxima Aba</button>

   <form action="#" method="POST">

Cadastro de Clientes e Fornecedores

         CNPJ
         <input>
         Exemplo "01.234.567/8901-23"

   </form>
   <button type="button" class="btn btn-light waves-effect prox_aba">Prosseguir para Próxima Aba</button>

   <form action="#" method="POST">

Contas Financeiras

         CNPJ
         <input>
         Exemplo "01.234.567/8901-23"

   </form>


VIF calculation in regression

Question: I want to use VIF to check the multicollinearity between some ordinal variables and continuous variables. When I put one variable as dependent and the other as independent, the regression gives one VIF value, and when I exchange these two, then the VIF is different. And once the VIF value is higher than 3, and the other time it is lesser than 3.
Then, how I do make a decision to keep the variable or not, and which one should I keep? Ultimately, I am going to use these variables in a logistic regression. How important it is to see multicollinearity in logistic regression?
Answer: It is important to address multicollinearity within all the explanatory variables, as there can be linear correlation between a group of variables (three or more) but none among all their possible pairs.
The threshold for discarding explanatory variables with the Variance Inflation Factor is subjective. Here is a recommendation from The Pennsylvania State University (2014):

VIF is a measure of how much the variance of the estimated regression coefficient $b_k$ is "inflated" by the existence of correlation among the predictor variables in the model. A VIF of 1 means that there is no correlation among the $k_{th}$ predictor and the remaining predictor variables, and hence the variance of $b_k$ is not inflated at all. The general rule of thumb is that VIFs exceeding 4 warrant further investigation, while VIFs exceeding 10 are signs of serious multicollinearity requiring correction.

Remember always sticking to the hypothesis previously formulated to investigate the relationship between the variables. Keep the predictors which make more sense in explaining the response variable.
Multicollinearity in logistic regression is equally important as other types of regression. See: Logistic Regression - Multicollinearity Concerns/Pitfalls.

VIF calculation in regression


Weighing correlation by sample size

Question: I'm a scholar in the humanities trying to not be a complete idiot about statistics. I have a problem relevant to some philological articles I'm writing. To avoid introducing the obscure technicalities of my field I'll recast this as a simple fictional "archaeology" problem.
In the Valley of Witches there are 29 tombs. Each contains an assortment of coins and gemstones. Some of the coins are gold coins and some of the gemstones are saphires.
There is a hypothesis in the field which predicts that the proportion of gold coins to total coins should correlate positively with the proportion of sapphires to total gemstones. Let's call this Angmar's prediction.
I would like to test Angmar's prediction for the dataset below. If I run a straightforward Pearson correlation on all 29 data points I get a correlation very close to zero (0.01). This looks bad for Angmar - but is it the whole story?
Some of the data points are clearly better than others. Tomb 1 has 46 gems and 990 coins. That seems to be a much more solid data point than Tomb 29, which has only 4 gems and 80 coins. In the dataset below I've arranged the tombs in order of "size", defined as the geometric mean of total gemstones and total coins. Now, if we only look at the 13 largest tombs we get a correlation of 0.67. This looks good for Angmar after all. If we include 25 tombs, all but the 4 smallest ones, we still have a correlation of 0.37.

It looks reasonable to look only at large tombs or exclude small ones but there is no non-arbitrary way to decide where to put the cut-off. And it seems wrong to throw any data away.
My question: Is there a way to make use of all the data and calculate some sort of properly weighted correlation?
My attempted answer: There are functions for weighted correlation out there (I've used this) - but what should I weigh by? If I weigh by total gems I get 0.28. If I weigh by total coins I get 0.16. Either seems reasonable but ideally I would make use of both. If I weigh by the product of total gems and total coins I get a correlation of 0.47. Is this a legitimate method?
To be clear - it's not that I want to gin up as large a correlation as possible - I have publishable data any which way. I just want to get this right.
Edit 1: There is no particular reason to think that the relationship should be linear. A rank correlation solution might also make sense.
Edit 2: We've settled on a rank correlation but the weighting formula is still unclear to me. Summing the sample sizes gives an intuitively wrong result in the case where one sample size is much larger than the other. But the geometric mean of the sample sizes also gives an intuitively wrong result for big numbers. A hundred zillion coins should not weigh a hundred times as heavily as a zillion coins. What might intuitively work in a case like that would be to use the sum of the sizes of the confidence interval (assuming a binomial distribution). Or maybe simply the reciprocal of the sums of the reciprocals - like with parellel resistors. But that's something I just pulled out of my behind. I don't feel on solid ground yet and additional answers would be very much appreciated.
The dataset is as follows. It is based on real data:
$$\begin{array}{c|c|c|c|c|c|c} \text{Tomb number} & \text{Sapphires} & \text{Total gems} & \text{Sapphire ratio} & \text{Gold coins} & \text{Total coins} & \text{Gold ratio}\\ \hline
\text{Tomb 1} & 44 & 46 & 0.96 & 33 & 990 & 0.03\\
\text{Tomb 2} & 35 & 41 & 0.85 & 3 & 761 & 0.00\\
\text{Tomb 3} & 21 & 25 & 0.84 & 13 & 558 & 0.02\\
\text{Tomb 4} & 23 & 25 & 0.92 & 12 & 368 & 0.03\\
\text{Tomb 5} & 14 & 18 & 0.78 & 2 & 426 & 0.00\\
\text{Tomb 6} & 13 & 17 & 0.76 & 6 & 350 & 0.02\\
\text{Tomb 7} & 12 & 14 & 0.86 & 3 & 418 & 0.01\\
\text{Tomb 8} & 8 & 13 & 0.62 & 3 & 318 & 0.01\\
\text{Tomb 9} & 11 & 12 & 0.92 & 4 & 269 & 0.01\\
\text{Tomb 10} & 6 & 6 & 1.00 & 17 & 503 & 0.03\\
\text{Tomb 11} & 9 & 10 & 0.90 & 8 & 286 & 0.03\\
\text{Tomb 12} & 4 & 6 & 0.67 & 3 & 454 & 0.01\\
\text{Tomb 13} & 9 & 10 & 0.90 & 10 & 255 & 0.04\\
\text{Tomb 14} & 7 & 10 & 0.70 & 12 & 250 & 0.05\\
\text{Tomb 15} & 7 & 7 & 1.00 & 6 & 351 & 0.02\\
\text{Tomb 16} & 9 & 9 & 1.00 & 8 & 218 & 0.04\\
\text{Tomb 17} & 6 & 7 & 0.86 & 3 & 251 & 0.01\\
\text{Tomb 18} & 7 & 7 & 1.00 & 5 & 246 & 0.02\\
\text{Tomb 19} & 5 & 5 & 1.00 & 7 & 304 & 0.02\\
\text{Tomb 20} & 4 & 4 & 1.00 & 10 & 336 & 0.03\\
\text{Tomb 21} & 4 & 4 & 1.00 & 15 & 274 & 0.05\\
\text{Tomb 22} & 6 & 6 & 1.00 & 3 & 175 & 0.02\\
\text{Tomb 23} & 5 & 6 & 0.83 & 5 & 174 & 0.03\\
\text{Tomb 24} & 4 & 4 & 1.00 & 4 & 174 & 0.02\\
\text{Tomb 25} & 4 & 4 & 1.00 & 5 & 150 & 0.03\\
\text{Tomb 26} & 1 & 2 & 0.50 & 15 & 218 & 0.07\\
\text{Tomb 27} & 2 & 2 & 1.00 & 8 & 201 & 0.04\\
\text{Tomb 28} & 1 & 3 & 0.33 & 2 & 108 & 0.02\\
\text{Tomb 29} & 4 & 4 & 1.00 & 1 & 80 & 0.01\end{array}$$
Comment: It would be nice to find something other than size that distinguishes between very small and large. Then one could have a revised hypothesis named after oneself, that there is positive correlation in rich people tombs, and negative correlation in loser tombs.
Comment: Hm, I don't know whether standard dev is the best. I'm toying with the idea to use the likelihood of finding "such a result" in "such a big sample" (where "sample" is the number of coins or gems in a tomb). Then if there are only 2 gems there, then by the binomial distribution we had p=0.25 that 2 of the 2 gems are saphire. So the null-hypothesis for each sample/tomb is, that the number of saphires is just the mean category of the binomially expected frequency etc. Perhaps then even the stderror is a useful measure/interval...
Comment: I see what you mean! I don't think that would pan out in my case but it was worth explicitly thinking about - which I hadn't before. Thank you.
Comment: The "two populations" hypothesis is a popular one in many places, including medical research.
Comment: I am a complete newbie in statistics, but does weighting by the standard deviation have any sense? Because the error brought by the limit of each set is measure by this deviation, so...
Comment: I too have a vague feeling that the standard deviation might enter into this - but I'm not sure how. Could you elaborate on your idea?
Answer: To correctly answer this interesting question, there are three issues to be considered. The first one refers to the opportunity of weighting. The problem of exploring the relationship between two variables by taking into account a third weighting variable is common in statistical research. For example, we could be interested in assessing the correlation between age and the value of a certain blood parameter in a sample of subjects where the blood parameter value in some of them represents the average of multiple measurements. In this case we could choose to give more importance to values representing averages than those representing single measurements, under the hypothesis that they are less affected by within-subject variability and can be considered more "reliable". The size or number of observations is not the only possible weighting variable: we can decide to weight, say, according to time of observation (e.g., if we want to give more importance to recent observations than old ones because are more relevant for the present situation), to the standard deviation of values (as correctly noted in the comments) in samples with aggregated data, to the order of preferences when one of the variables is a rank, and so on.
In the context described by the OP, considering the size discrepancies, a weighted analysis is fully appropriate. The utility of this choice is also highlighted by the type of variables considered in this case (proportions),  since their precision is well known to be highly sensitive to small sample sizes. This concept is a classical problem in power calculations for studies on proportions, and we can better visualize it by considering that the
sample size required to estimate a proportion with a specified level of confidence and precision is given by the formula $\displaystyle N=\frac{Z_\alpha^2 p(1-p)}{e^2}$, where $Z_\alpha$ is the value from the standard normal distribution corresponding to our predefined $\alpha$ error (e.g., Z=1.96 if we want a 95% CI), $p$ is the expected "true" proportion in the underlying population, and $e$ is the desired level of precision. As a result of this inverse relation, small sample sizes can be associated with very high levels of imprecision. For example, let us consider to get a sample from a population where the true underlying proportion is $50\%$, and to observe a proportion $p$. The precision of this observed proportion for an $\alpha<0.05$ (i.e. the range over which $p$ is distributed 95% of times if I take infinite samples of that size), is $\pm5\%$ for a sample of $385$ observations, but falls to $\pm10\%$ for a sample of $97$ observations and to $\pm20\%$ (clearly unacceptable) for a sample of $25$ observations. These considerations point out that caution is required when managing proportions given by small sample sizes. In our case, this problem is more evident for gems, since half of tombs has a size $<10$. In these conditions, weighting is clearly recommended.
The second issue is that we have to choose the method of weighting. As stated above, weighting can be performed according to different variables, the choice of which depends on several factors, including purpose of the study, underlying distribution, type of data aggregation, and so on. In our case, we are interested in finding a weighting variable that impacts on the reliability of observed proportions. According to the considerations above, and taking into account the marked impact of sample size on proportion precision, the size of each observation (in our case, the number of gems and that of coins in each tomb) is an appropriate choice. Weighting by standard deviation, which is correctly performed in many cases of aggregated data, is less appropriate in this  context, since here we have no aggregated data (also, even if we had aggregated data, we could not assume that the distribution of observed data in the tombs is normal). To quantify the size of each tomb, the geometric mean of the number of gems and coins  is the optimal choice and has to be preferred to the arithmetic mean. In fact, the geometric mean takes better into account that, to be reliable, an observation must have a precise proportion of both gems and coins, and that therefore a balance between the two elements is advantageous for the purpose of our analysis. To better explain this: if, for instance, we have a tomb $i$ with $2$ gems and $198$ coins, and another tomb $j$ with $100$ gems and $100$ coins, the overall reliability of the observation $x_i,y_i$ (where $x$ and $y$ are the proportions of gems and coins, respectively) is probably inferior to that of the observation $x_j,y_j$. The geometric mean captures this information and gives a size of $19.9$ in the first case and of $100$ in the second case. The arithmetic mean does not capture this information and gives a size of $100$ in both cases.
The third issue is that we have to identify the most appropriate method to assess correlation. In this regard, the most important choice to make is between parametric and nonparametric measures. Several assumptions must be satisfied before applying the classical Pearson correlation, which is the typical parametric test: 1) variables must be continuous; 2) variables must be approximately normally distributed; 3) outliers (observations that lie at an abnormal distance from the other data) have to be minimized or removed; 4) data have to be homoscedastic (i.e., the variances along the line of fit have to be approximately similar as we move along the line; 5) a linear relationship must be plausible (this is usually checked by visual estimation of scatterplots). We can use specific tests to check these assumptions, but looking at the data shown in the OP it seems highly unlikely that all them are adequately satisfied. This suggests that nonparametric measures of correlation have to be preferred in this case.
The most used types of nonparametric correlation coefficients are Spearman's R, Kendall's Tau, and Goodman-Kruskal's Gamma. All these methods overcome the problems related to the assumptions of parametric tests, since they only require that individual observations can be ranked into two ordered series. Spearman's R can be interpreted as the Pearson  correlation coefficient computed from ranks, so that it provides a similar message in terms of variability accounted for. Kendall's Tau is equivalent to  Spearman R in terms of statistical power, but
its results have a different interpretation since it represents a probability: in particular, it is the difference between the probability that, given any pair of observations ($x_i, y_i$ and $x_j, y_j$), the ranks of the two variables are in the same order (i.e., $x_i>x_j$ and $y_i>y_j$, or $x_i<x_j$ and $y_i<y_j$). Goodman-Kruskal's Gamma is basically equal to Kendall's tau, with the only difference that it takes into account ties (observations with identical value), and is preferable when data show several cases of equal values.
In summary, an optimal choice for this analysis could be a nonparametric test (e.g. the Spearman's R) weighted for size, where size is calculated as the geometric mean of the number of gems and that of coins. I have not tested whether this analysis, applied to the tomb data, yields a significant correlation. However, this analysis surely represents a very "robust" approach.
Comment: Consider that the Spearman's R can be used even in the presence of ties. It simply assign to them a rank equal to the average of their positions in the ascending order of the values. If you want to try an alternative test that accounts for ties in a more robust way, you can try the so-called Kendall "tau-b" or "tau-c", or the Goodman-Kruskal's Gamma (all designed to better manage ties).
Comment: For weighting, it is necessary to take into account both gems and coins. The product can be an alternative to the geometric mean: although "formally" less correct, it could be used if we predefine to have a "stronger" weighting that differentiates the "importance" of observations in a more evident fashion.
Comment: As regards the way of weighting: I understand your idea of a procedure where weights become similar at high sizes. However, unfortunately in this case we cannot use variability measures as weighting variables, since we have no aggregated data. In particular, how could we calculate any variability measure within a tomb considering that we have only a single proportion $x_i$ and $y_i$ in each tomb?
Comment: Thank you! You seem to confirm a large part of what I was thinking, which is great. Yes, nonparametric measures are probably the way to go. I've used Spearman's rho in the past and I've tried to apply that here but I was concerned and confused about the ties. There is, unfortunately, one tie in the coins (tombs 6 and 22 have the exact same ratio) and there are a bunch of ties in the gems. Is this not a concern? Or would only a simultaneous tie in coins and gems be a problem?
Comment: On the weighting front: Weighting by the geometric mean seems to yield a 'weaker' correction than weighting by gems alone, since gems are scarcer and cause (I think) more error. But ideally coins would be taken into account as well. That's why I was wondering if the product (rather than the geometric mean) might be the way to go. Then again, total gems and total coins are highly correlated so maybe that would kind of be correcting for the same thing twice. But, then again, we do have a similar source of error twice so maybe that's fine.
Comment: On the standard deviation front: If we imagine that we had very many coins in each tomb the reliability of the coin ratio would no longer be a practical issue. And then we would no longer really care whether a particular tomb had one zillion coins or a hundred zillion coins. At that point a hundredfold difference in coin amount should, if my intuition is correct, cause only a trivial difference in weighting. But the method we are discussing would fail to take this into account. So maybe it needs some refinement to take variance into account?
Comment: Yes, I had a little brainfart there. It's not a question of standard deviation. I don't know what it is a question of.
Comment: Here's a rough cut at an idea which gets at where I was going with this: Assuming a binomial distribution we could [calculate](http://www.danielsoper.com/statcalc3/calc.aspx?id=85) the size of the confidence interval for the coins in a given tomb and the gems in a given tomb. We could then use the _sum_ of these intervals as the weighting for that tomb. This works well in the limit where there are zillions of coins because then the coin confidence intervals will be dwarfed by the gem confidence intervals.
Comment: The problem with such approach (that could be interesting, albeit unusual) is that we do not know the underlying probability, strictly necessary to "build" the binomial distribution and to estimate the precision interval of the observed proportion.
Comment: In my opinion, the idea of creating a measure so that weights become similar at high sizes is not so important in this specific case, considering the real numbers of gems and coins in this problem. The numbers are quite small, and then is more important to worry about the confounding effect of small sizes, rather than the need of flattening weights at large sizes. I believe that the choice of size as a weighting variable is the most convenient, simple, and formally correct.
Comment: I appreciate your continued engagement. I would like to credit you in my paper. If that's all right with you, what name would you like me to use? On the geometric mean ("size") as a weighting variable: Yes, maybe that's the way to go and maybe it's a waste of time to try to dream up something more sophisticated. But note that calling the geometric mean the "size" was just something I came up with on the spot. It's a bit surprising to me if I happened to hit the nail on the head there.
Comment: Thank you, Haukur. It is not necessary to credit me since my contribution has been small. However, if you want, you can find details on my MSE account page. I wish you all the best for your paper.

Weighing correlation by sample size


filtro customizado range de numeros datatables

Question: estou tentando fazer um filtro customizado selecionando uma range de números com o datatables e só funciona uma vez. Tentei de várias maneiras e nenhuma funcionou e pesquisando nada encontrei, por isso venho aqui pedir a ajuda de vocês.
<code><select id="filtro1">
            <option value="">Selecione</option>
            <option value="1-10">1-10</option>
            <option value="11-16">11-16</option>
            </select>
</code>
aqui está o jquery
<code>$(document).ready(function() {
    $('#filtro1').on("change", function(){
        var valor = $(this).val();
        var arr = valor.split('-');

            $.fn.dataTable.ext.search.push(
    function( settings, data, dataIndex ) {
        var min = parseInt( arr[0], 7 );
        var max = parseInt( arr[1], 7 );
        var age = parseFloat( data[7] ) || 0; // use data for the age column

        if ( ( isNaN( min ) && isNaN( max ) ) ||
             ( isNaN( min ) && age <= max ) ||
             ( min <= age   && isNaN( max ) ) ||
             ( min <= age   && age <= max ) )
        {
            return true;
        }
        return false;
    }
);
table.draw();

    });

var table = $('#classificacao').DataTable({
        "lengthMenu": [ [10, 25, 50, 100, -1], [10, 25, 50, 100, "Todos"] ],
        "processing": true,
        "oLanguage": {
            "sUrl": "../busca/pt-br.txt"
        },
        "columnDefs": [
            {
                "targets": [ 7 ],
                "visible": false
            }
        ]
    });
});
</code>
tirei como base este exemplo que usa input type text
https://datatables.net/examples/plug-ins/range_filtering.html
desde já agradeço qualquer ajuda.
Answer: venho aqui com o problema resolvido e para possivelmente ajudar outras pessoas.
<code>        $('#filtro1').on("change", function(){
        var valor = $(this).val();
        var arr = valor.split('-');

        if ( $.fn.dataTable.ext.search.length>0 ) {
    $.fn.dataTable.ext.search.pop(); //<--here
  }

            $.fn.dataTable.ext.search.push(
    function( settings, data, dataIndex ) {
        var min = parseInt( arr[0], 7 );
        var max = parseInt( arr[1], 7 );
        var age = parseFloat( data[7] ) || 0; // use data for the age column

        if ( ( isNaN( min ) && isNaN( max ) ) ||
             ( isNaN( min ) && age <= max ) ||
             ( min <= age   && isNaN( max ) ) ||
             ( min <= age   && age <= max ) )
        {
            return true;
        }
        return false;
    }
);
table.draw();

    });
</code>


Cosine sequence with phase as random variable

Question: I have a question on how to derive the (marginal) pdf for the $k$-th random variable $X_k$, where $X_k = \cos(0.2\pi k + \theta)$, and $\theta$ is a random variable uniformly distributed over the interval $[0, 2\pi)$. Could anyone show me how to derive this?
Comment: See https://stats.stackexchange.com/questions/239588/derivation-of-change-of-variables-of-a-probability-density-function
Answer: I am not sure $k$ matters here
Indeed, running (Python):
<code>import numpy as np
import numpy.random as npr
k_arr=[1, 3, 5, 6, 10, 100]; theta=2*np.pi*npr.rand(50000); V=-0.2
[np.mean(np.cos(0.2*k+theta)<V) for k in k_arr]
</code>
Gives same results for different $k$. So if we would construct CDF for your variable:
$$
F\left(X_k\right)=Prob\left[\cos\left(\dots\right)<X_k\right]=\frac{1}{2\pi}\int_0^{2\pi}d\theta\,I_{X_k}\left(\cos\left(\alpha k+\theta\right)\right)
$$
where $I_X\left(u\right)=1$ for $u<X$ and 0 otherwise, we would get the same result irrespective of $k$. Indeed one can see that this would be the case since one can change the integration variable and remove $k$. So we can focus on
$$
F\left(X\right)=\frac{1}{2\pi}\int_0^{2\pi}d\theta\,I_{X}\left(\cos\left(\theta\right)\right)
$$
Next we can use the fact that for this range of $\theta$ every value of $\cos$ is repeated twice, so we can reduce the range of integration:
$$
F\left(X\right)=\frac{1}{2\pi}\int_{0}^{2\pi}d\theta\dots=\frac{1}{\pi}\int_{0}^{\pi}d\theta\,I_{X}\left(\cos\left(\theta\right)\right)
$$
Now we could use the fact that in the range $\theta=0\dots \pi$ $\cos$ is decreasing with $\theta$ so:
$$
F\left(X\right)=\frac{1}{\pi}\int_{\arccos\left(X\right)}^{\pi}d\theta\,1=1-\frac{\arccos\left(X\right)}{\pi}
$$
And to get the pdf you need to differentiate, so:
$$
f\left(X\right)=\frac{dF}{dX}=\dots
$$


Proving $4x^2$ is not One-To-One

Question: Give that $f:\mathbb R \rightarrow \mathbb R$, $f(x) = 4x^2$. Disprove that this is one-to-one.
I am trying to do this without a graph, and by writing a proof. We are told that for a function to be one-to-one it must follow this format: $\forall a,b \in A[(f(b) = f(a)) \rightarrow (b=a)$. So I tried the following:
$$f(b)=f(a) \\ 4b^2 = 4a^2 \\ b^2 = a^2 \\ \pm b = \pm a$$
Now I have the math, but I don't know what this says at the last line. I know squared functions are not one-to-one because the domain maps to more than one codomain, and it fail the vertical line test because of this. How do I say this with the approach of my proof? Like I said before, I don't understand the last line of this.
Answer: Just take $x=1$ and $x=-1$.
Can you end it now?
Comment: @ E__  We need $x_1\neq x_2\Rightarrow f(x_1)\neq f(x_2),$ but it's wrong. Also, by your reasoning you took $f(a)=f(b)$, but you did not get $a=b$.
Comment: @E__ Yes, of course.
Comment: @E__ Not anything else like $a=-b$.
Comment: Now this is clear! Thank you again!
Comment: I see. So my last line could be saying something like, "b maps to a plus or minus a?"
Comment: Okay, I think I am understanding this. So for this to be one-to-one it need to be $a = b$ not anything else, like $a \ne b$?
Comment: In my previous comment I meant to say, "It should say $a = b$, not anything else like $\pm b = \pm a?$ My mistake!

Proving $4x^2$ is not One-To-One