How can I fix the "The specified database connection is not defined: default" error?

Question: I installed PHP 7.4.21, then Drupal 9.2.1, and Drush 10.5.0 with Composer as well.
Running Drush without arguments, I get the list of all the available commands.
Running drush cr gives me the following error.

The specified database connection is not defined: default

drush cr --root=/home/ip/d916/web gives the same error.
The output of drush cr -vvv is the following.

Exception trace
at /home/ip/d916/web/core/lib/Drupal/Core/Database/Database.php:371
Drupal\Core\Database\Database::openConnection() at /home/ip/d916/web/core/lib/Drupal/Core/Database/Database.php:169
Drupal\Core\Database\Database::getConnection() at n/a:n/a
call_user_func_array() at /home/ip/d916/web/core/lib/Drupal/Component/DependencyInjection/Container.php:258
Drupal\Component\DependencyInjection\Container->createService() at /home/ip/d916/web/core/lib/Drupal/Component/DependencyInjection/Container.php:176
Drupal\Component\DependencyInjection\Container->get() at /home/ip/d916/web/core/lib/Drupal/Component/DependencyInjection/Container.php:437
Drupal\Component\DependencyInjection\Container->resolveServicesAndParameters() at /home/ip/d916/web/core/lib/Drupal/Component/DependencyInjection/Container.php:240
Drupal\Component\DependencyInjection\Container->createService() at /home/ip/d916/web/core/lib/Drupal/Component/DependencyInjection/Container.php:176
Drupal\Component\DependencyInjection\Container->get() at /home/ip/d916/web/core/lib/Drupal/Core/Cache/ChainedFastBackendFactory.php:89
Drupal\Core\Cache\ChainedFastBackendFactory->get() at /home/ip/d916/web/core/lib/Drupal/Core/Cache/CacheFactory.php:83
Drupal\Core\Cache\CacheFactory->get() at n/a:n/a
call_user_func_array() at /home/ip/d916/web/core/lib/Drupal/Component/DependencyInjection/Container.php:258
Drupal\Component\DependencyInjection\Container->createService() at /home/ip/d916/web/core/lib/Drupal/Component/DependencyInjection/Container.php:176
Drupal\Component\DependencyInjection\Container->get() at /home/ip/d916/web/core/lib/Drupal/Component/DependencyInjection/Container.php:437
Drupal\Component\DependencyInjection\Container->resolveServicesAndParameters() at /home/ip/d916/web/core/lib/Drupal/Component/DependencyInjection/Container.php:240
Drupal\Component\DependencyInjection\Container->createService() at /home/ip/d916/web/core/lib/Drupal/Component/DependencyInjection/Container.php:176
Drupal\Component\DependencyInjection\Container->get() at /home/ip/d916/web/core/lib/Drupal/Core/DrupalKernel.php:586
Drupal\Core\DrupalKernel->preHandle() at /home/ip/d916/web/core/includes/utility.inc:35
drupal_rebuild() at /home/ip/d916/vendor/drush/drush/src/Commands/core/CacheCommands.php:234
Drush\Commands\core\CacheCommands->rebuild() at n/a:n/a
call_user_func_array() at /home/ip/d916/vendor/consolidation/annotated-command/src/CommandProcessor.php:257
Consolidation\AnnotatedCommand\CommandProcessor->runCommandCallback() at /home/ip/d916/vendor/consolidation/annotated-command/src/CommandProcessor.php:212
Consolidation\AnnotatedCommand\CommandProcessor->validateRunAndAlter() at /home/ip/d916/vendor/consolidation/annotated-command/src/CommandProcessor.php:176
Consolidation\AnnotatedCommand\CommandProcessor->process() at /home/ip/d916/vendor/consolidation/annotated-command/src/AnnotatedCommand.php:311
Consolidation\AnnotatedCommand\AnnotatedCommand->execute() at /home/ip/d916/vendor/symfony/console/Command/Command.php:255
Symfony\Component\Console\Command\Command->run() at /home/ip/d916/vendor/symfony/console/Application.php:1027
Symfony\Component\Console\Application->doRunCommand() at /home/ip/d916/vendor/symfony/console/Application.php:273
Symfony\Component\Console\Application->doRun() at /home/ip/d916/vendor/symfony/console/Application.php:149
Symfony\Component\Console\Application->run() at /home/ip/d916/vendor/drush/drush/src/Runtime/Runtime.php:118
Drush\Runtime\Runtime->doRun() at /home/ip/d916/vendor/drush/drush/src/Runtime/Runtime.php:48
Drush\Runtime\Runtime->run() at /home/ip/d916/vendor/drush/drush/drush.php:72
require() at /home/ip/d916/vendor/drush/drush/drush:4

Composer works without any mistake. Drupal work fine too. Unfortunately I can't work without Drush 10.
How can I fix the The specified database connection is not defined: default error?
Comment: Can you share database details from your settings.php. It seems you haven't configured it properly
Comment: As side note: The previous comments are asking to give that information in the question, not in answers. Answers aren't used to give more information to answer the question. Stack Exchange sites aren't forums, but Q&A sites: A user asks a question that other users answer.
Comment: Please share the output of `drush status`.
Answer: You say that Drupal works fine. Do you really mean that your Drupal 9.2.1 website is fully functional without a database connection? That is surprising!
You can start by connecting to this environment via ssh and testing a connection to the database using the command-line mysql utility and the database authentication credentials stored in your settings.php file.
If you get a successful connection, run some diagnostic commands like USE `drupal`; (replacing drupal with the DB name specified in your settings) and SHOW TABLES; and SELECT COUNT(*) FROM `node`; (just be very careful not to issue any commands that insert, update, or delete any data!)
If Drupal really can connect to the database, and you can connect in this way from the command line, then you will have narrowed the problem down to Drush.
You can make sure that you are really running the correct project-local version of Drush 10 that you installed with Composer by executing which drush at the command prompt to see if you are instead using a gloabally installed Drush, perhaps even a different version.
If that is the case, please specify the full path to your local Drush to be sure you are executing the correct Drush PHAR:
$ cd /home/ip/d916/
$ ./vendor/bin/drush status
$ ./vendor/bin/drush cr

If these commands work for you, then you have different options depending on your hosting. The Drush docs are excellent, and will help you to decide the correct path forward.
Comment: It could also be that Drush is executed from the wrong directory and it doesn't find the settings.php file, or it finds a settings.php file that doesn't contain the database connection information, or the correct database connection information. This would explain why the Drupal site works but Drush reports an error.
Comment: Drush was the problem. The downloaded 10.5.0 called by an alias didn't work for me. After runnning `composer require drush/drush`  and `echo export PATH="$HOME/.composer/vendor/bin:$PATH` I had the correct version and both Drush and Drupal work fine.
Comment: I want to add my experience today to this question/answer. I had the
exact same problem as listed in the question, though the op's final answer didn't solve it for me. The steps inside this upvoted answer DID help. I could see that no matter what I did, I could not get a connection to the DB. None of my colleagues had the error I had. I ended up chucking the entire repo and reinstalling it. Same code, same steps, same files, no manual changes, but this time the DB connection formed. Drush commands worked and the site came up first try. Go figure. Hope this helps someone else.
Answer: If you have an extra file with your local settings, like for example  settings.local.php, check if it is placed in the correct directory.
In this case it must be in the sites/default/ directory, not in the sites/ root folder. Most likely the error is caused by a misplaced configuration file.
If that's not the case, or you have only one settings.php, check if you have a valid configuration for your database in the $databases[][] array in it, for the "default" site it must be named "$databases['default']['default']" and must contain all your database information.
Example:
## database settings
$databases['default']['default'] = [
  'database' => 'drupal9',
  'username' => 'drupal9',
  'password' => 'drupal9',
  'prefix' => '',
  'host' => 'database',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
];

Answer: I ran into this recently. If this is a shared host, or a multisite setup, you will need to include the --uri=https://[example-domain.com] parameter with your drush command. That's how it is going to find your particular site's db connection info.
Answer: If you're using local development, such as with Vagrant, Lando, or DDEV, be sure you've established a shell connection to your environment using a command such as vagrant ssh, lando ssh, or ddev ssh, then run your commands from within your SSH session. Otherwise, the Drupal Console command can't connect to the database.
This is true for any other commands like drush that require database access, although many local development environments have shortcuts like ddev drush that handle that connection for you. Drupal console does not have such a shortcut, so an SSH connection to your local environment is essential.
Answer: I had a same issue while executing a drush command. The reason behind my error was a missing directory alias in sites.php file. For ex: I had a site with "example.local.com" and I had created a site folder with the name "example". I had to add a directory alias in sites.php file to fix the issue.
$sites['example.local.com'] = 'example';

Hope this helps someone!!
Refer: https://www.techpond.in/drush-specified-database-connection-not-defined-default


How to practise a glockenspiel part without a glockenspiel?

Question: I've been asked to play one of three glockenspiel parts in a forthcoming performance of a brass band arrangement of Dance of the Sugar Plum Fairy. The three parts together form the well-known celesta part.
I'm not a tuned percussion player, and don't have access to a glockenspiel to practise on.
How can I practise my part so that when I get to play an actual glockenspiel it won't be a complete disaster?
Each individual part is a single line (not even two-note chords) but there are some semiquavers which look a bit intimidating at the moment.
Glockenspiel will be of the horizontal orchestral type, rather than a lyre-mounted marching type.
Comment: Have you looked into renting a glockenspiel?
Comment: Second the rental idea.  That is one of the cheaper rentals.
Answer: Play it on a piano using one finger of each hand.
Sketch out a rough map if a glockenspiel on a large sheet of paper.   Practice 'playing' it with two teaspoons (or something closer to  glock. beaters if you have them).
It'll be OK.  Don't sweat it!
Answer: Horizontal or vertical, static or hand-held?
Big sheet of paper on the kitchen table with a hand-drawn set of rectangles would do for horizontal. For vertical, maybe a sheet of board.
Either will sound just as tuneful ;)
Comment: My grandmother told me that her elementary school taught piano to the whole class at once with printed cardboard keyboards on their desks. She was one of the lucky few that had a real piano at home.  (This was in late-1920s Chicago.)
Answer: A glockenspiel has the same layout as a piano keyboard. Allowing you have access to a keyboard of some kind, learn to play the part that way. My suggestion is to learn it both "as a keyboardist" (i.e., play the notes with your fingers) and also by using soft mallets. Actually playing it as a keyboard part will help learn the location and sound of the notes; playing with some kind of soft mallet (perhaps homemade or home-modified) will let you practice the actual movements.
Comment: That was my first thought, but the spacing would be different. I had a similar issue trying to learn parts to be played on a string bass whilst only having access to an electric. I had no issue with the parts themselves, well within my capabilities, just the spacing. My issue was solved on the day - I had enough time to get used to the difference before it became truly important.


Can't communicate with SIM900a from PC via TTL

Question: I've connected my SIM900a module with PC by using a TTL converter. I've tried two or three terminal (including putty and TMFT) to communicate with this module. But none of them are working. I can't even write anything on these terminal! What am I doing wrong here?
Comment: What (TTL) settings were used in putty?
Comment: Baud rate has set to 9600 and I'm using COM4.
Answer: Connect your PC's TX pin to RX pin of SIM900A and PC's RX pin to TX pin of SIM900A.
You also need to connect your TTL converter's power supply to VMCU pin. This is generally the voltage level of your UART TX & RX pins.
You may also needs to  ground the PWRKEY for a second or two to turn the module on.
Serial Port Settings :

Baud Rate         : 9600
No. of Bits       : 8
No. of Stop Bits  : 1
Soft-Flow Control : None
Hard-Flow Control : None

If baud rate of 9600 doesn't work you cal also try a baud rate of 115200.
Don't forget to include carriage return character at end of each command.
e.g.
<code>const char *at_test = "AT\r"
</code>


Erro após subir apk na play store

Question: Após eu gerar o apk e subir no site a revisão me retorna o seguinte erro:

Fiz todo o processo da página: https://ionicframework.com/docs/v1/guide/publishing.html não houve nenhum erro até gerar o apk e incluir a assinatura. O que devo fazer?
Answer: Isso não é um erro, é um "warning" avisando que o seu app não é um bundle, segundo a própria google:

O Android App Bundle é o novo formato de publicação oficial do Android, que oferece uma maneira mais eficiente de criar e lançar apps. O Android App Bundle traz mais facilidade para você oferecer uma ótima experiência em um app menor, o que pode gerar mais instalações e reduzir as desinstalações. É fácil mudar. Você não precisa refatorar o código para começar a aproveitar as vantagens de um app menor. Depois da mudança, você poderá contar com o desenvolvimento de apps modulares e com a entrega de recursos personalizáveis.

https://developer.android.com/platform/technology/app-bundle
Até onde sei, não tem como fazer tal tipo de app com o ionic.

Erro após subir apk na play store


How to show validity in classical logic?

Question: Firstly, I would like to know what does it mean to be a valid expression in classical logic.
Secondly, How do we show validity of a formula (in sequent calculus) such as:
(∀x A → ∃xB) → ∃x(A → B)
As the above expression is not a sequent, how can we convert it to sequent form to show its validity using sequent calculus in classical logic?
Comment: @Git Gud: in the usual terminology, "valid" is a semantic concept. A formula is valid if it is true in every model. This happens to coincide with the syntactic notion of provability in first-order logic, but the distinction is a useful one. I think rsharma just left $x$ out after the first $\exists$, but I will leave that to rsharma to fix.
Comment: @RobArthan You're right, I got confused with the terminology.
Comment: @GitGud well by valid I mean proving that if its true in every model. This is from an exercise I am doing for my course. The exact question is "Show that (∀xA → ∃xB) → ∃x(A → B) is valid in classical logic, by using the sequent
calculus."

What is confusing me is that there is no "Ⱶ" sign so I could not figure out if its the antecedent or the succedent.
Answer: The sequent $\phi_1, \ldots, \phi_m, \vdash \psi_1, \ldots, \psi_n$ means that if all the antecedents $\phi_i$ hold, then at least one of the succedents $\psi_j$ holds. In some presentations, you must have exactly one formula on the right, so $n = 1$. However, whether or not you are requiring $n = 1$, to prove that a formula $\psi$ is valid using the sequent calculus, you convert it to the sequent $\vdash \psi$ (with $m = 0$ and $n = 1$).
Answer: Here is a proof is sequent calculus :

1) $B(a) \vdash B(a)$ --- axiom

2) $A(a), B(a) \vdash B(a)$ --- by Weakening
3) $B(a) \vdash A(a) \rightarrow B(a)$ --- by $\rightarrow$-right
4) $B(a) \vdash \exists x(A \rightarrow B)$ --- by $\exists$-right
5) $\exists xB \vdash \exists x(A \rightarrow B)$ --- by $\exists$-left

6) $A(a) \vdash A(a)$ --- axiom

7) $A(a) \vdash A(a), B(a)$ --- by Weakening
8) $\vdash A(a) \rightarrow B(a), A(a)$ --- by $\rightarrow$-right
9) $\vdash \exists x(A \rightarrow B), A(a)$ --- by by $\exists$-right
10) $\vdash \exists x(A \rightarrow B), \forall xA$ --- by $\forall$-right
Now we "join" the branches 1)-5) and 6)-10) into :

11)$$\frac{\vdash \exists x(A \rightarrow B), \forall xA \, \, \, \, \, \, \, \, \, \, \exists xB \vdash \exists x(A \rightarrow B)}{∀xA \rightarrow ∃xB \vdash \exists x(A \rightarrow B)}$$

by $\rightarrow$-left

12) $\vdash (∀x A → ∃xB) → ∃x(A → B)$ --- by $\rightarrow$-right.


Regex Jquery in Drupal 7 not working

Question: (I have posted this on Stack Exchange as well)
I have a Drupal 7 page on which I need to remove text bracketed by "Keywords:" and "Description:", there are a number of text blocks all with the class .feedDesc
Page is here: http://www.cafe.gen.nz/node/236/feed-items
I have this working on a plain html page with this Jquery below but can not for the life of me make it work in the Drupal setup:
  $('p.feedDesc').html( function (index,text) {
    var regex = /Keywords(.*)Description/;
    return text.replace(regex,"");
  });

On the site the below does work indicating the whole stack is good.
  $('p.feedDesc').html( function (index,text) {
    return text.replace("Keywords","Foobar");
  });

Help !
Any ideas?
Update:
This works to do the find/replace:
    $('p.feedDesc').html( function (index,text) {
      text = text.replace(/Keywords:([^"]*)Description:/gi,"");
      return text;
    });

However I also need to trim whitespace and $.trim does not work:
    $('p.feedDesc').html( function (index,text) {
      text = text.replace(/Keywords:([^"]*)Description:/gi,"");
      text = $.trim(text);
      return text;
    });

Answer: If that's the exact code, then
var regex = /Keywords(.*)Description/;

should be
var regex = '/Keywords(.*)Description/';

Comment: Regexs in javascript don't need quotes around them

Regex Jquery in Drupal 7 not working


how to solve this second order pde?

Question: $\frac{\partial^2 X_1}{\partial t^2}+\omega_0^2X_1=2\omega_0(1+a_0exp(-\tau))^{-1.5} Sin(3\omega_0t)$ where $a_0$ and $\omega_0$ are constants.
I tried to solve it using methods of characteristics.
$Au_{xx}+2Bu_{xy}+Cu_{yy}+Du_x+Eu_y+Fu=G(x,y)$
For the pde that I want to solve,
A=1, B=C=D=E=0, F=$\omega_0^2$, G=$2\omega_0(1+a_0exp(-\tau))^{-1.5} Sin(3\omega_0t)$
$B^2-AC=0$
so the pde is parabolic everywhere.
$\frac{d\tau}{dt}=\frac{B}{A}$=c, constant which is just $\epsilon$ since $\tau=\epsilon t$
$\implies$ $\xi=\epsilon$
If $\xi$ is constant then the Jacobian of $\xi$ and $\eta$ will always be 0 no matter what function we choose for $\eta$.
So I don't know how to move on from here.
Comment: Since you have derivatives with respect to one variable only, you could work like it was an ordinary differential equation. Just be careful with constants of integration.
Answer: Assume that $w>0$ is a real positive number.
The characteristic equation of an homogeneous equation $$u''+w^2 u=0$$
is $$r^2+w^2 =0$$ which roots are $r=\pm i w$
therefore the solution is $$u=a\sin x + b \cos x$$
To solve the inhomogeneous equation $$u''+w^2 u=f(x)$$
one uses either method of undetermined coefficients or a variation of parameters. The first assumes that the function $f(x)$ can be written in a specific form, the second involves integration of the $\frac{f}{Wronskian}$
Hope this helps.

how to solve this second order pde?


Comparing a List> to a List> Java

Question: I have a method that takes in a List<String> and List<Map<String, Object>>:
public List<Map<String, Object>> filterMethod() {

    List<String> listId = this.getUserIds(); //includes only the user id's
    List<Map<String, Object>> listUser = this.getUserDetails(); // includes user_id, user_name, and user_email
    List<Map<String, Object>> filteredListUser = null;

    return filteredListUser;
}

What I would like to be able to do, is compare these two and return a new List<Map<String, Object>>.
The comparison I'd like to do shown as an example:

Let's say:
List<String> listId =
    [
        "8000",
        "8002",
        "8004",
        "8006",
        "8010",
        "8012",
        "8014",
        "8016",
        "8018",
        "8020",
        "8022",
        "8024"
    ]
List<Map<String, Object>> listUser =
    [
      {
        "USER_ID": "8001",
        "USER_NAME": "username1",
        "USER_MAIL": "firstname.lastname@example.com"
      },
      {
        "USER_ID": "8002",
        "USER_NAME": "username2",
        "USER_MAIL": "firstname.lastname@example.com"
      },
      {
        "USER_ID": "8003",
        "USER_NAME": "username3",
        "USER_MAIL": "firstname.lastname@example.com"
      },
      {
        "USER_ID": "8004",
        "USER_NAME": "username4",
        "USER_MAIL": "firstname.lastname@example.com"
      },
      {
        "USER_ID": "8005",
        "USER_NAME": "username5",
        "USER_MAIL": "firstname.lastname@example.com"
      },
      {
        "USER_ID": "8006",
        "USER_NAME": "username6",
        "USER_MAIL": "firstname.lastname@example.com"
      },
      {
        "USER_ID": "8007",
        "USER_NAME": "username7",
        "USER_MAIL": "firstname.lastname@example.com"
      }
    ]

I would like to return a new filtered List<Map<String, Object>>, that contains listUser rows where a listUser USER_ID is in listId (i.e:)
List<Map<String, Object>> filteredListUser =
    [
      {
        "USER_ID": "8002",
        "USER_NAME": "username2",
        "USER_MAIL": "firstname.lastname@example.com"
      },
      {
        "USER_ID": "8004",
        "USER_NAME": "username4",
        "USER_MAIL": "email@example.com"
      },
      {
        "USER_ID": "8006",
        "USER_NAME": "username6",
        "USER_MAIL": "firstname.lastname@example.com"
      }
    ]

The issue comes when I need to compare the user_id from listUser with listId in order to check if I need to add the row to filteredListUser.
I would know how to do this if this were simply two string arrays like so:
String[] a = {1, 2, 3, 4, 5, 6, 7};
String[] b = {2, 4, 6, 8, 10};

ArrayList<String> c = new ArrayList<String>();

for (int i = 0; i < a.length; i++) {
        if (Arrays.asList(b).contains(a[i])) {
            c.add(a[i]);
   }
}

I think a for-loop would also be appropriate for the List comparisons, but I am unsure as to how I can compare the user_id in listUser with listId in List<Map<String, Object>> and List<String>.
As an attempt and pseudo-code perspective, what I am trying to accomplish is this:
public List<Map<String, Object>> filterMethod() {

    List<String> listId = this.getUserIds(); //includes only the user id's
    List<Map<String, Object>> listUser = this.getUserDetails(); // includes user_id, user_name, and user_email
    List<Map<String, Object>> filteredListUser = null;

    for (int i = 0; i < listUser.length; i++) {
        if (listId.contains(listUser.USER_ID[i])) {
            filteredListUser.add(listUser[i]);
        }
    }
    return filteredListUser;
}

I'm not entirely sure where to go from here however - would appreciate any help!
Apologies if this is a really rudimentary question - I'm very new to programming. Thank you in advance!
Comment: You need a better abstraction that List, Map, String, and Object.
Comment: User is a map with key for the userId and value for object with user attributes like userId, userName etc.. ?
Answer: I would iterate the List<Map<String, Object>> and check corresponding value to USER_ID is present in List<String> listId. below is the approach by using java-8 streams
List<Map<String, Object>> result = listUser.stream()
                                      .filter(m-> listId.contains(m.get("USER_ID")))
                                      .collect(Collectors.toList());

or By using simple for loop
List<Map<String, Object>> filteredListUser = new ArrayList<>();

for(Map<String, Object> m : listUser) {
        if(listId.contains(m.get("USER_ID"))) {
            filteredListUser.add(m);
        }
    }

You can also do it by using removeIf but this modifies the existing map
listUser.removeIf(m->!listId.contains(m.get("USER_ID")));

Comparing a List> to a List> Java


Django-ratelimit does not limit

Question: I have the issue using Django-ratelimit on heroku that the limiter is not working. I don't get any error. Any suggestions what I am doing wrong?
views.py
from django.core.cache import cache
from ratelimit.mixins import RatelimitMixin

[...]

class LoginView(RatelimitMixin, FormView):
    ratelimit_key = 'user'
    ratelimit_rate = '1/5m'
    ratelimit_method = 'GET'
    ratelimit_block = True

    template_name = "account/login.html"
    template_name_ajax = "account/ajax/login.html"
    form_class = LoginUsernameForm
    form_kwargs = {}
    redirect_field_name = "next"

    @method_decorator(sensitive_post_parameters())
    @method_decorator(csrf_protect)
    @method_decorator(never_cache)
    def dispatch(self, *args, **kwargs):
        return super(LoginView, self).dispatch(*args, **kwargs)

    def get(self, *args, **kwargs):
        if is_authenticated(self.request.user):
            return redirect(self.get_success_url())
        return super(LoginView, self).get(*args, **kwargs)

Setting.py
# RATELIMIT SETTINGS
#RATELIMIT_CACHE_PREFIX = 'rl:'
RATELIMIT_ENABLE = True
RATELIMIT_USE_CACHE = 'default'
#RATELIMIT_VIEW = None

Comment: how did you fix this issue?
Answer: Just some thoughts of what may be wrong. Please note that I've never used this app, I just had a look on the ratelimit's documentation.
Change the ratelimit_key to ip, instead of user.
Since it's on a login page, I believe the user key would have no effect, because it relies on the request.user.
Probably what you want is to use the ip instead.
class LoginView(RatelimitMixin, FormView):
    ratelimit_key = 'ip'
    ratelimit_method = 'POST'

It may require you to change the ratelimit_method to POST. At least it would make more sense for me.
Read more on Ratelimit Keys - Common Keys.
PS: Since you mentioned you have your application deployed on Heroku, there may be an issue regarding getting the client's IP address, which is probably used by the django-ratelimt app. Read more on this SO question: Get client's real IP address on Heroku.

Django-ratelimit does not limit


What is the problem about static pointer?

Question: I've just started learning OOP. I want to create a LinkList of BookList and use Singleton design pattern to create a unique object "library" to manage this BookList, but there is problem when initializing BookList.
class Library {
public:
static Library* library;
static BookList* pHead;
static int i;
static int getNewID(BookType typ) {
    return i++;
}
static Library* getLibrary();
static Library* getLibrary(BookList*);
static BookList* getNull(BookList*);
private:
Library(BookList* a);
};
Library* Library::getLibrary() {
if (library == NULL) {
        BookList* a = new BookList;
        library = new Library(a);
    }
    return library;
}
Library* Library::getLibrary(BookList* a) {
    if (library == NULL) {
        library = new Library(a);
    }
    return library;
}
Library::Library(BookList* a) {
    BookList* p = pHead;
    while (1) {
        if (p->getNext() == NULL) {  //I got error
        p->setNext(a);
        break;
        }
        p = p->getNext();
    }
}

And i got an error here:

Undefined symbols for architecture x86_64:
"Library::pHead", referenced from:
Library::Library(BookList*) in test-9c557d.o
ld: symbol(s) not found for architecture x86_64

Did i forgot something?
Answer: Seems like you didn't define pHead - you just declare it. Try to add the following code in your implementation file (.cpp / .cxx):
BookList* Library::pHead = new BookList();

Comment: I got it. Thank you for the answer.


What determines which fields are available in the relationship options?

Question: What determines which fields are available in the views relationship options?
When creating a view, you can use Relationships, choosing from a list of available fields. Are all created fields supposed to be available for relationship in any view? It seems that some fields are available and some are not.
Example: I have Students and School as my Content Types. Students uses a Node Reference to School. When creating a view, I use Relationship, and a bunch of fields are there to choose from. As expected, School is there, because it is referenced in a field. But there are a lot more fields available. Why are those fields available? What criteria do fields fill to be available to use?
Answer: One thing that affects the choice of the fields that are available is the show box when you first create the view this allows the developer to refine the criteria that is being chosen.
Answer: Inherently relational field types will automatically be there (e.g. entity reference, taxonomy). Other fields, like integer or text field, don't have anything to relate to by default.


Separating Line Numbers from Text in Terminal: Emacs

Question: When I run emacs in Terminal mode and have the global-linum-mode option enabled , the line numbers are very close to my text and it is really irritating for the eyes. Is there a way to separate the line numbers from the text in Emacs?
Answer: Try setting linum-format to "%d " (note space).
There's more to do if you want right-aligned line numbers (what's provided by the 'dynamic default for linum-format) with spacing after them. Perhaps something non-trivial should be done in linum-before-numbering-hook.
Answer: too few points to just add a comment to the accepted answer, but I'm using
(setq linum-format "%3d ")

to have right-aligned line numbers for files with less than 1000 lines. Also works OK for larger files, as the line numbers just take up the required number of chars (4 or more) even with that formatting option.


Opensource simplified calendaring solution

Question: I'm after a very simple (in my eyes) opensource calendaring solution. The basic functionality I need is:

provide readonly ICS feed (http/s/) (the way
google cal provides it), so clients
can subscribe to it
API to create/delete users (and
their calendars) - one calendar per
user is enough
API to manage (create, search,
update, delete) events in users'
calendars
supports events in multiple
timezones

Basically I want to skip all the steps needed to create ICS myself.
For what I need Zimbra looks like an overkill.
For an answer to be considered "good", and/or accepted, it has to list each of the above features, and how/if they are supported by the proposed solution.
Answer: The CalDAV protocol will give you what you're looking for. The CalDAV server that I use w/ Mozilla Sunbird and my iPod Touch is DAViCal, and I like it very much. It's definitely not the only thing out there, though...
Answer: Here, give this a look: http://www.k5n.us/webcalendar.php


Equation involving logarithm, solvable without calculator?

Question: I'd like to know if I can solve the following equation without calculator:
$(0.4)^t=5t$
I don't think it's possible, cause I always get stuck on formulas of the form $e^t=t$ or $t=\ln t$
I've also put the equation into wolframalpha, which was of no use to me unfortunately.
I'm not interested in the answer containing a W-function.
Just want to know whether I can find the real solution or not!
Thanks!
Comment: Here is a more [general case](http://math.stackexchange.com/questions/217254/apparently-cannot-be-solved-using-logarithms/217262#217262).
Answer: No, it is not possible to solve in terms of elementary functions.  That is why W|A returns an answer using the W function.
When you find the formula boils down to $t=\ln t$, you've come across a form of Lambert's Transcendental Equation:
Comment: @Quickquestion My pleasure.  Since you're somewhat new to Math.SE, I will remind you that you can accept answers that, in your opinion, answer your question the best.  That is done by clicking the green checkmark on the left of the answer you like.  This makes the accepted answer stay on top of all the other answers, provides a reputation bonus to the answerer, and increases your own reputation by 2pts.
Comment: Did I really just get an upvote in 16 seconds?  That's a little weird. `:)`  (but in a good way)
Comment: Okay thank you for your quick answer! :)
Answer: You will need a numerical method or some not-so-obvious special function to do this.
Answer: There is a solution $t$, since $(0.4)^t\gt 5t$ at $t=0$, and $(0.4)^t\lt 5t$ at $t=1$. It is easy to see that there cannot be a solution outside the interval $(0,1)$.
There is no rational solution. For suppose that $t=\frac{p}{q}$ is a solution, where $p$ and $q$ are relatively prime integers, neither equal to $0$. Since $0\lt t\lt 1$, we have $p\lt q$. Then from
$$\left(\frac{2}{5}\right)^{p/q}=5\frac{p}{q}$$
we obtain
$$2^pq^q=5^{p+q}p^q.$$
Thus $p$ is a power of $2$. This is impossible, since then $2^p \lt p^q$.
By using the Gelfond-Schneider theorem, we can now prove that $t$ cannot be an irrational algebraic number. For if $t$ is irrational algebraic, then $(0.4)^t$ is transcendental, but $5t$ is not.
So $t$ is transcendental. We have not ruled out the possibility that $t$ is a simple combination of "simple" transcendentals, such as $\log 2$, $\log 3$, \sin 1$, and so on.


Understanding the model-theoretic proof of Hilbert's Nullstellensatz

Question: The proof I am talking about goes like this: Given $k$ algebraically closed and $(f_1,..,f_k)=I\neq (1)$ an ideal in $A=k[x_1,..,x_n]$, let $m$ be a maximal ideal with $I\subseteq m$ and observe that $k$ embeds into the algebraic closure $k'$ of $A/m$ , and that $f_1,..,f_k$ have the common zero $(\overline x_1,..,\overline x_n)$ in the extension field. Now use model-completeness of the theory $\Phi$ of $k$, which is the same as the theory of $k'$, and conclude that $\Phi \models \exists y_1,..,y_n f_1(y_1,..,y_n)\land ..\land f_k(y_1,..,y_n)$, because this holds in $k'$, so it must hold in $k$ also.
The proof is described for example here on page 89 and here on page 8 and 9.
My problem is: $\exists y_1,..,y_n f_1(y_1,..,y_n)\land ..\land f_k(y_1,..,y_n)$ is not immediately a formula over the laguage of fields, since it contains the symbols/functions $f_1,..,f_k$ which are not part of that language. I can see how to restate this formula using only symbols of the language of fields in the case that $f_1,..,f_k$ have integral coefficients, but not in the general case. (e.g. for $k=\mathbb{C}$ there are uncountably many possiblities for coefficients)
Answer: But polynomials are formulas in the language of fields.
I mean what is an atomic formula in the language of fields? It has no relations except equality. So we have to claim that two terms are equal, but instead we can claim that the difference is zero. So we can always assume that this is a sum of two terms being equal zero.
What is a term? We have finitely many free variables, $x_1,\ldots,x_n$, and multiplication either by one another or by parameters (that is scalars) and finally... addition.
So we have finitely many variables and we are allowed to multiply them by one another, and by scalars from the field, and then we add everything up and we claim it is equal to zero. What do we end up with? A polynomial in $k[x_1,\ldots,x_n]$!
So atomic formulas are just polynomials. From there the rest follows.
Comment: Ah, I get it now. The definition of elementary substructure allows using free variables in a formula which is supposed to be equivalent in both structures as long as they are interpreted as some fixed elements of the substructure. Somehow I missed that, I was thinking only of sentences.
Comment: But what about the coefficients? I mean, how can you e.g. state that something is a zero of $\pi X +1\in \mathbb{C}[X]$
Comment: @user35359: You allow parameters. What are parameters if not elements from the model, i.e. scalars?
Comment: @user35359: Note that $\pi X+1$ is a term. When you assign $X$ a value then it becomes just a complex number. The formula stating that this term is equal to $0$ is just $\pi X+1=0$, and it is true if and only if you assign $X$ a particular value, in this case $-\frac1\pi$.
Comment: @user35359: this is precisely the part which uses model completeness.


How can I specify Standard SQL in a Talend tBigQueryInput query?

Question: I have tried specifying standard SQL using a query prefix with this syntax but Bigquery seems to ignore the directive:
<code>"#standardSQL  \r\n
select column1 from `mydataset.myview`"
</code>
but I get this error:
<code>Running Query : #standardSQL
select column1 from mydataset.myview
---> Reason: invalidQuery
Message: Cannot reference a SQL view in a Legacy SQL query.
</code>
Comment: It looks like Talend might be prepending their own `--` or `#` style comment to your query before it is sent to BigQuery. Does Talend provide some other way of specifying the SQL dialect? If not, it might be good to file some kind of feature request with them.
Answer: I got this to work by removing the space between "#standardSQL and \r\n.
Works:
<code>"#standardSQL\r\n
</code>
Doesn't work:
<code>"#standardSQL \r\n
</code>
RTFM:
<code>"Must be separated from the query by a newline character"
</code>
My update to the FM:
<code>"Must be separated from the query by ONLY a newline character"
</code>


Add a class (or attribute) if not already there

Question: How would I add an attribute to an element if that element does not already have that attribute?
if (' this does not have class=selected') {

    $(this).addClass('selected');
}

Comment: Do you mean class specifically, or any attribute? Because you can call .addClass() as many times as you want.
Comment: And that won't add a duplicate?
Comment: It doesn't matter if it's a duplicate.  Either an element has a class or it doesn't; if it has the same class more than once, from the perspective of Javascrcipt and the DOM, it has the class.
Answer: if(!$(this).attr('name')) {
   $(this).attr('name', 'value');
}

that ought to do it.
Comment: I just tried this as is exactly what I want but couldn't get it to work if(!$(this).attr('placeholder')) {
   $(this).attr('placeholder', 'c');
}
Comment: This question has an incorrect title.  This answer correctly answers the question as it is stated in the title.  If the title is ever corrected, this answer will appear to be incorrect.
Answer: If you're talking specifically about classes, then just go ahead and add it. If it already exists, it won't be added twice.
$(this).addClass('selected'); // will only add the class if it doesn't exist

I doubt that first testing for the class would be any more efficient.
live demo: http://jsfiddle.net/2sLd5/
Answer: The jQuery documentation is your friend! :)
http://api.jquery.com/category/css/
You are probably looking for the HasClass
http://api.jquery.com/hasClass/
$('#mydiv').hasClass('foo')

Answer: You can use the attribute not selector. This works not only for classes but for any attribute
if($('#elemid[class!="myclass"]').length) {
    $('#elemid').addClass('otherClass');
}

Of course as mentioned before if you want to add the class your checking against, just add it. There is no harm in that.
Answer: It is not necessary to check and see if the class is already present before adding the class.  Looking through the jQuery source (https://github.com/jquery/jquery/blob/master/src/attributes.js, search for addClass), it appears that addClass will do nothing if the class is already present.  Therefore, there's no point to checking first.


Issue loading MDX Query into PowerBI when it loads into SSMS with no problems

Question: I am trying to create a dashboard in PowerBI that refreshes with the information in a Pivot Table by connecting directly to a SSAS Cube. I retrieved the MDX query from the Excel file and the query runs perfectly in SSMS. However, when I import the query to PowerBI, the numerical data loads in, but the categorization data (text) loads in as [Plant].[Plant].[All] rather than the actual Plant name. Any insight into why this is happening?
SELECT
  CrossJoin(
    {[Measures].[Closing Balance Amount],
    [Measures].[Closing Balance Quantity]},
    Hierarchize(
      {DrilldownLevel(
        {[Product SKU - Material].[Material Type].[All]}
      ) }
    )
  ) DIMENSION PROPERTIES PARENT_UNIQUE_NAME,
  HIERARCHY_UNIQUE_NAME ON COLUMNS,
  NON EMPTY CrossJoin(
    CrossJoin(
      CrossJoin(
        Hierarchize(
          {DrilldownLevel(
            {[Profit Center].[Profit Center].[All]}
          ) }
        ),
        Hierarchize(
          {DrilldownLevel(
            {[Product Hierarchy].[L11 BFPP].[All]}
          ) }
        )
      ),
      Hierarchize(
        {DrilldownLevel(
          {[Product Hierarchy].[L14 SKU].[All]}
        ) }
      )
    ),
    Hierarchize(
      {DrilldownLevel({[Plant].[Plant].[All]}) }
    )
  ) DIMENSION PROPERTIES PARENT_UNIQUE_NAME,
  HIERARCHY_UNIQUE_NAME ON ROWS
FROM
  (
    SELECT
      (
        {[Product SKU - Material].[Material Type].& [1U] & [ROH],
        [Product SKU - Material].[Material Type].& [1U] & [PACK],
        [Product SKU - Material].[Material Type].& [1U] & [HALB],
        [Product SKU - Material].[Material Type].& [1U] & [FERT]}
      ) ON COLUMNS,
      (
        {[Profit Center].[Profit Center].& [1U] & [ULAM] & [0000100058],
        [Profit Center].[Profit Center].& [1U] & [ULAM] & [0000100075],
        [Profit Center].[Profit Center].& [1U] & [ULAM] & [0000100022],
        [Profit Center].[Profit Center].& [1U] & [ULAM] & [0000100090],
        [Profit Center].[Profit Center].& [1U] & [ULAM] & [0000100091],
        [Profit Center].[Profit Center].& [1U] & [ULAM] & [0000900015]}
      ) ON ROWS
    FROM
      [Stock Balance]
  )
WHERE
  (
    [Reporting Currency].[Reporting Currency].& [USD],
    [Segment].[Segment].& [1U] & [0000001010],
    [Company Code].[Company].[All],
    [Time].[Month].& [2019] & [4]
  ) CELL PROPERTIES VALUE,
  FORMAT_STRING,
  LANGUAGE,
  BACK_COLOR,
  FORE_COLOR,
  FONT_FLAGS

I would like to see the Plant name and SKU names rather than just the references.
Comment: Hi Emily, please can you add the MDX to the question
Comment: Do you only get this behaviour with [Plant] or does it also happen with the other hierarchies?
Comment: It happens with all the hierarchies
Comment: hmmm ... I added an 'answer' but sorry it is not much of a help. We have very mature OLAP cubes but we are currently porting over to Tabular so we can get the most out of Power BI ...
Answer: I have the following against Adventure Works:
1.
SELECT
   [Measures].[Internet Order Count] on 0,
   [Customer].[Customer].[Customer] on 1
FROM [Adventure Works]

Then I import this into Power BI via "Import" and the above MDX script.
The only slight oddity in Power BI is that the column headers/names are the full addresses:

This is trivial to change though - very easy to adjust the column headers.
In the table the member names look fine:

2.
If I include the ALL member then things get strange.
So the script I use is now this:
SELECT
    [Measures].[Internet Order Count] on 0,
   {
    [Customer].[Customer].[All Customers],
    [Customer].[Customer].[Customer]
   } on 1
from [Adventure Works]

All Customers does not now appear in the visualization - definitely not good:

3.
So last I tried a live connection - now there is no ALL member at all, in the fields area, but at least the column headers are clean:

So I'd suggest either using a live connection to your cube OR start exploring Tabular cubes and get a plan to move over to Tabular as that is the flavour of SSAS which Power BI likes best.


Finding the summation of the floor of the series.

Question: Can someone help me the summation of the given series.
$$\sum_{i=1}^n\left\lfloor\frac{n}i\right\rfloor$$
Negative of the above summation looks similar to the expansion of the $\log(1-x)$ without the floor.
Comment: According to a [recent answer](http://math.stackexchange.com/a/485879/7933), it is $n\log n + (2\gamma-1)n + O(n^{1/2})$.
Comment: As the floor is being used can't we get the numerical value..
Comment: [OEIS A006218](http://oeis.org/A006218) gives various formulae and references
Comment: Yes, but we can give an approximation, which is what I gave. @user1580096
Comment: @user1580096 and so? for example you can easily prove that $\sum_{r=0}^{n-1}\bigl\lfloor\frac{a+r}n\bigr\rfloor=a$ for any $a,n\in\mathbb Z$ with $n\ne0$.
Comment: Strictly speaking, you are right when you call your sum a "series", because you can change the upper limit of summation $n$ by $\infty$ (because $\lfloor n/i\rfloor=0$ for $i>n$)...but I think that it is better you call it simply "a sum".
Answer: This is OEIS A$006218$. No closed form is known; the problem of finding a precise asymptotic estimate is the Dirichlet divisor problem. You'll find references, asymptotic estimates, and other information at the two links and here.
A useful tip: I simply calculated the first half-dozen terms and ran them through The On-Line Encyclopedia of Integer Sequences (OEIS); that's worth a try any time you want information about an integer sequence.


Windows incremental backup script

Question: I'm from a linux background, and need to run an incremental backup script on windows. I already have a batch script which dumps my database into a file. What I'd like is to only keep backups for the last seven days in addition to one backup file per week for the last 4 weeks (for example). I presume it's possible to do something like this with the windows task scheduler and a clever batch script?
Thanks.
Comment: What kind of database are you backing up?  How are you backing it up?
Comment: It's a postgres database backed up with pg_dump called from batch script if that helps.
Answer: (loudhailer voice) STEP AWAY FROM THE BATCH SCRIPT
People from a Linux/Unix background frequently make the mistake of trying to do things on Windows in the Linux/Unix way, and the end result is invariably horrifying (the opposite is also true, of course).
Use NTBackup to set up the jobs you want, it will handle them properly and will create scheduled tasks for you.  It does accept command-line params, but you are better off using the GUI, in particular as this is an unfamiliar environment for you.  Ask yourself - is your data worth so little to you that you would run the risk of scripting something in an unfamiliar environment?
Be aware though that if the type of database can only be backed up using a file-based backup, there is no value in incrementals (or differentials, which would be preferred, as you only need the last full and the last diff to restore), as the entire file will be backed up every time.
Comment: There is nothing wrong with using the command line in Windows. man page for ntbackup.exe: http://support.microsoft.com/kb/814583
Comment: It is true that for recovery you only need the last full and the last differential. But keeping only these two files really limits your restore options to the last full, and the most recent backup.  There are plenty of reasons to restore to some intermediate point.
Comment: @shufler - absolutely agreed, but I'm coming from the perspective of making it less possible for someone working in an unfamiliar environment to trip themselves up.  What I would recommend to an experienced Windows user would of course be different.
Comment: @Laura: true that, but even for an intermediate point you would still only need 1 full and 1 diff to restore vs 1 full and potentially more than 1 incremental.
Answer: A really fast scan of the pgdump docs leads me to suspect that every time you back that database up it is a full of the database.  I'm not seeing an option for an incremental.  I haven't used it though and like I said it was just a quick skim over the docs.
It is absolutely possible to write a batch script that copies files and keeps version of specific ages.  I would probably keep my weekly copies in a folder different from the nightly ones.  Copy the oldest nightly into the weekly folder on whatever day of the week... then delete the oldest weekly.  Robocopy is capable of determining file age and acting on files based on that age.
Then schedule your weekly full task to run weekly and grab the oldest/newest/wednesday whatever day you like and copy it to the full folder.   Schedule your other script to run daily.

Windows incremental backup script


Why wasn't Frantisek Fadrhonc the coach of Netherlands during 1974 FIFA World Cup?

Question: I read that someone called Frantisek Fadrhonc was the Netherlands coach from 1970 to 1974 but, for some reason, he was replaced by Rinus Michels 4 weeks before the 1974 World Cup. I couldn't find any data about why he quit or why he was fired.
It is curious that, AFAIK, he seems to be forgotten and he didn't receive any credit for the formation of that historic "Orange Clockwork" team, while Rinus Michel is highly recognized, despite he "only" coached the team during the World Cup and quit the job immediately after.
Answer: Rinus Michels was indeed the manager of the Netherlands for the FIFA World Cup in 1974, where they lost the final versus Germany.
I have not been able to find any exact reference on why Michels was not the coach prior to the tournament, but here comes my reasoning:
Checking his career path I found out that he was the coach of Futbol Club Barcelona from 1971 to 1975. This probably means that he was not allowed to serve as national team coach at the same time of being Barcelona's coach, but allowed as soon as the season was over. Since La Liga finished on May 20, 1974 and the 1974 FIFA World Cup started on June 13, it would make sense.
I also found out in the Dutch article on the FIFA 1974 World Championship Wereldkampioenschap voetbal 1974 → Groep 3:

Eindelijk plaatste Nederland zich voor een wereldkampioenschap, de grote generatie van Ajax en Feyenoord kon zich eindelijk manifesteren tegen de grote landen. De KNVB had weinig vertrouwen in coach Fadrhonc en besloot de succescoach van Ajax en FC Barcelona Rinus Michels als supervisor aan te stellen. In de oefencampagne liep het allemaal totaal niet en de verwachtingen waren laag.

Which Google translates as:

Netherlands finally qualified for a world championship, the great generation of Ajax and Feyenoord could manifest itself at last against the big countries. The KNVB had to appoint little confidence in coach Fadrhonc and decided the success of Ajax and FC Barcelona coach Rinus Michels as a supervisor. The training campaign was all totally and expectations were low.

In relation with the credit for the formation of that historic "Orange Clockwork", I do think that this is due to the fact that the underlying style was set up a bit before by Ajax with Johan Cruyff, which had Michel itself as a coach in its golden years 1965-1971. As Wikipedia says:

While at Ajax, Michels modernized the game by introducing what became known as "Total Football" and using the Offside trap

All together, it looks like he was kind of assigned the honor to be the coach in the World Cup for being the one who had defined the style of playing with the same players that helped him to do it.


account lockout policy - what happen user tried logon with wrong password 3 and use the correct PWD on 4th time?

Question: Password settings attribute in question:

A number of failed login attempts value set to 4.
Reset failed logon attempt counter reset to after 1 min

Scenario:
When the user use the wrong password to login thrice and he used the right password on 4th time. Within a min, he lock the system and tried with the wrong password.
In the above scenario will the account lockout or will it reset the counter?
Answer: A successful login should clear the bad password counter on the PDC Emulator.  This attribute does not replicate.
Comment: HI Thanks for the response. Just to make sure we both are in same page . The counter will not reset unless and until its exceed the counter reset to specified value . for instance user tried 2 bad password attempt and the 3rd on was successful right after he lock the system and tried again with bad password with in the specified value ( 1 min) the account will locked out.
Comment: correct me if am wrong.


Representing pairwise-independent but not independent occurrences with venn diagram

Question: For $A,B$ and $ C $ partially pairwise independent occurrences (i.e. $I(A;B)=0$, $I(A;C)=0$ ), it is not true to say that $I(A;B,C)=0$, since $I(A;B,C)=I(A;B)+I(A;B|C)$ [<-this is not correct, see edit] and we have no information about $I(A;B|C)$.
If i had to use venn diagram on the above case, i would use this diagram, in which $I(A;B,C)=0$.

I use venn diagram often when I need to prove/disprove equalities and inequalities in information measures, but my intuition seems to mislead me here.. So my question is - is it possible to draw an appropriate diagram for this case? or should i stop using such diagrams since they do not fit all cases?
EDIT: i have made a mistake when i wrote down my question here, possibly misleading some of the answers. the correct identity is $I(A;B,C)=I(A;B)+I(A;C|B)$ (note its A;C|B and not A;B|C). when wrote in the correct way, it is possible to use the inequality ("conditional reduces entropy") and get $I(A;B,C)=I(A;B)+I(A;C|B)\le I(A;B)+I(A;C)=0$ (the last equality comes form the question terms). this only confuses me more, since i did not expect $I(A;B,C)$ to be zero (again, pairwise independent between A,B and A,C).
EDIT2: Im not sure about this inequality $I(A;B)+I(A;C|B)\le I(A;B)+I(A;C)$. if anyone can help out, ill be glad. I will update when i will be sure what happens here.
Comment: Is $I(A;B)$ the probability of $A$ and $B$ both occuring? What does $B|C$ mean?
Comment: Please explain your notation.
Comment: $I(A;B)$ is the mutual information between A and B. $I(A;B|C)$ is the mutual information of A and B given C.
Answer: In this chat discussion, we have obtained a case:

Here, $B$ and $C$ are independent random variables which can each take a value of $0$ or $1$ with equal probability. It is clear that $B$ and $C$ each have 1 bit of entropy. Let the bits be represented by fair coins.
Here, $A$ is defined as $B\ \text{XOR}\ C$. It is clear that $A$ is determined by both coins, so in the diagram $A$ must include both $B$ and $C$.
But, it has been shown that $A$ only has $1$ bit of entropy. Therefore, the grey space (that is, the space in $A$ but outside $B$ and $C$) contains $-1$ bits of entropy, which makes the Venn diagram invalid.
Therefore, there exists a case for which no Venn diagram is appropriate.
This is a counter-example to the following statement:

For any three random variables $A,B,C$ such that I$(A;B)=0$ and $I(A;C)=0$, a Venn diagram that represents $A$, $B$, and $C$ can be drawn according to entropy.
Comment: as i said, it is possible that $I(A;B,C) \ne 0$ since i only have pair-wise independency, and this cannot be seen from the diagram, so how can this be correct?
Comment: Please confirm, A is independent from both B and C, right? Then it's impossible for anything in A to be in either or both of B and C.
Comment: As far as venn diagrams go - i think you are correct. But the tricky part is the pairwise independency. check out [wiki-link](https://en.wikipedia.org/wiki/Pairwise_independence) for more info.
Comment: @sagivd If you really meant $A,B$ and $A,C$ are pairwise independent as defined in the wiki article, then the notations $I(A;B)=0$ and $I(A;C)=0$ are incorrect.
Comment: If the notation is correct _and_ they are pairwise independent, then either A or either of B and C is 0.
Comment: @sagivd I think the problem is in your _notation_.
Comment: I am sure that if A and B are independent then $I(A;B)=0$. I am not sure about the converse, but i had the feeling that it is true as well. why do you think this is not true? I use the [first definition of mutual information from here](https://en.wikipedia.org/wiki/Mutual_information), and you can see that it is zero only if X,Y are independent.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/42490/discussion-between-user351579-and-sagivd).
Comment: @sagivd I have edited my answer to answer your updated question.
Comment: See my answer. I believe venn diagrams cannot be used in such cases where conditional mutual information is involved. Thanks for all the effort!
Comment: @sagivd There is _unconditional_ mutual information and _conditional_ mutual information. The existence of a third random variable does not affect the unconditional ones, such as $I(A;B)$ and $I(A;C)$. The sentence in the Wikipedia article means that if you add a condition to previously unconditional mutual information (for example turning $I(A;C)$ into $I(A;C|B)$) its value can change. But the value of $I(A;C)$ _itself_ does not change. With all due respect, I think you are the one who misunderstood.
Comment: @sagivd It's like adding an argument to a $max$ function expression, for example turning $max(x,y)$ to $max(x,y,z)$. The value of $max(x,y)$ itself does not change.
Comment: If it couldn't be represented by a Venn diagram, the Wikipedia article wouldn't include a Venn diagram.
Comment: I cannot agree. Since the element $I(A;B|C)$ can be smaller than $I(A;B)$, the element in the "middle" (which is denoted by $I(A;B;C)$, or **(2)** in your diagram, and is different than $I(A;B,C)$) can be negative. How can you use a Venn diagram for a negative value?
Comment: @sagivd Please state in terms of $A$, $B$, and $C$.
Comment: @sagivd And no, it's not negative, because $I(X;Y)=I(X;Y|Z)+I(X;Y;Z)$, or equivalently, $I(X;Y)-I(X;Y|Z)=I(X;Y;Z)$. If $I(X;Y|Z)$ is smaller than $I(X;Y)$, $I(X;Y;Z)$ would be _positive_.
Comment: !!!!$I(X;Y|Z)$ is the part of $I(X;Y)$ which is **outside** $Z$ ($Z$ is given, so no entropy from $Z$). $I(X;Y;Z)$ is is the part of $I(X;Y)$ which is **inside** $Z$.
Comment: Check again: My point was that $I(A;B|C)$ (or $I(X;Y|Z)$) can be smaller, greater or equal to $I(A;B)$, which means that $I(A;B;C)$ can be negative.
Comment: If the value of a random variable is given, it ceases to have entropy.
Comment: I understand the notation using the Venn diagram. I am saying the the diagram is INVALID in this situation because it cannot depict negative sizes.
Comment: How can it be greater than $
I(A;B)$?
Comment: Let's move this to chat again. The comment count is sharply increasing.
Comment: Honestly: I don't know. the course i took did not include this information. I am basing this on the link i gave from wikipedia.
Comment: @sagivd I have edited the answer again.
Comment: @sagivd I'm testing the concept, with paper and pen.
Comment: @sagivd It turns out assigning numbers to "number-of-determining-bits-based" doesn't work in some cases. So just use the upper part.
Answer: From wikipedia:

Conditioning on a third random variable may either increase or decrease the mutual information

I believe this fact prevents the use of venn diagram in such cases where it is relevant, since (as the previous answer and also myself stated) in the diagram it is clear that $I(A;B) \ge I(A;B|C)$, but this is actually NOT true.
EDIT: I am accepting my own answer since I was not convinced that @user351579 is 100% correct, and honestly - knowing that Venn diagram does not work in ALL cases is an answer i am satisfied with. For a deeper discussion of ways around this, see my conversation\chat with @user351579 and\or his answer.
Comment: Sorry I should correct it as: If $X \to Y \to Z$ then $ I(A;B) \geq I(A;B|C)$ AND without the condition $X \to Y \to Z$, both $ I(A;B) \geq I(A;B|C)$ and $ I(A;B) < I(A;B|C) $ could happen
Comment: There are still cases where Venn diagrams is usable, such as when entropy equals the number of determining bits. But I presume a counter-example is enough.
Comment: Actually, $I(A;B) \geq I(A;B|C)$ is true only when $A, B, C$ forms a Markov chain ( $A \to B \to C$ ), which means $A$ and $C$ are conditionally independent given $B$.
Comment: @Julie I understand that $I(A;B) \ge (A;B|C)$ is true when $A,B,C$ forms a markov chain, but why is it **only** true with this condition?
Comment: this looks correct to me :)
Answer: I'm new in information theory, but here's my opinion after reading your discussion and links.
I think the point is that in a three-set Venn diagram, the overlapping part of $A$ and $B$ isn't $I(A;B)$ but $I(A;B|C)$ which may not equal to $I(A;B)$.
And $ I(A;B) = 0 $ doesn't imply $ I(A;B|C) = 0 $ since the inequality
$ I(A;B|C) \leq I(A;B) $ is under the condition of $ X \to Y \to Z $
Thus, returning to your question, it might be impossible to draw an appropriate diagram for this case unless you have the information about $I(A;B|C)$, in my opinion.
Comment: $I(A;B|C)$ is the intersecting part of $A$ and $B$ **which is not in $C$**. $I(A;B)$ is always the entire intersecting part of $A$ and $B$. For more information read this section of the Wikipedia article about mutual information : https://en.wikipedia.org/wiki/Mutual_information#Relation_to_other_quantities
Comment: @Julie I edited the question. i am now confused about the whole situation..


Offline files fail with "Access Denied" but only by MS Office apps

Question: I have a Win10 computer on a domain.  It can access all files/folders on a server share fine when online.  I have marked a subfolder for offline use on the laptop, and synced.
I can browse the offline folder fine when disconnected using file explorer, but when I try to open the Word/PPT files shown in the explorer by double clicking (launching the app) I get "Access Denied.  Contact your administrator" from the app (Word/PowerPoint).
The files and folders on the server are all set for full control by everyone.
The share on the server grants full control to this user.
Strangely, if I create a notepad TXT file in that same folder then I can open it fine from offline folder using NOTEPAD, sync the file, etc.  All great.  But MS Office apps fail to open office files only when offline.  (When online they work normally)
If I open WORD when offline and click file open, I can type the "\server\" into the address bar to start browsing the offline share, however, I immediately get a "Windows cannot acess \server\" error.  If I repeat the above in file explorer it works fine.
I have reformatted the offline cache and rebooted.  No difference.  I have repaired office 2016 installation.  No difference.
What is going one here?  Feels like a permissions error but I can't see it.  Why office apps can't even browse the offline file structure is beyond me.
Answer: I found a clue on a microsoft forum here.  There appears to be an issue related to pre-installed office on OEM computers, combined with joining a domain after office is installed.
Repairing office is not sufficient.  You have to completely remove office, then reinstall.  After that offline files work fine with office.


Comparing the results of multiple regressions of the sample sample for different year

Question: For a period of ten years, I have to identify, if there are timely variations of impact of the independent variables on the dependent variable.
So far, I have run an RE regression for the entire period. But now I have to identify variatins over time. My approach is to run one multilinear regression for the sample for each year from 2011 to 2021. Then, I would compare the coefficients and intercepts in a scatterplot and graph to depict their varying impact over time.
Does this make sense? Thank you already for your help!
I use Stata and Excel and only have basic experience.

I have panel data for ten years (2001-2011), then CSR strategy score is my dependent variable and I would like to understand the impact of different independent variables on the CSR strategy score over time.
Would I then create a dummy for each year and what do the interaction coefficients tell me?

This is what I have done so far. But I dont know what the coefficients of the year tell me
Comment: It sounds like you have panel data, but can you clarify your data structure and specification? The easiest thing would be to add year dummies and year-x interactions to the RE model and test that the interaction coefficients are jointly zero.
Comment: Unlike forum-style discussion sites, Cross Validated
threads do not consist of a sequence of posts forming a
conversation between the original poster and the
answerers. We use a Q&A style where the question is posted
once at the top, and is updated (using the "edit" button)
where necessary for clarification. Sometimes
it makes sense to ask a new, follow-up question instead of
editing the old one.
Please don't use the "answer" space to post clarifications
to your own questions
- have a look at the [tour] to understand how our site
works.
Answer: Here's an example where I have a dataset of 49 pigs (indexed by $i$) whose weights are observed over 9 weeks (indexed by $t$). I simulated an experiment by having some pigs put on more weight (see code below). While all pigs put on kgs over time, the yellow line looks a bit steeper:

Do the two lines really have different slopes? The RE model is
$$E[\mathtt{weight_{it}} \vert t, \mathtt{treated_i} ] = \mu + \alpha_i + \delta_t + \beta \cdot \mathtt{treated_i} + \gamma_t \cdot \mathbf{I}(\mathtt{week=t}) \cdot \mathtt{treated_i} $$
Here the effect of treatment is a function of time: $$\beta + \gamma_t$$
You can test the hypothesis that effect does not vary with time by testing the joint null that $\gamma_2,\dots,\gamma_9=0$ against the alternative that they are not zero. Since we need to drop one time dummy, the effect in week 1 is not identified. This means that $\beta = (\beta_T + \gamma_1)$ and everything will be relative to the impact in week 1.
Here's the Stata output:
<code>. capture ssc install coefplot

. webuse pig, clear
(Longitudinal analysis of pig weights)

. xtset id week

Panel variable: id (strongly balanced)
 Time variable: week, 1 to 9
         Delta: 1 unit

. generate treated = mod(id,2)

. replace weight = weight*(1 + .029*week/9) if treated == 1
(216 real changes made)

. xtreg weight i.week##i.treated, re vce(cluster id)

Random-effects GLS regression                   Number of obs     =        432
Group variable: id                              Number of groups  =         48

R-squared:                                      Obs per group:
     Within  = 0.9860                                         min =          9
     Between = 0.0358                                         avg =        9.0
     Overall = 0.9327                                         max =          9

                                                Wald chi2(17)     =    6567.80
corr(u_i, X) = 0 (assumed)                      Prob > chi2       =     0.0000

                                    (Std. err. adjusted for 48 clusters in id)
------------------------------------------------------------------------------
             |               Robust
      weight | Coefficient  std. err.      z    P>|z|     [95% conf. interval]
-------------+----------------------------------------------------------------
        week |
          2  |   6.833333   .2480495    27.55   0.000     6.347165    7.319501
          3  |   13.85417   .4551682    30.44   0.000     12.96205    14.74628
          4  |   19.47917   .4884237    39.88   0.000     18.52187    20.43646
          5  |   25.45833   .6543407    38.91   0.000     24.17585    26.74082
          6  |   31.60417   .6799763    46.48   0.000     30.27144     32.9369
          7  |   37.41667   .8166819    45.82   0.000       35.816    39.01733
          8  |   44.20833   .9016777    49.03   0.000     42.44108    45.97559
          9  |   49.85417   1.079434    46.19   0.000     47.73852    51.96982
             |
   1.treated |   .7066298   .7226836     0.98   0.328    -.7098042    2.123064
             |
week#treated |
        2 1  |  -.0211066   .3319502    -0.06   0.949    -.6717171     .629504
        3 1  |   .2761475   .6378184     0.43   0.665    -.9739536    1.526249
        4 1  |   .2849352   .6875297     0.41   0.679    -1.062598    1.632469
        5 1  |   .0804423   .9307069     0.09   0.931     -1.74371    1.904594
        6 1  |   .6581483   .9600435     0.69   0.493    -1.223502    2.539799
        7 1  |   1.376338   1.145815     1.20   0.230    -.8694176    3.622095
        8 1  |   1.860593   1.295432     1.44   0.151    -.6784076    4.399593
        9 1  |   2.806245   1.604311     1.75   0.080    -.3381472    5.950638
             |
       _cons |   24.70833   .4370002    56.54   0.000     23.85183    25.56484
-------------+----------------------------------------------------------------
     sigma_u |  3.9696885
     sigma_e |   2.118182
         rho |  .77838142   (fraction of variance due to u_i)
------------------------------------------------------------------------------

. estimates store re_model

. testparm week#treated

 ( 1)  2.week#1.treated = 0
 ( 2)  3.week#1.treated = 0
 ( 3)  4.week#1.treated = 0
 ( 4)  5.week#1.treated = 0
 ( 5)  6.week#1.treated = 0
 ( 6)  7.week#1.treated = 0
 ( 7)  8.week#1.treated = 0
 ( 8)  9.week#1.treated = 0

           chi2(  8) =    8.06
         Prob > chi2 =    0.4272

. coefplot re_model, keep(*.week#1.treated) xline(0) label ///
> title("p-value = `=r(p)'*") ///
> note("*The p-value for the null that all time x treated  effects are zero again alternative that they are all not equal to zero.")
</code>
Here's the graph of the week x treatment interactions ($\gamma_2,\ldots,\gamma_9$):

Though there is a suggestive trend of bigger effects over time, the individual confidence intervals cover zero. Hence, none of the estimated time x treatment effects is statistically distinguishable from zero. The joint p-value that they all zero is 0.43, so we would not reject the joint null either.
The coefficients on week dummies capture the fact that pigs gain weight over time (the $\delta_t$s).
You have multiple covariates, but the idea is the same as with one. You may want to correct your inference for multiple hypothesis testing since you will be testing many parameters.


What is the exact difference between Rack and Rails Metal in Ruby on Rails

Question: I am newbie to Rack and Rails metal, can anyone tell me which situation has to use which?. According to my understanding both Rack and Metal to filter/bypass http request and response. Need a better clarification, when to use what?
Thanks in advance!!!
Answer: As far as I know Rails Metal has been removed from Rails 3 a long time ago. Basically it used to be a thin wrapper around Rack that could act more like an endpoint rather than a filter (which is usually the case with Rack middleware). Check this post for a more detailed explanation: http://jnewland.github.io/articles/2008/12/16/rails-metal-a-micro-framework-with-the-power-of-rails-m/
Nowadays, as an alternative, what you can use is ActionController::Metal which is  a very lightweight controller that can provide very fast responses without offering many of the "cool" Rails stuff.
As far as Rack is concerned it is basically:

a minimal interface between webservers supporting Ruby and Ruby frameworks.

So it basically helps standardize the communication between any webserver that supports Ruby with any possible Ruby web framework.
Here is a nice schematic representation of what Rack does taken from Passenger's docs


combinatorics implementation in real life problems

Question: How many ways there are to organize $7$ men in a row, if two insist on not standing next to each other? How do I approach this?
Answer: Hint: Answer = (All number of ways) $-$ (The ways where the two are next to each other).
Comment: This is just what I was thinking. (+1)
Answer: There five positions next to each other: $\;1-2,2-3,3-4,4-5,5-6\;$ (times two, as two people can interchange places with each other) , and for each of these there are $\;4!\;$ permutations for the other four men. You want all the possible arrangements except the ones described above...
Comment: Well put: helps explain the logic! +1
Comment: Don't forget the $2!$ permutations of the 2 men standing next to each other.
Comment: Indeed so, @Geoffrey. Thanks.
Answer: There are a total of $7!$ ways to organize the $7$ men in a row with no restrictions. Now we must count all the ways in which $2$ specific men stand next to each other, say person $x$ and person $y$. Treat these $2$ men as a single person. We can place these $2$ men in $2\cdot{6\choose 1}$ ways. We multiply by $2$ because we can have their order switched ($xy$ or $yx$). Now we will fill in the remaining $5$ places with the remaining $5$ men in $5!$ ways. Thus we can organize $7$ men in a row where $2$ men refuse to stand next to each other in $7!-2\cdot{6\choose 1}\cdot5!$ ways.
Comment: Im not sure I got you correctly but my line of reasoning goes like this: 7! is number of options to organize the 7 men. 6! is the options we have if we wish to organize 6 men in a row, if we treat 2 as one. taking into account internal order between the two we must double that by 2! Finally we must disgard all these options which would yield 7! - 6!*2! .
Comment: We have $7!$ ways to order the men with no restrictions. If we treat $2$ men as a single person we have to count all the ways we can place these $2$ men. There are ${6\choose 1}$ positions for them, but we have to take into consideration each mans position, so $2\cdot {6\choose 1}$ ways to order these two men. Then we fill in the remaining $5$ men with no restrictions for $5!$. Now we apply the Subtraction Principle and get the desired result.


esbuild import css as a string

Question: I am using vite to build a component library. I use css?inline like this
import otherStyles from './bar.css?inline' // will be available as a string

And use the string to construct stylesheets in the component. see here
Now I made a build script with esbuild. But can't seem to get this inline css to work. Esbuild parses the import but makes an external css.
I know vite (dev env) is based on esbuild, so it should be possible to let esbuild do inline css parsing. Can't find it in the docs, can't find a plugin that does this either.
Comment: you probably need to create a custom plugin, see this [article](https://dev.to/rxliuli/using-the-esbuild-plug-in-mechanism-to-achieve-the-desired-functionality-4fh9) and scroll to "Binding text files via ?raw" which should be similar to "?inline".
Answer: https://github.com/claviska/esbuild-plugin-inline-import
Usage:
import string from 'inline:./path/to/file.ext';

f.e.
import cssCode from 'inline:./path/to/style.css';

esbuild import css as a string


Bounded set & outer measures

Question: Let $\mu: P(\mathbb R) \rightarrow [0, \infty]$.
$\mu(A)$ is $0$, if $A$ is bounded, $1$ if $A$ is not bounded.
Is this $\mu$ an outer measure?
($\mu(\emptyset) = 0$ is clear, but what about the subadditivity and monotonity? )
Comment: Can you show your attempt please?
Comment: Yeah, I think it is an outer measure, because $\mu$ is monotone (takes only value 0 or 1) and also subadditive.
Answer: It is not an outer measure.
Take $A_n=[-n,n]$
Then $1=\mu^*(\Bbb{R})=\mu^*(\bigcup_nA_n)>0=\sum_n \mu^*(A_n)$
Comment: Thanl you very much for this answer! What about the following correction: $\mu(A)$ is 0, if $A$ is empty, $\mu(A)$ is 1, if $A$ is non-empty and bounded and $\mu(A) = \infty$ if $A$ is unbounded. This should be an outer measure, right?
Comment: @StMan  then that  is an outer measure...

Bounded set & outer measures


iOS disable autorotate but adjust according to orientation

Question: Can somebody explain how Apple is handling autorotation in the default camera app?

Apple doesn't enable rotation in actual sense, but understands that the device has rotated.
It then changes the orientation of the UIControls on the screen and accommodates them to the new orientation, but the actual view doesn't autorotate.

I trying to fiddle with the iOS camera for a new app and have scratched my head whole day trying to understand if they are playing around with a view hierarchy or if they are handling custom notifications but I cannot understand.
I don't want auto-rotation; I simply want to know if user rotated his/her device - pretty much how Apple implements in their native camera app (with or without rotation disabled).
EDIT: Is there no other way to do it without Accelerometer?
Comment: When is orientation locked, iOS will report the last supported locked orientation. However, I believe it's possible to watch UIAccelerometer which reports regardless of orientation lock.
Comment: `UIDeviceOrientationDidChangeNotification`, https://developer.apple.com/library/ios/documentation/uikit/reference/UIDevice_Class/Reference/UIDevice.html
Comment: Have a look at this: http://stackoverflow.com/a/12086463/1019630
Comment: possible duplicate of [Detecting iOS orientation change instantly](http://stackoverflow.com/questions/12085990/detecting-ios-orientation-change-instantly)
Comment: "(with or without rotation disabled)"; `UIDeviceOrientationDidChangeNotification` does not work with rotation lock enabled. Please read.
Comment: Thanks. Looks like that's the only way.
Answer: As suggested by comments and by browsing throw the interwebs, handling this through the accelerometer is the only possible solution.


Maximising area of a pentagon given a fixed perimeter

Question: ABCDE is a pentagon of fixed perimeter P cm. Its shape is such that ABE is an equilateral triangle and BCDE is a rectangle. If the length of AB is x cm, find the value of P/x for which the area of the pentagon is the maximum.
This question is in a chapter dealing with calculus and maxima and minima. Someone posted a similar question but the answer offered used LaGrange multipliers, of which I know nothing.
I have drawn the following diagram.

I have said:
Area = ABE + BCDE
$= \frac{1}{2}x(x^2 - \frac{x^2}{4})^{1/2} + xy$
$P = 2y + 3x$
So $y = \frac{P - 3x}{2}$
I now have a formula for the area in terms of P and x:
Area = $\frac{1}{2}x(x^2 - \frac{x^2}{4})^{1/2} + x(\frac {P - 3x}{2})$
I have tried differentiating this but it becomes very messy and I am not sure I am on the right track. Can anyone help?
I am self-taught.
Comment: You should simplify your expression further before differentiating. $(x^2 - x^2/4)^{(1/2)} =\sqrt 3 x/2$, for instance.
Comment: Make it into a simple quadratic expression.
Comment: Thank you for these helpful suggestions.
Answer: $P = 3x + 2y \implies y = \frac{P - 3x}{2}$
Pentagon area $A = \frac{1}{2} \times \frac{\sqrt3 x}{2} \times x + xy$
$A = \frac{1}{2} \times \frac{\sqrt3 \, x}{2} \times x + x \times \frac{P - 3x}{2}$
At extrema, $\frac{dA}{dx} = \frac{\sqrt3 \, x}{2} + \frac{P}{2} - 3x = 0$
That gives us $\frac{P}{x} = 6 - \sqrt 3$


How do I print SQL syntaxed code as string in Python?

Question: So I need to print in console this:
print(f"INSERT INTO TABLE{i+1} ({fin_prnt[i].keys()[1:-1]})")
but PyCharm keeps highlighting INSERT INTO as SQL syntax and it produces an error when executing. Is there a way I could print that paragraph as string in console output?
Thanks
Comment: show more code - where `i` comes from? what is `fin_prnt` ?
Comment: try this: print('INSERT INTO TABLE{0}'.format(fin_prnt[i].keys()[1:-1] + 1))
Answer: Have you changed any settings in PyCharm?
The print works for me fine (Version 2021.2).


CppFlow on windows 10

Question: I found this interesting project on Github (https://github.com/serizba/cppflow)
Which is a c++ wrapper for the tensor api written in C.
However I have some issues when installing it..
I have installed a c++ compiler, but when I try to build it in visual studio, I get the following error:
cannot convert from 'T *' to 'std::vector>'
Does anybody have experience with this wrapper or recogninces the error message? My initial though was that I am using the wrong c++ compilier.
Comment: Impossible to diagnose the compiler error message without knowing what line of code it relates to.
Comment: I see from the project that it requires C++17. Have you enabled C++17 in your visual studio compilation?
Comment: Where did you see that? Anyhow thanks! (from the syntax or something?)
Comment: I have enabled c++17 under the project settings (ISO C++17 Standard (/std:c++17)). However when I debug I use "Local Windows debugger" I only assume that is c++17 since the project is defined for 17?
Comment: "return { T_data, T_data + size };" Gives two error messages:

1: Conversion from 'T *const ' to 'bool' requires a narrowing conversion.
2: Conversion from 'T *' to 'bool' requires a narrowing conversion.
Comment: I saw the setting in this file https://github.com/serizba/cppflow/blob/master/examples/load_model/CMakeLists.txt (line 4).
Comment: `/std:c++17` is the setting you (apparently) need.
Comment: Which is the same that I got, but I still get the errors..
Comment: Which source file does that line appear in? Just quoting one line is not enough context to understand the error.
Comment: Tensor.cpp (line 146). But the template function is used on 208 (the one that causes the issue). When I comment that one, I get several other issues.
Answer: Well I'm not enough of a language lawyer to know where the fault lies (the code or the compiler) but it's clear that the intent of the line of code causing the problems is this
<code>return std::vector<T>(T_data, T_data + size);
</code>
With that more old-fashioned style of code it compiles for me.
Comment: @AtleKristiansen That's a different topic, so if you need help create a new question. I just editted the `#include` directives until it compiled. But obviously you should do the right thing and edit your project settings to reflect the location of your tensorflow folder. It shouldn't matter where you put it, the important thing is to tell your compiler where you put it.
Comment: Hmm, that error was removed, however I got some others. Where did you put the tensorflow folder?
Comment: Did you make it run on Windows? If so, can you take a look at https://stackoverflow.com/questions/56798707/unable-to-compile-c-with-external-dependencies
Answer: I had the same error, i found that the bool type doesn't seem to work for the moment. Take a look to the bottom of Tensor.cpp, and check that all the template with bool type are commented.

CppFlow on windows 10


Edit just for earning reputation?

Question: I don't know I am wrong or right I just need to share my thoughts.
Today I found that one user have continuously made an edit in questions and edits are also approved. Edits are very minor just for earning reputations, there is no meaning of such  edits.
Below is some links that you may check
Magento 2 - Free Shipping / Drop Off (shipping) charge based on specific zip codes
Magmi not saving checked options on mac
What is a good method to handle suspected fraudulent transactions with Authorize.net?
What is 'best practice' when setting anchor on multi-level categories?
Conflicts in where clause with ambiguous column names
Change the template inheritance hierarchy
Multiple local.xml layout files in a package
Onepage checkout, or not Onepage checkout
some of them are 5 year old question, and in most of this edits there is no meaning or usefulness.
should we really allow such things in the community ?
Should we really allow such edits ?
Please correct me here.
Thanks.
Answer: I'd even consider these edits harmful. They are using quotes to highlight random paragraphs which are not remotely quotes.
What to do in such a case? Flag one of the answers/questions for moderator attention and mention that this particular user is vandalizing in their edits. You don't need to include a whole list of edits, the moderators can see the edit history for any user.
I rolled back the edits. Please be more careful when reviewing, if you read this:

Rama Chandran M reviewed this 4 hours ago: Approve
Prince Patel reviewed this 4 hours ago: Approve
saravanavelu reviewed this 3 hours ago: Approve
Rama Chandran M reviewed this 4 hours ago: Approve
saravanavelu reviewed this 3 hours ago: Approve
Rama Chandran M reviewed this 4 hours ago: Approve
Prince Patel reviewed this 2 hours ago: Approve
Murtuza Zabuawala reviewed this 2 hours ago: Approve
Qaisar Satti reviewed this 2 hours ago: Approve
Prince Patel reviewed this 2 hours ago: Approve
Rama Chandran M reviewed this 2 hours ago: Approve
Qaisar Satti reviewed this 2 hours ago: Approve
Rama Chandran M reviewed this 4 hours ago: Approve
Jai reviewed this 4 hours ago: Approve

Friendly formatting reminder
> for quotes, `` for code, */** for highlighting
Comment: I approve of what Fabian said. Just for the record, the user has been notified to stop this practice.
Comment: This is becoming a serious issue in my assessment. You'll find users such as Teja bhagavan Kollepara continually spamming edits on out of date answers/questions causing them to resurface. Users engaging in these activities should just have their accounts deleted.
Comment: @Eirik Teja isnt a good example (imho), I know he does a lot of minor edits (e.g. replace "magneto" with "magento") ... I agree with this and it takes no time to review, since he already was above 2k REP and can edit w/o reviews. Sometimes it's bit anoying to have some old quesetions bumped, but it doest hurt.
Comment: It's usually missing write permission, but a missing directory may cause it as well, so the answer is valid. They don't explain why, but probably just don't know. Still it can be helpful, although it is not a very good answer. Let the votes decide I'd say, nothing to delete.
Comment: Thanks @FabianSchmengler for advise.I have undo the delete
Comment: QaisarSatti, PrincePatel, RamaChandranM: Thank you for your consideration!
Comment: Any words about this? https://magento.stackexchange.com/review/low-quality-posts/121464 ... *The issue was missing media folder.* Isnt it a possible answer? @Marius
Comment: @sv3n I didn't delete that. Also don't mix issues.
Comment: Just mentioned you, to check this ;) Didnt want to open a new question and thought it fits to this.
Comment: @sv3n,can u please tell me why you are  thought that that this is  an  answer. My point of view, i not thought that one single line is give  that answer. user should be more details. marius &Fabian what your thought about this?
Comment: @AmitBera as said above, the 2nd sentence is answer to me. Not a good on, but it's an answer. :)
Comment: @FabianSchmengler Thanks for your advice i will be more careful next time.
Comment: @FabianSchmengler Thanks for the advice. Take care next time.
Comment: Thanks for comments. Next time I will look carefully the edit and low-quality post.
Comment: @sv3n can't we do something to avoid such ting?
Comment: @Magento2Learner avoid which kind of things? The edits you have posted in your question are useless. They should be reported (here) so a moderator can contact the person to stop this. Edits that improve grammer/spelling (like Teja does) or improve tags are useful (imho), even if they bring up old or closed questions.

Edit just for earning reputation?


Existence of entire function (Rosay-Rudin's paper)

Question: I am studying a paper by Rosay and Rudin, titled Holomorphic maps from $\mathbb{C}^n$ to $\mathbb{C}^n$, and at some point they assume the existence of an entire function $f$ in $\mathbb{C}$ satisfying the following properties:
$e^{f(0)} = \frac{1}{\alpha}$, $f'(0) = 0$, $f(1) = 0$, $f'(1) = \frac{1+\alpha^2}{1-\alpha^2}$,
where $\alpha\in\mathbb{C}$, $0<|\alpha|<1$. I do not think that they are wrong but I can not find such an entire function. Any ideas?
Answer: It seems to me like they only specify $f(0),f'(0),f(1),f'(1)$. Getting those 4 conditions down can be done in multiple ways but perhaps most obvious way is just taking a polynomial of order 3.
If you don't know how to do that look at Lagrange interpolation.


sbt publish produces jar with too many folders in the path => unresolved dependency

Question: I'm trying to test a project, so I did sbt publish-local (here's the project's build file: build.sbt).
I expected that a jar be produced with the path:
/Users/julianpeeters/.ivy2/local/com.oysterbooks/scavro_2.10/0.9.0/jars

But instead I got:
/Users/julianpeeters/.ivy2/local/com.oysterbooks/scavro/scala_2.10/sbt_0.13/0.9.0/jars

1) How come the two extra directories scala_2.10 and sbt_0.13 were generated?
2) How can I reference the jar as a sbt libraryDependency? For example, "com.oysterbooks" % "scavro" % "0.9.0" wont work.
Currently my workaround is moving the jar into the scavro directory manually after publishing.
Thanks
Comment: what version of `SBT`?
Comment: for part #2, you need to either include the `_2.10` suffix or change to using a `%%` (see: http://www.scala-sbt.org/0.12.2/docs/Detailed-Topics/Cross-Build.html#using-cross-built-libraries)
Comment: Thanks for the response. `SBT` version is `0.13.8` (for the project being published, and the test project, though my launcher is `0.13.6`)
Comment: for part #2, those methods would work for my expected path, but they don't work my actual path.
Answer: The deliberate Scala/SBT-version folders you are seeing in the published ivy directory is a result of the sbtPlugin := true command.
Comment: Which means that `Defaults.sbtPluginExtra("com.oysterbooks" % "scavro" % "0.9.0", "0.13", "2.10")` is how I should represent it as a dependency. Thank you very much.


Can a smartphone's accelerometer be used for tuning instruments?

Question: Similar to a clip-on tuner, the vibrations of the instrument itself will be detected instead of its sound.
Procedure:

Phone is held where it can sense vibrations of the instrument
Play the instrument
Tune according to vibration Hz displayed.

Will this be reliable?
Comment: This seems like a tech question rather than a musical one, and I imagine the answer is that phone accelerometer's are nowhere near that sensitive (or if they were, it might vary by model). After all, a device which measures how it is vibrated by sound waves... is a microphone, and they all have one of those.
Comment: @AndyBonner "Phone is held where it can sense vibrations of the instrument" doesn't really rule out pressing the phone against instrument.
Comment: I'm voting to close this question because it's about an intersection of acoustics and technology, not music.
Comment: Getting a clip on transducer that plugs into your phone seems like an easier way.
Comment: I will say, though: There's an underlying confusion. What's proposed is *not* like a clip-on tuner; the clip-on is a type of pickup, measuring the vibrations of a solid object. If you hold something near a sound source, you're measuring sound waves in air. This will almost always be *less* reliable, simply because you're likely to get contamination from other sound sources.
Comment: Why not just try it out?  I"m not aware of any tool that will report the accelerometer values at anything close to the 2 - 10 kHz rate you'd need and I rather doubt the accelerometer itself responds at that rate.
Comment: @CarlWitthoft as an example, the Bosch accelerometer datasheets under https://www.bosch-sensortec.com/products/motion-sensors/accelerometers/ list bandwidths from 800 Hz to 1600 Hz, which is already enough open guitar strings. The BMA400 even has antialiasing filter.
Answer: Maybe, but not for long. At the time of writing this, the maximum accelerometer sampling rates are unspecified and may extend to audio frequencies, but Android 12 will limit the sample rate to 200 Hz to prevent using the accelerometer as microphone. This prevents the accelerometer from detecting frequencies above 100 Hz, or G2.
Comment: A nit: yes that's the Nyquist limit, but when you add the digital sampling quantization of amplitude the limit gets even lower.
Comment: @CarlWitthoft do you mean antialiasing filter? A properly designed ADC would filter out frequencies above Nyquist frequency before sampling and the filter amplitude response would start dropping well below it, but I haven't seen any sensor actually do that. I don't really understand how quantization would affect frequency response.


calling an environment variable in a ps-watcher config file

Question: I am trying to use ps-watcher to monitor my system and make sure a given number of worker threads are working on a task. If I hard code the number of workers into the config file for ps-watcher, it works great. However I would like the number of workers to be pulled from an environment variable named WORKERS. This seems simple, but has proven to be a pain.
Here's an example config file that works:
[myProg]
  trigger = $count<5
  action = /home/ubuntu/startWorkers.sh

I pulled the following from the man for ps-watcher:

This parameter specifies the condition
  on which a process action is fired.
  The condition is evaluated with Perl
  eval() and should therefore return
  something which is equivalent to
  ``true'' in a Perl expression.

Which makes me think I should use $ENV{VARIABLE} as I would in Perl. So I tried the following:
[myProg]
  trigger = $count<$ENV{WORKERS}
  action = /home/ubuntu/startWorkers.sh

to which my ps-watcher log recorded the following:

Use of uninitialized value in
  concatenation (.) or string at (eval
  6) line 1 (#1)
      (W uninitialized) An undefined value was used as if it were already
      defined.  It was interpreted as a "" or a 0, but maybe it was a mistake.
      To suppress this warning assign a defined value to your variables.
      To help you figure out what was undefined, perl will try to tell you
      the
      name of the variable (if any) that was undefined. In some cases it cannot
      do this, so it also tells you what operation you used the undefined value
      in.  Note, however, that perl optimizes your program and the
      operation displayed in the warning may not necessarily appear literally in your
      program.  For example, "that $foo" is usually optimized into "that "
      . $foo, and the warning will refer to the concatenation (.) operator,
      even though there is no . in your program.

I'm at a bit of a loss. Any help would be appreciated.
Comment: It seems like this example gives hints... but I can't grok it: http://ps-watcher.cvs.sourceforge.net/viewvc/ps-watcher/ps-watcher/samples/port-watch.ini?view=markup
Answer: Maybe single quotes around the environment variable?
$ENV{'WORKERS'};

Comment: I was expecting it to be something with escaping or quoting. Unfortunately the single quotes didn't change anything.
Comment: Thanks for the help! The single quotes were needed, but I also had issues with the environment variable not being exported.
Answer: I agree with the single quote idea, but also double-check that the variable is actually exported by doing a print "$ENV{'WORKERS'}\n"; before the eval.  Perhaps you are not exporting the variable into the children.
Comment: Also do a print of $trigger or whatever you are evaluating to double-check the resulting perl code is what you want.
Comment: the pain I'm having is that this is a configuration file, not a proper Perl script... although it is being parsed by Perl. I wish I could throw debugging code in there and test it, but I can't. As I think about it, I suspect you are right about this being an export problem. But I'm not sure how to verify. I may have to start digging through the source for ps-watcher.
Comment: @JD Long: Then run `printenv > /tmp/x` in an evaluated context, or `ps axewww` while the program is running, to check for the environmental variable.
Comment: hey thanks. I slipped a printenv in there in ticks and it evaluated. And I can see that the environment variable is not being exported. Now to figure out why.
Comment: @JD Long: Please upvote and accept, then.


How do I combine multipe hook form alter functions

Question: How can I combine multiple functions inside one hook form alter. If I try to use them separate I get the error Cannot redeclare mymod_form_alter()previously declared.
i want to combine this function
use Drupal\Core\Form\FormStateInterface;

 function mymod_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
 if ($form_id == 'node_page_form' || $form_id == 'node_page_edit_form') {

$form['uid']['widget'][0]['target_id']['#required'] = TRUE;
 }
   return $form;
}

and this function
use Drupal\Core\Form\FormStateInterface;

function mymod_form_alter(&$form, &$form_state, &$form_id) {
$form['field_short_description']['widget']['#after_build'][] =

'_allowed_formats_remove_textarea_help';
}

function _allowed_formats_remove_textarea_help($form_element, FormStateInterface $form_state)

{

  if (isset($form_element[0]['format'])) {
    // All this stuff is needed to hide the help text.
    unset($form_element[0]['format']['guidelines']);
    unset($form_element[0]['format']['help']);
    unset($form_element[0]['format']['#type']);
    unset($form_element[0]['format']['#theme_wrappers']);
    $form_element[0]['format']['format']['#access'] = FALSE;
  }
  return $form_element;
}

Comment: This needs to be tagged in Drupal 8
Answer: You can do switch statements based on the form ID:
function hook_form_alter(array &$form, FormStateInterface $form_state, $form_id)
{
  switch($form_id)
    case 'form_id_1':
      // Alter the form with an id of form_id_1
      break;
    case 'form_id_2':
      // Alter the form with an id of form_id_2
      break;
    case 'form_id_3':
      // Alter the form with an id of form_id_3
      break;
}