APÍ django-storages dropbox erro url pattern

Question: Eu estou utilizando a seguinte API:
https://django-storages.readthedocs.io/en/latest/backends/dropbox.html
Eu tenho exatamente tudo configurado, desde a lib instalada até as configurações do settings.py.
A lib 'storages' no INSTALLED_APPS e as três variáveis de conexão com o dropbox:
DEFAULT_FILE_STORAGE = 'storages.backends.dropbox.DropBoxStorage'
DROPBOX_OAUTH2_TOKEN = 'meu_token'
DROPBOX_ROOT_PATH = '/media/'

Eu quero que os campos FileField e ImageField façam upload de uma imagem ou arquivo e este seja salvo na pasta /media/ do projeto e do dropbox, mantendo a imagem em produção, tendo a App criada e configurada para ser app_folder.
Se eu retirar as três variáveis de configuração do dropbox e tentar modificar ou adicionar uma imagem pelo django admin é possível, porém, quando retorno as variáveis e tento novamente, aparece o seguinte erro:
  ValidationError at /admin/catalog/product/6/change/
'C:/media/products/cortina-city.jpg' did not match pattern '(/(.|[\r\n])*|id:.*)|(rev:[0-9a-f]{9,})|(ns:[0-9]+(/.*)?)'

Dá erro também no dropbox.py da lib:
C:\Users\evert\Desktop\Synth\SynthDev\myenv\lib\site-packages\storages\backends\dropbox.py in exists
                return bool(self.client.files_get_metadata(self._full_path(name))) ...
        C:\Users\evert\Desktop\Synth\SynthDev\myenv\lib\site-packages\dropbox\base.py in files_get_metadata
                                       include_property_groups) ...
        C:\Users\evert\Desktop\Synth\SynthDev\myenv\lib\site-packages\dropbox\files.py in __init__
                self.path = path ...
        C:\Users\evert\Desktop\Synth\SynthDev\myenv\lib\site-packages\dropbox\files.py in path
            val = self._path_validator.validate(val) ...
        C:\Users\evert\Desktop\Synth\SynthDev\myenv\lib\site-packages\dropbox\stone_validators.py in validate
                                      % (val, self.pattern))

Eu entendo que não está identificando o padrão do get da url. Imagino que o C: não deve ir junto na string e está indo, ou seja, 'C:/media/products/..".
Como resolver isso?
Comment: Everton , como esta seu arquivo urls.py ?
Comment: Tenho a configuração:
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Answer: Pessoalmente eu acho que lidar com os arquivos estáticos no ambiente de produção é uma das coisas mais complicadas. Como a própria documentação diz:

Claro, como todas as tarefas de implantação, os problemas estão nos detalhes. Cada configuração de produção será um pouco diferente, então você irá precisar adaptar o esquema básico para atender suas necessidades.

Como não vou conseguir reproduzir seu erro com facilidade, lhe dou algumas dicas de segurança:

Verifique para onde suas variáveis de configuração como STATIC e MEDIA estão apontando. Abas devem estar apontando para o um caminho no root do seu projeto.
Verifique no momento em que esta subindo os arquivos qual o local desejado.
FileField(upload_to='media/', null=True, blank=True) #exemplo

Verifique sua urls.py. Você mencionou que esta usando:
 if settings.DEBUG:
     urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Essa configuração seta seu 'static' para ser uma combinação da sua STATIC_URL e STATIC_ROOT então certifique-se que os dois também estão devidamente configurados em seu settings.py
Usar:
 url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),

Embora não seja recomendável, lhe ajudará também a mapear seus arquivos
estáticos para suas rotas.
Por fim rode python manage.py collectstatic e verifique se seus arquivos estáticos estão sendo devidamente importados para o dropbox. Tenha em mente que quando rodar o collectstatics todos os seus arquivos estáticos terão de ir para o caminho definido no seu STATIC_ROOT. Tendo atingido essa meta você deve estar bem pois o django-storages deve encarregar-se de servir esses arquivos.
Comment: Otávio, obrigado pelas excelentes dicas, porém, eu tenho tudo configurado e aparentemente está ok.

No meu settings.py: MEDIA_URL = '/media/'; STATIC_URL = '/static/'; MEDIA_ROOT = os.path.join(BASE_DIR, 'media'); STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
Comment: O atributo imagem está assim: image = models.ImageField('Imagem', upload_to='products', blank=True, null=True). Dessa forma será criada uma pasta 'products' dentro de media. Como funciona normalmente local.


Core doesn't update with Composer

Question: We use commands:
composer outdated drupal/*
drupal/core 8.6.10 8.6.13 Drupal is an open source content management platform powering millions of websites and applications.

It does show 8.6.13.
We run either composer update drupal/core --with-dependencies or composer update drupal/core:8.6.13 webflo/drupal-core-require-dev --with-dependencies and we get nothing, it does update some dependencies and that is it. Our site is built with composer.
Here's the rest of the log:
composer update drupal/core:8.6.13 webflo/drupal-core-require-dev --with-dependencies
> DrupalProject\composer\ScriptHandler::checkComposerVersion
Package "drupal/core:8.6.13" listed for update is not installed. Ignoring.
Dependency "drupal/core" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "twig/twig" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 0 installs, 5 updates, 0 removals
  - Updating symfony/css-selector (v3.4.22 => v3.4.23): Loading from cache
  - Updating symfony/phpunit-bridge (v3.4.22 => v3.4.23): Downloading (100%)
  - Updating symfony/dom-crawler (v3.4.22 => v3.4.23): Downloading (100%)
  - Updating symfony/browser-kit (v4.2.3 => v4.2.4): Downloading (100%)
  - Updating squizlabs/php_codesniffer (3.4.0 => 3.4.1): Downloading (100%)
Package phpunit/phpunit-mock-objects is abandoned, you should avoid using it. No replacement was suggested.
Writing lock file
Generating autoload files
> DrupalProject\composer\ScriptHandler::createRequiredFiles
root@dev /var/www/example.com # composer update drupal/core
> DrupalProject\composer\ScriptHandler::checkComposerVersion
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Package phpunit/phpunit-mock-objects is abandoned, you should avoid using it. No replacement was suggested.
Generating autoload files
> DrupalProject\composer\ScriptHandler::createRequiredFiles
root@dev /var/www/example.com # drush status
 Drupal version   : 8.6.10
 Site URI         : default
 DB driver        : mysql
 DB hostname      : localhost
 DB port          : 3306
 DB username      : root
 DB name          : example
 Database         : Connected
 Drupal bootstrap : Successful
 Default theme    : seven
 Admin theme      : seven
 PHP binary       : /usr/bin/php7.2
 PHP config       : /etc/php/7.2/cli/php.ini
 PHP OS           : Linux
 Drush script     : /usr/local/bin/drush
 Drush version    : 9.4.0
 Drush temp       : /tmp
 Drush configs    : /var/www/example.com/vendor/drush/drush/drush.yml
                    /var/www/example.com/drush/drush.yml
 Install profile  : standard
 Drupal root      : /var/www/example.com/web
 Site path        : sites/default
 Files, Public    : sites/default/files
 Files, Temp      : /tmp

Drush is still reporting 8.6.10
First time we did get the WSOD from https://www.drupal.org/project/drupal/issues/3039408 so we ran composer require twig/twig:1.37.1 to fix it.
Comment: Might be that you connected to a repo site that did not have 13 on it yet.  It was just released.  Try again later. FYI - Just updated my site with composer require drupal/core --update-with-dependencies and had no problems other than slow core download.
Comment: @CGMonroe  It doesn't update to 12 either.
Answer: So after we ran regular update (current version was 8.6.10), our website crashed. We followed this fix to recover from WSOD https://www.drupal.org/project/drupal/issues/3039408#comment-13018093
After website was restored we tried running all kinds of composer commands to update (like mentioned in question) and it would just spit out "Nothing to install or update".
Solution:

remove "twig/twig": "1.37.1", from composer.json
Run again composer update drupal/core webflo/drupal-core-require-dev --with-dependencies

Updating twig/twig (v1.37.1 => v1.38.2): Loading from cache
Updating drupal/core (8.6.10 => 8.6.13): Downloading (100%)
So, not sure what's going on.
Comment: A bug arose in Drupal 8.6.10 when Twig updated to 1.38; the fix was to `require twig/twig:1.37.1` explicitly. That's most likely why you had `twig/twig` in your composer.json, when you normally wouldn't
Comment: @Clive yes, but why are the core updates locked to certain twig version? Having that twig line prevented from updating the website.
Comment: Perhaps the fix for Drupal's integration into 1.38 wasn't backwards compatible with its integration into 1.37? I haven't checked the code to be honest. I doubt they would've done it arbitrarily though, there'll be a good reason
Comment: I think they locked it because of a breaking change that shouldn't have gone in upstream.
Comment: Wouldn't `composer why-not drupal/core:8.6.13` revealed the problem with Twig? People tend to forget that you can ask Composer why it is (not) doing stuff.
Answer: We came across the similar issue while upgrading from 8.6.10 to 8.6.13, try deleting the core and then run
composer update drupal/core --with-dependencies

It should upgrade it to 8.6.13

Core doesn't update with Composer


Picasso not loading image from http url but loads images from https url?

Question: Picasso Loads the image fine if its from a https url like: https://i.ytimg.com/vi/28uUsJ72a1A/hqdefault.jpg
Since youtube directs all traffic through https this works to:
http://i.ytimg.com/vi/28uUsJ72a1A/hqdefault.jpg
But when I use my url
http://www.example.com/images/djnsdfndsf.jpg
it redircets the link to a https version of the site and just gives a error
This is how i'm loading the images
Picasso.with(this).load(current.getImageURL()).into(ImageView);
So I tried using this:
//Below code for Picasso initializing once for the app
private Picasso picasso;
private OkHttpClient okHttpClient;

okHttpClient = new OkHttpClient();
picasso = new Picasso.Builder(this)
                .downloader(new OkHttpDownloader(okHttpClient))
                .build();

//Below code to retrieve the images whereever required on the app
picasso.with(this).load(current.getImageURL()).into(imageView)

But Above code gives cannot resolve OkHttpDownloader
Right Now I'm using compile 'com.squareup.picasso:picasso:2.5.2'
EDIT
How do I force Picasso to download it over http not https?
Comment: picasso.with(this).load(current.getImageURL()).into(**ImageView**) here ImageView is your object or your class name>>
Comment: It's the Object
Answer: HTTP requests are not allowed in API level 28+. To specifically allow HTTP requests to your domain, you must add the following file to your code.
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
    <domain includeSubdomains="true">aravind.me</domain>
</domain-config>
</network-security-config>

Add your domain name replacing aravind.me and add this file as network_security_config.xml in xml folder in resources.
android:networkSecurityConfig="@xml/network_security_config"

Add this to application tag in your manifest file.
Comment: if possible it's better to use https URL.
Answer: Just try this:

Replace http with https in your URL.

String aUrl = aImageInfo.getImage_url().replace("http", "https");

    Picasso
            .with(myContext)
            .load(aUrl)
            .placeholder(R.mipmap.place_holder)
            .error(R.mipmap.error)
            .fit()
            .into(aHolder.aImageView);

Comment: Good one! I laugh a little bit, because I arrived here after searching through Picasso library to see what is happening there, and then I saw your answer and I was like "Ok, I don't care, this is the solution" :))
Comment: hmm this wont work because the whole problem was that it is forced to use https which does not resolve, I need to force it to use http because my site does not have SSL.
Comment: Why it should work? if the server redirect to https its meaningless
Comment: While this is more like hack, but seems like this is the only simple solution. And its a pity that Picasso doesn't mention it anywhere and leave everyone struggle to find a solution. On the other hand, Android 9, i.e. API 28 and above don't allow HTTP calls without adding new libraries and more boilerplate code in your app. There are some suggestions on this page which might work but I haven't tried them, I just changed my HTTP URLs to HTTPS and it is working fine for me.
Answer: By default Picasso is using UrlConnectionDownloader. From the name you can understand that it is using HttpURLConnection which won't automatically redirect from HTTP to HTTPS (or vice versa). Following the redirect may have serious security consequences.
The way to overcome this is to use OkHttp3Downloader - OkHttp 3 downloader implementation for Picasso 2.
OkHttpClient client = new OkHttpClient();
Picasso picasso = new Picasso.Builder(context)
.downloader(new OkHttp3Downloader(client))
.build()

To use OkHttp3Downloader you have to add dependency
compile 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.1.0'

Comment: this is not working anymore.
Answer: If you want get a callback from Picasso then try the following
and onBitmapLoaded() set the bitmap to your ImageView
Picasso.with(getContext()).load(url).into(new Target() {
    @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
        // cache is now warmed up
    }
    @Override public void onBitmapFailed(Drawable errorDrawable) { }
    @Override public void onPrepareLoad(Drawable placeHolderDrawable) { }
});

Answer: you can add this to your application class:
    final OkHttpClient client = new OkHttpClient.Builder()
            .protocols(Collections.singletonList(Protocol.HTTP_1_1))
            .build();

    final Picasso picasso = new Picasso.Builder(this)
            .downloader(new OkHttp3Downloader(client))
            .build();

    Picasso.setSingletonInstance(picasso);

Answer: CustomPicasso.java
import android.content.Context;
import android.util.Log;

import com.jakewharton.picasso.OkHttp3Downloader;
import com.squareup.picasso.Picasso;

/**
 * Created by Hrishikesh Kadam on 19/12/2017
 */

public class CustomPicasso {

    private static String LOG_TAG = CustomPicasso.class.getSimpleName();
    private static boolean hasCustomPicassoSingletonInstanceSet;

    public static Picasso with(Context context) {

        if (hasCustomPicassoSingletonInstanceSet)
            return Picasso.with(context);

        try {
            Picasso.setSingletonInstance(null);
        } catch (IllegalStateException e) {
            Log.w(LOG_TAG, "-> Default singleton instance already present" +
                    " so CustomPicasso singleton cannot be set. Use CustomPicasso.getNewInstance() now.");
            return Picasso.with(context);
        }

        Picasso picasso = new Picasso.Builder(context).
                downloader(new OkHttp3Downloader(context))
                .build();

        Picasso.setSingletonInstance(picasso);
        Log.w(LOG_TAG, "-> CustomPicasso singleton set to Picasso singleton." +
                " In case if you need Picasso singleton in future then use Picasso.Builder()");
        hasCustomPicassoSingletonInstanceSet = true;

        return picasso;
    }

    public static Picasso getNewInstance(Context context) {

        Log.w(LOG_TAG, "-> Do not forget to call customPicasso.shutdown()" +
                " to avoid memory leak");

        return new Picasso.Builder(context).
                downloader(new OkHttp3Downloader(context))
                .build();
    }
}

build.gradle (Module:app)
android {

    ...

}

dependencies {

    ...

    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.1.0'
}

Usage -
CustomPicasso.with(context)
    .load("http://i.imgur.com/DvpvklR.png")
    .into(imageView);

Answer: Your url contains Https then you need to must be use https in url otherwise it will not load also you can't download image with normal http. If you want to try then just download http image using BitmapFactory.
Thanks.
Comment: So there is no possible way to use http?
Comment: No, in browser its automatically redirect http to https but in programmatic ally we need to set https.
Comment: What did you even just say here?


Error "no matching mac found" with ubuntu 10.04 and github

Question: I have a web application mounted on an old server with Ubuntu 10.04.4 LTS and for a short time I have not been able to deploy it due to a problem that occurs with the connection to github to download the code:
no matching mac found: client
hmac-md5,hmac-sha1,email@example.com,hmac-ripemd160,firstname.lastname@example.com,hmac-sha1-96,hmac-md5-96
server
email@example.com,firstname.lastname@example.com,hmac-sha2-512,hmac-sha2-256
fatal: The remote end hung up unexpectedly

The problem seems to be caused by a recent change in github that does not accept connections with old protocols, here they explain it:
https://github.blog/2021-09-01-improving-git-protocol-security-github/
This is the ssh version of my Ubuntu server:
ssh -V
OpenSSH_5.3p1 Debian-3ubuntu7.1, OpenSSL 0.9.8k 25 Mar 2009

Which by the way does not support the -Q option that is proposed in some responses to similar questions that have not helped me to solve the problem.
ssh: illegal option -- Q
usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]
           [-D [bind_address:]port] [-e escape_char] [-F configfile]
           [-i identity_file] [-L [bind_address:]port:host:hostport]
           [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]
           [-R [bind_address:]port:host:hostport] [-S ctl_path]
           [-w local_tun[:remote_tun]] [user@]hostname [command]

The ssh_config file for my server is this:
#       $OpenBSD: ssh_config,v 1.34 2019/02/04 02:39:42 dtucker Exp $

# This is the ssh client system-wide configuration file.  See
# ssh_config(5) for more information.  This file provides defaults for
# users, and the values can be changed in per-user configuration files
# or on the command line.

# Configuration data is parsed as follows:
#  1. command line options
#  2. user-specific file
#  3. system-wide file
# Any configuration value is only changed the first time it is set.
# Thus, host-specific definitions should be at the beginning of the
# configuration file, and defaults at the end.

# Site-wide defaults for some commonly used options.  For a comprehensive
# list of available options, their meanings and defaults, please see the
# ssh_config(5) man page.

# Host *
#   ForwardAgent no
#   ForwardX11 no
#   PasswordAuthentication yes
#   HostbasedAuthentication no
#   GSSAPIAuthentication no
#   GSSAPIDelegateCredentials no
#   BatchMode no
#   CheckHostIP yes
#   AddressFamily any
#   ConnectTimeout 0
#   StrictHostKeyChecking ask
#   IdentityFile ~/.ssh/id_rsa
#   IdentityFile ~/.ssh/id_dsa
#   IdentityFile ~/.ssh/id_ecdsa
#   IdentityFile ~/.ssh/id_ed25519
#   Port 22
#   Ciphers aes128-ctr,aes192-ctr,aes256-ctr,aes128-cbc,3des-cbc
#   MACs hmac-md5,hmac-sha1,firstname.lastname@example.com
#   EscapeChar ~
#   Tunnel no
#   TunnelDevice any:any
#   PermitLocalCommand no
#   VisualHostKey no
#   ProxyCommand ssh -q -W %h:%p gateway.example.com
#   RekeyLimit 1G 1h

Host *
        SendEnv LANG LC_*

Could someone help me to fix this issue considering I am tied to that server running Ubuntu 10.04.4 LTS? Thank you very much.
Comment: 10.04? Dude, upgrade the System to a supported device. As long this question is offtopic since questions should demonstrate reasonable information technology management practices
Answer: Try this
Host *
MACs hmac-md5,hmac-sha1,firstname.lastname@example.com,email@example.com,firstname.lastname@example.com,hmac-sha2-512,hmac-sha2-256


How to find whether Recordset is empty is not in VBA?

Question: I tried the following code:
rs5.Open "select Duration from onduty where User_id='" & rs1!User_id & "' and date=#" & Date & "#", cn, adOpenDynamic, adLockOptimistic

where rs5, rs1 are declared as ADODB.Recordset.
I need to find where rs5 after executing the query is empty or not.
Comment: Why didn't you read documentation? "If the data source returns no records, the provider sets both the BOF and EOF properties to True, and the current record position is undefined. You can still add new data to this empty Recordset object if the cursor type allows it." http://msdn.microsoft.com/en-us/library/windows/desktop/ms675544(v=vs.85).aspx
Comment: I am new to VB and I need to modify an earlier done project and I am appointment to that project. As the project is to be completed soon i have no time to read the documentation.
Comment: What kind of programmer are you, if you disregard documentation? What warranties can you supply to your code?
Comment: I usually read documentation and proceed further. Without documentation I wont do or proceed further. I was given a job to modify a project which was urgent and which was previously completed by some other. Almost I completed my job. Just for report generation the condition to generate the report was not working. I tried your suggestion earlier using EOF. But the mistake was at the other location in the program and debugged and finished the project.
Answer: Did you try :
If rs5.EOF Then MsgBox "null"

Comment: Yes I tried it earlier. But the mistake was in the other part of  the program which I was working. Now I corrected it.Now My program is working correctly. Any way your answer is the answer to my question. So I accept it. Thank you for answering, as if you wont answer I would think that I have used a wrong condition. Now its clear for me.


Using least squares regression for line of best fit

Question: Use the least square approximation to find the closest line (the line of "Best Fit") to the points:
$$(-6,-1), \quad (-2,2), \quad (1,1), \quad (7,6)$$
I'm attempting to use the least squares approximation formulation that is as follows:
$$A^TAx = A^Tb$$
However, I'm confused because I'm given four vectors. Does that mean I can use the first three vectors $(-6,-1),(-2,2),(1,1)$ to create my matrix A, and then use the last vector $(7,6)$ for the "$b$" value? I understand the process is very straight forward once proper substitution has been done, but I tried the method I described above and got the wrong answer.Thank you guys.
Answer: You are looking for an equation $y=mx+c$. Ideally it would pass through all of the given points: that is, you would have $-6m+c = -1$, and similarly for other points. This is a set of four equations with two unknowns $m,c$. Its matrix representation is
$$
\begin{pmatrix}
-6 & 1\\ -2 & 1 \\ 1 & 1 \\ 7 & 1
\end{pmatrix}
\begin{pmatrix}
m \\ c
\end{pmatrix}
 = \begin{pmatrix}
-1 \\ 2 \\ 1 \\6
\end{pmatrix}
$$
These are $A$ and $b$ you are looking for. Typically, the system $Ax=b$ has no solutions (there is no line through all the points); this is why  we solve $A^TAx=A^Tb$ instead, obtaining $x$ that minimizes the residual $\|Ax-b\|^2$.
Comment: thank you so much for that. That was a very helpful answer.
Answer: The trial function is
$$
  y(x) = c_{0} + c_{1} x.
$$
As noted by @user147263,you have the linear system
$$
\begin{align}
  \mathbf{A} c & = y\\
%
\left[
\begin{array}{rr}
 1 & -6 \\
 1 & -2 \\
 1 & 1 \\
 1 & 7 \\
\end{array}
\right]
%
\left[
\begin{array}{r}
 c_{0} \\
 c_{1} \\
\end{array}
\right]
%
  &=
%
\left[
\begin{array}{r}
 -1 \\
  2 \\
  1 \\
  6
\end{array}
\right].
%
\end{align}
$$
Your choice for solution is the normal equations
$$
\begin{align}
%
  \mathbf{A}^{*} \mathbf{A} c &= \mathbf{A}^{*}y \\
%
\left[
\begin{array}{cc}
 4 & 0 \\
 0 & 90
\end{array}
\right]
%
%
\left[
\begin{array}{r}
 c_{0} \\
 c_{1} \\
\end{array}
\right]
%
  &=
%
\left[
\begin{array}{r}
  8 \\
 45
\end{array}
\right] .
%
\end{align}
$$
The solution is
$$
\begin{align}
  c &= \left( \mathbf{A}^{*} \mathbf{A} \right)^{-1} \mathbf{A}^{*} y \\
%
\left[
\begin{array}{r}
 c_{0} \\
 c_{1} \\
\end{array}
\right]
%
  &=
%
\left[
\begin{array}{cc}
 \frac{1}{4} & 0 \\
 0 & \frac{1}{90} \\
\end{array}
\right]
%
\left[
\begin{array}{r}
  8 \\
 45
\end{array}
\right] \\
%
 &=
%
\left[
\begin{array}{c}
  2 \\
 \frac{1}{2}
\end{array}
\right] .
%
\end{align}
$$
The solution function is
$$
 y(x) = 2 + \frac{1}{2} x.
$$
The residual error vector is
$$
  r = \mathbf{A}c - 7 =
\left[
\begin{array}{r}
  0 \\
 -1 \\
  \frac{3}{2} \\
 -\frac{1}{2}
\end{array}
\right]
$$
with a total error of $r^{2} = \frac{7}{2}.$
The solution is plotted against the data points below.


Differences between stroke and let

Question: I was checking up on some squash rules and realised that I have never really grasped the difference between stroke and let in squash. Especially if there is no dedicated ref, how do you go about deciding these?
Here's an interesting video, where three events: let, stroke and no-let happen during some match, but they looked pretty much the same to me. Could someone explain why the calls are made in that way?
Comment: I'm not an expert, but from my understanding a Let is when the player is in the way but there's doubt about the ability of doing a good return. A Stroke is when the player would realistically get to return the ball or the player did not try to get out of the way. No-let would be the opposite, when the player clearly won't reach the ball in time. (I've only used Let since I played casually with friends for 1.5years)
Answer: The rules are a bit complex. The word "let" is mentioned 39 times in the online US Squash Rules. Under rule 12, Interference, here are some of the more common uses of "Let", "No Let" and "Stroke":

The player is entitled to a let if he or she could have returned the ball and the opponent has made every effort to avoid the interference.
The player is not entitled to a let (i.e. loses the rally) if he or she could not have returned the ball, or accepts the interference and plays on, or the interference was so minimal that the player's access to and strike at the ball was not affected.
The player is entitled to a stroke (i.e. wins the rally) if the opponent did not make every effort to avoid the interference, or if the player would have hit a winning return, or if the player would have struck the opponent with the ball going directly to the front wall.

The main points are that a Let is awarded if the player on the ball was not able to hit the ball due to interference by the other player. A let may also be awarded the the player on the ball does not hit the ball for fear of injuring their opponent (either by the ball contacting them or the racket). it generally needs to meet three criteria:

The interfering player made every effort to avoid interfering.
The player on the ball would have had a reasonable shot.
The player on the ball would not have had a clear winning shot.

If the interfering player did not make very effort to avoid interfering, or if the player on the ball would have had a clear winning shot, then a "Stroke" (and point) is awarded to the player on the ball.
If the player on the ball would not have had a reasonable shot (i.e. the ref thinks they wouldn't have made it, regardless of the interference), then it's a "no let".
I can't watch the video at the moment, but I'll try to watch it later. Ultimately, though, the ref's decision likely hinges upon the three points above.
If there is no dedicated ref, then you and your playing partner need to judge it yourself. Generally I only call "Let" (no "Stroke") when playing with friends, and only call it if I'm fairly confident I would have had a shot. My partners respect my call, and I respect theirs.
Answer: Just to clearly link this response to the video, in the first instance (:38) you can see the player in white tries to get out of the way to leave a path to the ball, but just doesn't quite clear out enough. As a result there's a small amount of interference, but it's not really anyone's fault - so Let.
In the second instance (:58), white hits then clearly steps back into the path of the striker, who no longer has a path to the ball. So here the stroke is awarded because white did not make a reasonable attempt to clear the path and blue could easily have hit the ball to the front wall.
In this case, I suspect white meant for that ball to be much shorter and lower in which case it would have been a winner, and resulted in a No Let. This is what happens in the third case:
The last one (1:38) is a No Let because white hits the ball very well (low and short) so that the striker did not have any chance of getting to the ball regardless of the interference. Basically the second and third shots are the same situation, the only difference being whether or not blue had a chance on the ball.

Differences between stroke and let


How do I move a shape to the foreground or background in Javascript?

Question: I have a Code HS project in which I have to make a a few frames for a comic in Javascript. How do I make a shape appear on top of another shape (the intended background always covers up the characters)?
Answer: In the HTML, set the CSS property "z-index" of the elements. The higher the z-index, more "on top" it is.
In Javascript you can manipulate the z-index at runtime.
Answer: In javascript the css attributes is changed to camelCase
Like this:
<code>  document.getElementById("img1").style.zIndex = "1";
</code>


Generic repository pattern and multiple selects

Question: I am trying to learn the repository pattern and looking at a generic repository I cannot see how to handle customized select statements. For example, using this article the author uses a select by ID and a select all.
public interface IGenericRepository<T> where T:class
{
    IEnumerable<T> SelectAll();
    T SelectByID(object id);
    void Insert(T obj);
    void Update(T obj);
    void Delete(object id);
    void Save();
}

Later the article the IGenericRepository interface is implemented using Northwind. Then that is used to create a Customer controller.
public class CustomerController : Controller
{
    private IGenericRepository<Customer> repository = null;
    public CustomerController()
    {
        this.repository = new GenericRepository<Customer>();
    }
    ...

This would handle selecting a list of all Customers or for one Customer by ID but where I get stuck is some more real world examples like "select all Customers for a client" or "select all Customers for a region". Plus, you could have another controller based on a different entity that would filter on different attributes. I assume I'm missing something basic. If the user interface needed to present the Customer entity (or any other entity) by various filters, how would this be done by sticking with one generic repository?
Comment: FYI, there are some limitations when trying to create a Base class repository: http://stackoverflow.com/questions/15452377/c-sharp-object-composition-removing-boilerplate-code .  Things start to get quite nasty if you have an Entity (like `Customer`) which should never really be deleted.
Comment: Thanks for that information. My next question was going on that very topic and customer is a good example. I have access to entities that I cannot control so update/delete are not possible. I wasn't sure about throwing exceptions for those cases.
Answer: Here you go; to handle any select criteria apart from the Id, you can add Where method
like below
public interface IGenericRepository<T> where T:class
{
    IEnumerable<T> SelectAll();
    T SelectByID(object id);
    IEnumerable<T> Where(Expression<Func<T,bool>> predicate)// this one
    void Insert(T obj);
    void Update(T obj);
    void Delete(object id);
    void Save();
}

Now in the Where method  implementation do it like this
public IEnumerable<T> Where(Expression<Func<T,bool>> predicate)
    {
        return _objectSet.Where(predicate).AsEnumerable();
    }

Here _objectSet in created in repository constructor like this :
public Repository(ObjectContext context)
        {
            _context = context;
            _objectSet = _context.CreateObjectSet<T>();
         }

public CustomerController()
    {
        _context = new NorthwindEntities();
        _reporsitory = new Repository<Customer>(_context);

    }

Use of Where method like
 reporsitory.Where(c=>c.Country=="Canada").ToList();

For full reference see this project on codeplex (download /browse source code)
https://efgenericrepository.codeplex.com/SourceControl/latest
Comment: Sorry for the delay, let me process your response a bit more.
Comment: I also found an interesting example using Contoso University on CodePlex here: https://contosontiermvc.codeplex.com/SourceControl/latest#ContosoUniveristy/Contoso.Data/Infrastructure/IRepository.cs
Answer: I think the implementation of the GenericRepository should somehow be able to return the IQueryable of current entity, like adding Get() method.
protected IQueryable<T> Get() // Notice that the access modifier is protected.
{
   return table;
}

Then you could just create a derived class from GenericRepository and add a select method that accepts the Filter class.
public class CustomerRepository : GenericRepository<Customer>
{
   public IEnumerable<T> SelectAll(CustomerFilter filter){ .. }
}

The filter class contains 2 filters.
public class CustomerFilter
{
   public int? ClientId { get; set; }
   public int? RegionId { get; set; }
}

Then the SelectAll implementation would be.
public IEnumerable<T> SelectAll(CustomerFilter filter)
{
   var query = Get();
   if (filter == null)
   {
       return query;
   }

   if (filter.ClientId.HasValue)
   {
      query = query.Where(q => q.ClientId == filter.ClientId.Value);
   }

   if (filter.RegionId.HasValue)
   {
      query = query.Where(q => q.RegionId == filter.RegionId.Value);
   }

   return query;
}

In the controller, calling it like.
public ActionResult Get(int? clientId, int? regionId)
{
    var filter = new CustomerFilter { ClientId = clientId, RegionId = regionId };
    var customers = _repository.SelectAll(filter);
    return View();
}

You might need to see this post as your reference.
Answer: An approach I've seen in one asp.net mvc based mission critical app, is to use the generic interface as defined in the question. Then there is an abstract class that implements that interface. And there is one more repository class that inherits the abstract class, which has all methods specific to that class.
public interface IGenericRepository<T> where T:class
{
 ...
}

public abstract class GenericRepository<T> : IGenericRepository where T:class
{
 ...
}

And the CustomerRepository class
public class CustomerRepository : GenericRepository<Customer>
{
 //add method specific to Customer like select Customers in specific country

}

And in the controller
public class CustomerController : Controller
{
  private CustomerRepository  repository = null;
  public CustomerController()
  {
    this.repository = new CustomerRepository();
  }
  ...


Wait for javascript callback function to finish

Question: I am using google storage api for saving a file in gcp bucket in a async function. I want to wait till I get a error or success in callback, only then I want to proceed with other lines of code but I am getting LastMessage before success or error.
https://googleapis.dev/nodejs/storage/latest/File.html#save
await file.save(jsonData.trim(), {resumable : false}, function(error) {
 if (error) {
   console.log('error');
 } else {
   console.log('success');
 }
})

console.log( "LastMessage: Error or Success is received, only then log this message")

Comment: Are you sure `.save()` returns a promise when you pass a callback? If not, there's nothing the `await` will wait for.
Answer: Your .save() is not returning promise. Rather is giving a callback.
You can create a traditional promise method to get what you want to achieve.
Here's the code snippet for that -

const saveFile = (jsonData) => {
    return new Promise((resolve, reject) => {
        file.save(jsonData.trim(), { resumable: false }, function (error) {
            if (error) {
                console.log('error');
                reject()
            } else {
                console.log('sucess');
                resolve()
            }
        })
    })
}

await saveFile()

console.log("LastMessage: Error or Success is received, only then log this message")

Answer: There is an example in the document
https://googleapis.dev/nodejs/storage/latest/File.html#save-examples
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const myBucket = storage.bucket('my-bucket');

const file = myBucket.file('my-file');
const contents = 'This is the contents of the file.';

file.save(contents, function(err) {
  if (!err) {
    // File written successfully.
  }
});

//-
// If the callback is omitted, we'll return a Promise.
//-
file.save(contents).then(function() {});

You don't need to use await, for your example you can try this:
file.save(jsonData.trim(), {resumable : false})
.then(() => nextFunc())
.catch(() => nextFunc())

function nextFunc() {
   console.log( "LastMessage: Error or Success is received, only then log this message")
}


Macro for concatenating two strings in C

Question: I'm trying to define a macro which is suppose to take 2 string values and return them concatenated with a one space between them. It seems I can use any character I want besides space, for example:
#define conc(str1,str2) #str1 ## #str2
#define space_conc(str1,str2) conc(str1,-) ## #str2

space_conc(idan,oop);

space_conc would return "idan-oop"
I want something to return "idan oop", suggestions?
Answer: Try this
#define space_conc(str1,str2) #str1 " " #str2

The '##' is used to concatenate symbols, not strings. Strings can simply be juxtaposed in C, and the compiler will concatenate them, which is what this macro does. First turns str1 and str2 into strings (let's say "hello" and "world" if you use it like this space_conc(hello, world)) and places them next to each other with the simple, single-space, string inbetween. That is, the resulting expansion would be interpreted by the compiler like this
"hello" " " "world"

which it'll concatenate to
"hello world"

HTH
Edit
For completeness, the '##' operator in macro expansion is used like this, let's say you have
#define dumb_macro(a,b) a ## b

will result in the following if called as dumb_macro(hello, world)
helloworld

which is not a string, but a symbol and you'll probably end up with an undefined symbol error saying 'helloworld' doesn't exist unless you define it first. This would be legal:
int helloworld;
dumb_macro(hello, world) = 3;
printf ("helloworld = %d\n", helloworld); // <-- would print 'helloworld = 3'

Comment: Keep in mind this is not necessarily dumb if you're doing something like `dumb_macro(mypackage,myfunction)`...
Comment: @R., of course the concept has uses, but it's generally connected to some other semantic value, or the option to replace the macro with something else (such as, for debugging purposes). I didn't want to dive in to anything like that, so this particular one is just a dumb macro concatenating two symbol names for no real purpose... :)
Comment: whoa that's one great answer. Wanted to know how to do that symbol concatenation. It's really useful..
Comment: @roe I have a thing to ask. `dumb_macro(a,b) a ## b` will concatenate the exact symbols, as you've shown. But how can i concat a symbol with a value of a variable? Say there an integer `n` which hold a value 1,2... How can i concatenate `sym` with the **value of** n (not with `n`)? for eg. if n=1, then i need to get `sym2`.
Comment: @Anubis; Due to some quirks in the preprocessing spec, it'll only recursively evaluate tokens if they're not part of a concatenation or made into strings, so you'll need a level of indirection. Quick google gives [these](http://stackoverflow.com/questions/1597007/creating-c-macro-with-and-line-token-concatenation-with-positioning-macr) two [examples](http://stackoverflow.com/questions/4284733/preprocessor-token-expansion), I hope they can help you, good luck!
Answer: #define space_conc(str1, str2) #str1 " " #str2
printf("%s", space_conc(hello, you)); // Will print "hello you"

Answer: The right was to do it is to place the 2 strings one next to the other. '##' won't work. Just:
#define concatenatedstring string1 string2


How to prove that $(a + (b^2 + k^2)^{1/2}) > (c + (d^2 + k^2)^{1/2})$, given that $(a + b) > (c + d)$?

Question: What is the simplest/best way to show that:
If $(a + b) > (c + d)$ then $(a + (b^2 + k^2)^{1/2}) > (c + (d^2 + k^2)^{1/2})$?
For context, I have a VR environment and I want to find the shortest path between O and T. There are Walls and computing possible paths is not easy so I hard-coded corridors and intersections using a weighted graph (red vertices).
Targets positions are variable and, once again, its not easy to see if there is a path between them and the remaining nodes so, T and arcs i,j are not part of the graph.
The problem I stated is the following: It is correct to assume that the nodes of the graph belonging to the shortest path between O and T (if T was connect to the graph) are the sames as the ones between O and the nearest graph node?
In other words, If the shortest path between O and N if by "2", then the shortest path between O and T, if i and j arcs existed, would also be by "2"?
a = a' + a'' so: if a+b > c+d then a + i > c + j?
Comment: Welcome to math.SE: since you are new, I wanted to let you know a few things about the site. In order to get the best possible answers, it is helpful if you say in what context you encountered the problem, and what your thoughts on it are; this will prevent people from telling you things you already know, and help them give their answers at the right level.
Answer: Not true.  Note that $1 + 4 = 2 + 3$ but $1 + \sqrt{4^2 + 3^2} = 6 < 2 + \sqrt{3^2 + 3^2} = 2 + 3 \sqrt{2}$.  So for $a$ slightly greater than $1$,
$a + 4 > 2 + 3$ while still $a + \sqrt{4^2 + 3^2} < 2 + \sqrt{3^2 + 3^2}$.
Comment: nice, quick counterexample! +1
Comment: yes, thanks :) I was focusing, without reason, what examples with a>>b... i don't know if that explains my difficulties.. but, since that condition is not necessary in my problem... your solution is great.. btw, is there any method to solve this kind of problems algebrically? like my manipulating inequalities? thanks


Is it okay to pass dispatch and getState from a Redux thunk function down into helper functions?

Question: Let's say I have a thunk which is a top-level function:
export default () => (dispatch, getState) => {
    // do stuff here

    childFunction(getState) // is it okay to pass in getState so that children down the chain can call getState?
    anotherChildFunction(dispatch) // is it okay to pass in dispatch so that children down the chain can dispatch something?
}

In the above example, let's say that both childFunction and anotherChildFunction don't directly use their arguments but pass it on further down to their child functions and to their child functions and eventually one of them needs it to dispatch an action or retrieve something from the Redux state.
Is it okay to pass these down the chain or is there another way that I'm not thinking about?
Comment: As long as your reducer remains pure and you don't mix async into a reducer function it should not matter.
Answer: Yes, that's totally fine.  Alternately, you could define those other functions as thunks and dispatch them as well, but if they're only ever used as "helper functions" just passing in dispatch or getState directly is very reasonable.


Move square to right on every click

Question: As I wrote in the title, when user clicks on the square it should move 100px to the right and after next click it should move 100px again to the right but square is going back to left. How can I fix this?
Also in JSFiddle code is working but when I open this on Chrome it's giving me error:
Cannot read properties of null (reading 'addEventListener')

    <title>JavaScript animation</title>

JS Fiddle link
Answer: Right now you're simply toggling the class, so it moves right and back to its original position.
You need to add a value to the already existing value, in this case 100 pixels.
Also not getting an error from your original fiddle.

const square = document.querySelector('#square');

square.addEventListener('click', moveRight);

function moveRight() {
  square.style.left = square.offsetLeft + 100+'px';
}
#square {
  width: 100px;
  height: 100px;
  background-color: #333;
  position: absolute;
  left: 0px;
  top: 100px;
  transition-duration: 3s;
  transition: left 1.5s ease-in-out;
}

Move square to right on every click


How can I change icon inside button on hover using chakra-ui and vanilla-extract?

Question:
I am using nextjs13, chakra-ui, and vanilla-extract

Does anyone know how to change icon and text inside button on hover, using chakra-ui and vanilla-extract?
I have a button like this:
<Button >
 <svg width="16" height="18">
  <use xlinkHref={path/to/iconA}></use>
 </svg>
{!isFollowing ? follow : following}
</Button>

I want to show 'follow' button with icon A if logged in user is not following the user.
I want to show "following" with icon A if logged in user is following the user.
When I hover the button(and logged in user is currently following the user),
I want to change button text: from "following" to "unfollow" with red text color and icon: from iconA to iconB.
I could change the text color by adding css to span:
following
const textCss = style({
":hover":{
color:"red"
}})

but not sure how to change the text and icon.
Answer: You could do the following
import * as styles from './styles.css'
<Button className={styles.button}>
 <svg width="16" height="18">
  <use xlinkHref={isFollowing ? 'path/to/iconA' : 'path/to/iconAB'}></use>
 </svg>
{isFollowing ? 'unfollow' : 'follow'}
</Button>

and for your vanilla extract css file you could do something like this
export const button = style({})
export const buttonText = style({
    selectors: {
        `${button}:hover &`: {
             color: 'red'
         }
     }
})

Vanilla extract provide some good documentation that can be found here.
Comment: thanks for the answer. What I want to achieve is to show iconB only when isFollowing=true && when I hover the button. do you have any idea? @jnbjarni
Comment: Then you need to store in state variable information about the hover state of the button. `const [hover, setHover] = useState(false)` and then on your button component you need to add the two methods that track if the user is hovering ` setHover(false)} onMouseOver={() => setHover(true)}>...`, and finally you add the check on the icon ``. Should note that this is just rough pseudo code but should aim you in the right direction.
Answer: I solved issue by adding 'isHover' as state variable.
const [isHover, setIsHover] = useState(false);

<Button onMouseEnter={() => setIsHover(true)}
        onMouseLeave={() => setIsHover(false)}>
 <svg width="16" height="18">
  <use xlinkHref={ !isFollowing && isHover? path/to/iconB: path/to/iconA}>
  </use>
 </svg>
 {!isFollowing ? follow : following}
</Button>

Answer: If you simply need to change the color of the existing icon, you can change the SVG file to have fill="curentColor" throughout that file, and then using
svg:hover { fill: red; } should work for you.


Westell 7500 - unable to reach static IPs from external network

Question: I am trying to troubleshoot a network configuration at a remote site. It's a standard configuration for us, that we use across multiple sites. The only difference here is that this ISP uses PPPoE, whereas our others do not.
We were assigned a block of static addresses, using a default gateway from within that block. We are using a Westell 7500 modem, and currently have two machines attached to it that I am trying to reach via Internet through IPMI. The remote techs configured the IPMI settings, using two static IPs from within our block, and the supplied default gateway and subnet.
They sent me the router configuration, and I find it a little confusing. Our WAN IP is the gateway address, which I believe is the right way to configure it, but our WAN gateway is an address we have no knowledge of (our statics start with 209, this WAN gateway address starts with 69). Tech support told us that's fine but didn't really give an explanation of what that should be set at.
I can ping the gateway but not the internal statics (they time out). When the modem is power-cycled all three addresses throw "destination net unreachable."
I don't ever do router configurations; my setup is always everything behind the modem/router. I'd appreciate advice on what to look at and how to try to troubleshoot this.
EDIT: Another tech recommended that we connect a laptop directly to the modem, configure it to one of the static IPs, and see what we get. That computer is able to get Internet access; however, they then turned off Windows Firewall and I was unable to ping them.
Answer: Turns out that this particular model has a quirk. Turning off the internal firewall does not work all the time. You have to create exceptions to be sure.


Using "link_to" in a button to link to a different page

Question: I want to have my button link to a different page in this bootstrap setup. The file is located in "static_pages" and is called "register.html.erb". It also has a named route called "register_path". How do I make my button link there?
I've tried this using "a href" and it doesn't work. I assumed it's better to use "link_to" but I didn't know how to do that.

Sign Up

Comment: So, what is the real problem?
Answer: Try this:
<%= link_to "Register Page", register_path, :class => "btn btn-primary btn-lg" %>

Answer: Reading the Rails documentation is going to make your life a lot easier.
<%= link_to "Sign Up", register_path, :class => "btn btn-primary btn-lg" %>


Esp32 Turn by turn Navigation

Question: I am trying to create an app that allows me to use my esp32 as a "GPS" for turn by turn navigation.
I searched a lot, saw a lot of projects, but couldn't understand any of them + it seens that some of those projects don't work anymore. Basically I am using BLEDevices in order to create a bluetooth connection with my esp32 and my android phone
<code>#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>

// See the following for generating UUIDs:
// https://www.uuidgenerator.net/

#define SERVICE_UUID        "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"

void setup() {
  Serial.begin(115200);
  Serial.println("Starting BLE work!");

  BLEDevice::init("Long name works now");
  BLEServer *pServer = BLEDevice::createServer();
  BLEService *pService = pServer->createService(SERVICE_UUID);
  BLECharacteristic *pCharacteristic = pService->createCharacteristic(
                                         CHARACTERISTIC_UUID,
                                         BLECharacteristic::PROPERTY_READ |
                                         BLECharacteristic::PROPERTY_WRITE
                                       );

  pCharacteristic->setValue("Hello World says Neil");
  pService->start();
  // BLEAdvertising *pAdvertising = pServer->getAdvertising();  // this still is working for backward compatibility
  BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
  pAdvertising->addServiceUUID(SERVICE_UUID);
  pAdvertising->setScanResponse(true);
  pAdvertising->setMinPreferred(0x06);  // functions that help with iPhone connections issue
  pAdvertising->setMinPreferred(0x12);
  BLEDevice::startAdvertising();
  Serial.println("Characteristic defined! Now you can read it in your phone!");
}

void loop() {
  // put your main code here, to run repeatedly:
  delay(2000);
}
</code>
the main problem is that I can't figure out which app I can use in my phone (waze,komoot, sygic ...) to get for ex the next move, speed and etc and send it to my esp32.Also I already tried different approechs like KomootBLEConnect.h, my phone connects to the esp32 bluetooth, but it don't show any information about navigation
<code>#include "Arduino.h"
#include "KomootBLEConnect.h"

//When data is received from Komoot, this callback is triggered. Start your processing here
void NavCallback(uint8_t icon, uint32_t length, String street)
{
  Serial.printf("icon: %d, length %d, street: %s\n", icon,length,street);
}

void setup()
{
  Serial.begin(9600);
  Serial.println("Starting Arduino BLE Client application...");
  Komoot::BLEHandler::Begin("ESP32 Komoot");
  Komoot::BLEHandler::RegisterCallback(NavCallback);
}

void loop()
{
  Komoot::BLEHandler::Loop(); //Scans for BLE devices that serve the BLEConnect Service and connects to them IF paired
  delay(1000);
}

</code>
Comment: Recommendation: Don't look for code. Look for documentation.
Comment: @ user4581301 can't find any docs...
Comment: See [softwarerecs.se]
Answer: I had made one thing that ran with Sygic application but we have important problem here: The development team of Sygic would be remove this feature anytime.
For your refer:
https://vt.tiktok.com/ZSNLPUuWQ/
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

Esp32 Turn by turn Navigation


Are the area of a circle inscribed in a square and the area of the "spandrels" (the four corners that remain) commensurable?

Question: And how would you demonstrate that most simply?
See the beginning of my blog post for a little more:
http://seekecho.blogspot.fr/2013/02/different-ilks.html
Comment: You should include the definition of the spandrel in your question.
Answer: So you want to show that the area of the circle, i.e. $\pi$, is not commensurable with the area of "square minus circle", i.e. $4-\pi$, right? Two things are commensurable if their fraction is a rational number. Now look at it this way:
$$\frac{4-\pi}\pi = \frac4\pi-1 = r\not\in\mathbb Q$$
Suppose $r$ were a rational number, then all the following would be rational numbers as well:
\begin{align*}
\frac4\pi &= r + 1 \\
\frac1\pi &= \frac{r+1}4 \\
\pi &= \frac4{r+1}
\end{align*}
But as you know that $\pi$ is irrational, you know that $r$ cannot be rational.
Given two incommensurable numbers $a$ and $b$, the set $\{pa+qb\;\vert\;p,q\in\mathbb Q\}$ can be interpreted as a vectorspace over $\mathbb Q$ with dimension two. You can check all the vector space axioms to see that this is true. The switch from "circle and square" to "circle and spandrel" is simply a change in basis vectors, but does not make the vectors linearily dependent. So as a general conclusion, two numbers $p_1a+q_1b$ and $p_2a+q_2b$ will still be incommensurable unless they are linearily dependent in the vector space sense, i.e. unless
$$\begin{vmatrix} p_1 & p_2 \\ q_1 & q_2 \end{vmatrix} =
p_1q_2 - p_2q_1 = 0$$
Comment: @SimonG: If you look at the Wikipedia lemma for [vector space](http://en.wikipedia.org/wiki/Vector_space), you will find "A [field extension](http://en.wikipedia.org/wiki/Field_extension) over the rationals ℚ can be thought of as a vector space over ℚ" (link added by me) which expresses this concept. More info in the surrounding text. In your case you have the field extension $\mathbb Q(\pi)\subsetneq\mathbb R$ obtained via [adjunction](http://en.wikipedia.org/wiki/Adjunction_%28field_theory%29). Also look up "Linear independence", "Basis (linear algebra)" and "Dimension".
Comment: Thanks for that, MvG. The first bit explains it beautifully - embarrassingly - simply. The second part I'll have to research to understand...


Does not contain query

Question: I'm working in SQL Server 2008.  I am trying to run a "does not contain" query.  My basic syntax is:
SELECT
*
FROM some_table
WHERE
some_column <> '%some_text%'

I would expect this to return all records that do not contain the text "some_text" anywhere in the some_column string.  However, the actual result set is returning records that do contain "some_text" somewhere in the string.  What am I doing wrong?
Comment: i think you need to leave out the % when not using "like"
Answer: Can you try:
SELECT
*
FROM some_table
WHERE
some_column NOT LIKE '%some_text%'

Comment: I was just about to suggest that.

Does not contain query


How to integrate google script (web app) with IOS application?

Question: I have a google web application, which has web form. I would like to create an IOS app to get all the information I need to fill in that web form and pass that information through IOS app.  Google web app is built on Javascript. Where can I find good information to build this app?
Thank you
Answer: The client side of GWT is javascript. To access native code from javascript you need phonegap
Comment: Is there any way we can do it? I know in iOS 8 they expanded the webkit so we can evaluate it using javascript, but I'm not sure if that would work or not?


Use Views to delete a record from the database

Question: I have created a view that displays userpoints info. What I need is to create a link that will delete or reset individual records.
Answer: Userpoints can not be deleted, at least not through the UI.
Instead, you need to create a reverting transaction that removes the points that the other transaction added, or the other way round.
The only thing that you can currently do out of the box is building a link that points to the add points form with the username pre-filled, by using that as a token in views. Then you just need to add the points and save.
Everything else currently requires custom code, by e.g. writing a custom action.
Userpoints 7.x-2.x will allow this using bulk operations and better rules integration, but there is currently not much progress on that branch. As in, pretty much none.
Comment: I was thinking if there is a reset all button there should be a reset this one user point. I desperately need this. :-(
Comment: Could you elaborate on prefilling the users name in the add form?
Comment: You need to build an url that points to admin/config/people/userpoints/add/[uid], which should be able to using views tokens.
Answer: If you have access to the database where all the information about your website is stored (when you're using phpMyAdmin for example), you can navigate to your_database > userpoints/userpoints_total/userpoints_txn and delete all the granted User Points you want to. There's a nice 'select all' link at the bottom if you'd need to delete a lot of data.
It worked for me, but be careful with this: all deleted data will be lost forever! Therefore, make sure you always back-up before deleting stuff from your database!


Reporting of Neural Network Accuracy for Academic Publications

Question: I'm an academic researcher, working with Convolutional Neural Networks, particularly for image classification. In academic publications, a typical metric for evaluating the performance of a recognition pipeline is the classification accuracy. What I am wondering, is exactly at what point during the training stage this number is taken.
For example, in my experiments, I train the network with back propagation, and reduce the learning rate over time. For this, I observe the testing accuracy, and reduce the rate by a certain amount whenever this accuracy is no longer increasing. However, what I notice is that once the system has converged, and I continue to train with minibatches, the overall testing accuracy still varies after each minibatch by around 1%, even though the average testing error over all minibatches is constant.
So, my questions are:

When reporting the testing accuracy in an academic publication, is it acceptable to simply take the highest accuracy over all these minibatches? Or should something more representative be used, such as an average over all minibatches?
Sometimes, the testing accuracy actually begins to fall as further training is carried out, due to overfitting. Is it acceptable to stop the training at this point, and report this peak testing accuracy, even though the testing dataset is distinct from the training dataset (i.e. the validation set is not a subset of the training dataset)?
Comment: I have no idea what you're doing. If the system has converged, why are you continuing to train? If it's converged, you're done! Test the model in whatever way is standard in your community and write it up. If you're continuing to run a stochastic simulation after convergence, yeah, it's going to fluctuate **because it's stochastic.** Metrics of test sets tell you virtually nothing about the out-of-sample performance of the model, which is the only relevant performance information.
Comment: If the training is done ("converged"), and you're continuing to poke around for a random batch that makes your results better, it sounds a lot like you're on a fishing expedition for the samples that will make your results look artificially better. But your third sentence sounds like a contradiction: you're *not* training to improve results, but you *are* training to improve test accuracy? What does that mean?
Comment: http://pages.cs.wisc.edu/~shavlik/roc.pdf
Comment: I'd like to say that it is not academic practice to be deceptive in publications, but recent examples of academic misconduct demonstrate that is not strictly the case that authors are aboveboard in presentation of their findings. But I'm probably naive for insisting that people be honest.
Comment: Thanks, that's an interesting article. In particular though, I'm interested in what the *standard* approach is for academics in reporting these classification accuracies, particularly for neural networks where training is not deterministic.
Comment: It's not possible to train with full batch on standard hardware, so minibatch training is typical. The stochastic nature of this means that accuracies will fluctuate a little. So I am not continuing to train for the purpose of improving the overall performance, but possibly for the purpose of finding the minibatch after which the testing accuracy is highest, and then reporting the result at this point. And I'm just wondering whether this is acceptable practice.
Comment: Yes, you're correct -- I would be fishing for the best results -- even though this is strictly not good practice, I'd like to know if it is this typical for academic publications.
Answer: Before I answer your question let me say, in general it is considered good practice to have a Validation set that is completely distinct from your Test set. You may or may not be aware of this fact, but you seem to gloss over it in your question, so I wanted to make that explicitly clear.
The answer to your question would be an average across all mini-batches of your Test set, as the Test set is supposed to represent an unbiased representation of how that NN may perform in the wild. Another way of stating this would be that the test set (since you haven't tuned your hyper-parameters to do well on that set) should represent how well your network generalizes, which is the goal for any network.
It would likely be considered deceptive academic practice to cherry-pick the best mini-batch for publishing results, and generally any published results should be able to be reproduced by other researchers. If you artificially conflate your accuracy by choosing the best mini-batch, that would make replication of your results difficult for other researchers and would likely lead other researchers to question the validity of your claims.
Examples of this can be seen in other areas of Science: many researchers have swiftly ruined their careers by publishing results that are not able to be reproduced by other researchers.
While I can't explicitly tell you whether or not this is typical of academic publications in this field of study, it is definitely unethical, probably immoral, and, as you have already stated yourself, not good practice.
It is likely that as this field grows in maturity, more attention will be paid to replication of results, and in doing so, will make the ability to replicate results vital to not only the integrity of the researcher, but also whether or not the research is generally accepted.
Please note that reproducability is a standard in all Scientific endeavors, and Computer Scientists are not the only ones facing this issue. For instance, I just ran across this BBC article about reproducability. This article (tangentially) addresses some of the points you have brought up with this question. This article also addresses the issue of, and need for, reproducability in general.
Comment: Absolutely. These are very important points, +1 for making them explicit


Using which() over matrix row-wise without for loop

Question: I have a matrix that looks like this
> a <- matrix(c(1,1,1,2,3,2,2,4,4,5,3,3,8,4,3,8),4,4, byrow = TRUE)
> a
     [,1] [,2] [,3] [,4]
[1,]    1    1    1    2
[2,]    3    2    2    4
[3,]    4    5    3    3
[4,]    8    4    3    8

Now I want to have a list of the indices for the minimum of each row. One way to do this is with a $\verb|for|$ loop
> b <- apply(a,1,min)
> c <- rep(list(), 4)
> for (i in 1:4){
    c[[i]] <- which(a[i,]==b[i])
  }
> c
[[1]]
[1] 1 2 3

[[2]]
[1] 2 3

[[3]]
[1] 3 4

[[4]]
[1] 3

I can't use $\verb|apply()|$ because the thing to repeat is a logical expression. Is there a way to do this without $\verb|for|$ loop?
Comment: This is an R programming question and if so it is off-topic here. See http://stackoverflow.com/. However, can't you define function which does the part "c[[i]] <- which(a[i,]==b[i])" and then feed it to apply?
Comment: Thanks. I didn't know we could use apply() this way.

I will post on stackoverflow from now on.
Answer: You can still use apply:
a <- matrix(c(1,1,1,2,3,2,2,4,4,5,3,3,8,4,3,8),4,4, byrow = TRUE)

> apply(a, 1, function(x) which(x == min(x)))
[[1]]
[1] 1 2 3

[[2]]
[1] 2 3

[[3]]
[1] 3 4

[[4]]
[1] 3


Does the 260 character limit still apply to path names in Windows Server 2016?

Question: does anybody know if the annoying 260 character limitation still apply to Windows Server 2016?
As far as I know this will be fixed in Windows 10 with the anniversary update coming this summer. But I couldn't figure out anything about that according to MS's server system.
Thank you.
Comment: Can you be more specific as to the 'annoying 260 character limitation'?  Non-Windows users (including me!) might not know what it is.
Comment: Of course:
Windows limits the length of possible path names down to 260 characters when handling files and folders through Explorer. That is especially a problem when you are a Java developer and you are dealing with deeply neested packet structures. If you use 3rd party application you still can store files, but you are very limited handling those files with Windows onboard tools. Thats the reason why I wrote annoying - I think experienced users would agree to that adjective :-)
Answer: If the filesystem is NTFS, you must enable the machine GPO: "Enable Win32 long paths". This GPO isn't enabled by default.
You can locate this GPO at:
<code>Policies > Computer Configuration > Administrative Templates > System > FileSystem > Enable Win32 long paths
</code>
Extracted from: http://www.sysadmit.com/2016/08/ruta-demasiado-larga-solucion-con-gpo.html
Comment: The GPO "Enable Win32 long paths" is available in Windows 10 "anniversary update" but not in Windows Server 2016 Technology Preview 5. Are you sure about Win 2016?
Answer: If you are still on NTFS then sadly yes. But if you are already on ReFS which started in w2k12 then you are good to go. There's also a tickbox on 2016 same as on W10 but it's not working correctly. I mean not out of box.... it is manual step, hopefully there will option to put that in xml file for unattended installation....
Comment: Enabling NTFS long paths will allow manifested win32 applications and Windows Store applications to access paths beyond the normal 260 char limit per node. Enabling this setting will cause the long paths to be accessible within the process.

so it's a matter of your application if it will be native to this new feature also that's what I meant when saying that's not working correctly ;) .
Comment: This would be a new server. So with the new fs it wouldn't be a problem according to you. Is the ReFs included in the Standard Edition?
Comment: yes in all editions


How to properly chain RxJS observables together with a for loop?

Question: I have a projectService to retrieve projects. Each project in turn has methods to retrieve corresponding tags and modules.
What i try to do is populate an instance property projects: Project[] with all corresponding tags and modules and when everything is populated call another method, which depends on the data.
I know my approach is not working because my map operation returns the projects before the observables in the for loop complete, but I have no idea how to do it properly.
class ProjectService {
  getAll(): Observable<Project[]> {...}
}

class Project {
  tagCollection: Tag[];
  moduleCollection: Module[];

  getTags(): Observable<Tag[]> {...}
  getModules(): Observable<Module[]> {...}
}

this.projectService
  .getAll()
  .pipe(
    map(projects => {
      for (const project of projects) {
        project.getTags().subscribe(tags => {
          project.tagCollection = tags;
        });
        project.getModules().subscribe(modules => {
          project.modules = modules;
        });
      }
      return projects;
    })
  )
  .subscribe(projects => {
    this.projects = projects;
    this.someOtherMethod();
  });

Update
I have tried both solutions and edited them to retain the project type and use a similar coding style. Both solutions work and seem to do the same thing in my project context. But I'm unsure which solution is better and if the edits i made are breaking any reactive best practices. Can someone elaborate on this?
Solution 1 from Reqven
this.projectService
  .getAll()
  .pipe(
    switchMap(projects =>
      combineLatest(
        projects.map(project =>
          combineLatest([project.getTags(), project.getModules()]).pipe(
            map(([tags, modules]) => {
              project.tagCollection = tags;
              project.modules = modules;
              return project;
            })
          )
        )
      )
    )
  )
  .subscribe(projects => {
    console.log(projects);
    this.projects = projects;
    this.someOtherMethod();
  });

Solution 2 from NateDev
this.projectService
  .getAll()
  .pipe(
    mergeMap(projects => from(projects)),
    mergeMap(project =>
      combineLatest([project.getTags(), project.getModules()]).pipe(
        map(([tags, modules]) => {
          project.tagCollection = tags;
          project.modules = modules;
          return project;
        })
      )
    ),
    toArray()
  )
  .subscribe(projects => {
    console.log(projects);
    this.projects = projects;
    this.someOtherMethod();
  });

Comment: Don't subscribe in the rxjs operators or place a subscription inside of another subscription. Please create a minimal reproduction of your project in stackblitz
Answer: Would something like that work for you ?
Might need some tweaking to fit your project, but it seems to be working.
this.projectService.getAll()
  .pipe(
    switchMap(projects => !projects.length
      ? of([])
      : combineLatest(
          projects.map(project => combineLatest([
            project.getTags(),
            project.getModules()
          ]).pipe(
            map(([tags, modules]) => ({tags, modules})),
            map(data => ({
              ...project,
              tagCollection: data.tags,
              moduleCollection: data.modules
            })),
        ))
    ))
  ).subscribe(projects => {
    this.projects = projects;
    this.someOtherMethod();
  });

Answer: There a many different ways to perform batch calls asynchronously.
So what I like to do is flatten my data as I believe it's easier to perform
operations on a more flat structure. After I'm done performing operations on the objects I regroup/reassemble them using the toArray operator
If you have any question regarding the operators I used feel free to ask. I highly recommend you to play around with the different rxjs transformation operators.
Be aware my code below is definitely not the best solution, but it works fine!
Hope it works for you!
StackBlitz
import { Component, Input, OnInit } from '@angular/core';
import { Observable, of, from, combineLatest } from 'rxjs'
import { delay, map, mergeMap,switchMap, toArray } from 'rxjs/operators';

@Component({
  selector: 'hello',
  template: `<h1>Hello {{name}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent implements OnInit {
  @Input() name: string;

  data: Partial<Project>[] =  [
    { name: 'foo'},
    { name: 'foo'}
  ]

  ngOnInit() : void {
    this.getProjects().pipe(
      mergeMap(projects => from(projects)),
      mergeMap((project) => {
        const tag$ = this.getTagsByProjectName(project.name);
        const module$ = this.getModuleByProjectName(project.name);
        return combineLatest([tag$,module$]).pipe(map(([tag,module]) => ({...project, tag, module})))
      }),
      toArray()
    ).subscribe({
      next: projects => {
        console.log(projects);
        this.name = JSON.stringify(projects);
      }
    })
  }

  getProjects() : Observable<Partial<Project>[]> {
    return of(this.data).pipe(
      delay(100)
    )
  }

  getTagsByProjectName(name: string){
    const tag = 'bar';
    return of(tag).pipe(delay(100));
  }

  getModuleByProjectName(name: string){
    const module = 'baz';
    return of(module).pipe(delay(100));
  }
}

interface Project {
  name: string;
  tag: string;
  module: string;
}

Comment: I didn't have time to evaluate the answers in my project yet. Will do that ASAP and give feedback.
Comment: Did the solution above help?
Comment: I have edited my question. It now contains an edited version of your solution that seems to work in my project but I'm still uncertain about some details.
Comment: You can also rewrite my solution using a switchMap if you only want to allow one active inner subscription at a time. Both solutions are correct in my opinion.


A point in a differential manifold who's an extremum of a smooth function

Question: This question about differential manifolds has 2 parts, I managed to do the first but not the second.

A. Let $M\subset \mathbb{R}^n$ be a $k$-dimentional manifold ($k<n$) and let $f:\mathbb{R}^n\rightarrow \mathbb{R}$ be a smooth function.
  Let $x_0\in M$ be a local extremum of $f$. Show that for every $h\in T_{x_0}M$, $$D_{x_0}f(h)=0$$

That's actually quite easy: we can take a smooth path $\gamma(t)$ with $\gamma(0)=x_0, \dot{\gamma}(0)=h$, and then $f\circ \gamma: I\rightarrow \mathbb{R}$ has local extremum in $0$, so it's derivative is $0$ there, and then the chain rule gives us the desired equality.
The second part is:

B. Prove that given these $M, x_0$, we can always choose a function $f$ that satisfies the conditions of the first part, and also $D_{x_0}f\neq 0$.

I have a geometric intuition about what I need to prove buy I still have no idea how to prove it. Any ideas?
Answer: Since $M$ is a $k$-dimensional submanifold of $\mathbb{R}^n$, we can choose a chart $(U, \phi) = (U, x^1,...,x^n)$ of $\mathbb{R}^n$ which is adapted to $M$, in the sense that $U \cap M = \{x^{k+1}= \cdots = x^n = 0\}$. Since $\phi$ defines a coordinate system about $x_0 \in U$ we have, $f = f \circ \phi$. Now apply the chain rule and you'll have your result.
$$Df \underbrace{(v^1,...,v^k,...,0)^T}_{h} = Df \cdot \begin{pmatrix} 0 \\ \vdots \\ x^k=0 \\ 1 \\ \vdots \\ 1\end{pmatrix}(v^1,...,v^k,...,0)^T $$
$\textbf{Edit}$
$$Df|_{x_0} = \begin{pmatrix} \frac{\partial f}{\partial x^1}(x_0) = 0 & \cdots & \frac{\partial f}{\partial x^k}(x_0) = 0 & \frac{\partial f}{\partial x^{k+1}}(x_0)&  \cdots &\frac{\partial f}{\partial x^{n}}(x_0)\end{pmatrix}$$
How the idea works is we have to assume $f$ is not a constant function, otherwise this result is incorrect. With this assumption, we can choose a chart $(U, \phi)$ as above. Plus, since $f$ is not constant, for some $x^j$ we have $\partial f/\partial x^j (x_0) \not = 0$. Can you finish now?
Comment: Cool. I'm glad you got it.
Comment: I don't think I understand. Where is the part that $x_0$ is an extremum of $f$ here?
Comment: I didn't want to give much away, but I'll make an edit.
Comment: I'm sorry, but I don't think it answered my question. How's $f$ defined, and in particular how is $x_0$ an extremum?
Comment: I made an edit.
Comment: Yes, I have succeeded thanks to your chart idea. Thank you!


Changing Git Repo

Question: My repo was taken down off GitHub for a copyright infringement. I have since removed all the files that were an issue and want to get it back into GitHub. I am assuming I need to push it to a new repo. I am not sure exactly how to go about making the switch. Can anyone explain how this might be accomplished?
When trying to push it with a git push origin master
I get:
remote: Repository unavailable due to DMCA takedown.
remote: See the takedown notice for more details:
remote: <link to the take down>
fatal: unable to access 'https://github.com/<repo>': The requested URL returned error: 503

Comment: You should consider moving from github/microsoft. It is unsafe to rely on this guys
Answer: Try creating a new repository. You need to add a remote repository.
git remote add origin https://github.com/user/repo.git

Then you should see this remote when run:
git remote -v

Check here for more details.
Comment: So I ran that command with a different repo name, and I get the following: fatal: remote origin already exists. Any ideas?
Comment: When I run `git remote -v` it still shows the old origin. Do I need to remove the old origin first?
Comment: You need to remove your old `origin`: `git remote rm origin` and then do this. `origin` is basically the short-hand name of your remote repository on Github. You can call it anything you like really.
Answer: If you want to switch repos, you need to change your git remotes.
You can view your current remote by changing into your repo and running git remote -v, which gives you the name and the repo path:
origin  firstname.lastname@example.com:username/reponame.git (fetch)
origin  firstname.lastname@example.com:username/reponame.git (push)

You can delete this old origin via git remote remove origin and add a new one with git remote add origin firstname.lastname@example.com:username/newreponame.git.
Don't forget that removing files from your repo may not be enough; you'll have to purge them from your Git history.

Changing Git Repo


Find projection matrix using partitioned matrices

Question: If X is a ($n$, $p+1$) design matrix, partition $X$ to be $X$=[$J$ $X$*]  where $J$ is a ($n$,$1$) vector of all $1$'s, and $X$* is a ($n$,$p$) matrix.
Let $H_X$ be a projection matrix, where $H_X$ = $X{(X'X)}^{-1}X'$.
I'm trying to prove:

$H_X$ = $H_J$ + $H_X*$

And in doing so, I've been trying to deduce the above equation using:

Suppose the design matrix $X$ can be decomposed by columns as $X$= [$A$ $B$].
  Define the hat or projection operator as $P${$X$} = $X{(X'X)}^{-1}X'$.
  Similarly, define the residual operator as $M${$X$}=$I$-$P${$X$}.
  Then the projection matrix can be decomposed as follows:
$P${$X$} = $P${$A$} + $P${$M${$A$}$B$}.

I found this formula (the "Blockwise Formula") on Wikipedia.
The link is: https://en.wikipedia.org/wiki/Projection_matrix
I've been trying to prove this formula, and from that deduce the equation I'm trying to solve. But I still haven't found a way to prove either.
How can I prove the equation above?
Will the formula I found on Wikipedia be helpful?
Comment: This formula will only work if the columns of $J$ are perpendicular to the columns of $X^*$.  That is, if $J'X^* = 0$. In other words, all columns of $X^*$ should have entries that sum to $0$.
Comment: Oh okay..so the "Blockwise Formula" won't be helpful then.. Thanks alot! So in this case do you happen to have any ideas on how I might solve the above equation?? @Omnomnomnom
Answer: Here is a counter-example: $$\begin{bmatrix}1&1&0&0\\1&0&1&0\\1&0&0&1\\1&0&0&0 \end{bmatrix}.$$
You can check that in this case $H_X=I_4 \neq H_J + H_{X^*}$.
Comment: Thanks! Actually I found out the equation I was trying to solve was flawed in the first place: It was H(X)=H(J) + H([I-H(J)]X*)...! The Blockwise Formula works in this case when X, J, X* are all full rank. Thanks alot for your suggestions:)


Substituirr espaço por Vírgula

Question: $var = 123 456 789;

Preciso que o valor dessa varável fique:
$var = 123,456,789;

Ou acrescentar uma vírgula após o numero:
$var = 123, 456, 789;

Tentei assim:
str_replace($var," ","")

Comment: Faça o inverso: `str_replace(" ",",", $var)`
Answer: Você já está quase conseguindo. Os argumentos da função str_replace que estão em ordem errada.
Conforme a documentação do PHP que você pode consultar aqui, você precisa fazer o seguinte:
$resultado = str_replace(' ', ',', $var);  // resultado: 123,456,789;
// ou
$resultado = str_replace(' ',', ', $var);  // resultado: 123, 456, 789;

Você pode sempre que quiser consultar a referência do PHP que indica funções relacionadas e outros conteúdos importantes em http://php.net/manual/pt_BR/
Answer: Uma maneira de não esquecer a ordem é:
substituir('este', 'por este', 'neste');

traduzindo para o PHP
str_replace(' ', ',', $var)

$var = 123 456 789; não é numero nem string, portanto vai gerar um erro no PHP

 PHP Parse error:  syntax error, unexpected '456' (T_LNUMBER) in source_file

Tem que colocar entre aspas para ser tratada como string

$var = "123 456 789";

//errado não vai imprimir nada
echo str_replace($var," ","").PHP_EOL;

//substitui espaço por virgula
echo str_replace(" ",",",$var).PHP_EOL;

//substitui espaço por virgula mais espaço
echo str_replace(" ",", ",$var).PHP_EOL;

rodando no ideone
Answer: Para usar o STR_REPLACE tu precisa transformar o conteudo da variavel em string então deve deixar entre aspas os numeros.
Depois tu passa para fazer a substituição dos espaços pelas virgulas no str_replace, mas dai tu precisa passar o valor recebido do replace para uma variavel que vai armazenar o novo valor.
E dai tu pode até separar depois com explode.
$var = '123 456 789';
$texto = str_replace( ' ', ', ', $var );
echo $texto;
$array = explode( ',', $texto );
var_dump($array);

Substituirr espaço por Vírgula


How to trim UK postcodes

Question: I would like to only show the first letters of a UK postcode. For example if its WV14 7AR then i only want to show WV
I have tried:
DECLARE @v VARCHAR(30)
SET @v='WV14 7AR'
SELECT LEFT(@v,LEN(@v)-6)

This returns: WV
However if the postcode is: WV4 then it will show: W and this is wrong.
Bare in mind you can get a UK postcode which could be 1 letter!
A Birmingham postcode is: B1 2AR and therefore LEFT suggestion will fail.
Comment: If you want to display the first two letters, why don't you do a LEFT(,2) ?
Comment: If it helps you search, that's called the postcode "Area". (e.g. there's an answer [here](https://social.msdn.microsoft.com/Forums/sqlserver/en-US/81853fbc-5ecd-4b5d-a2d1-f188f3985fc6/how-to-extract-just-the-postcode-area-from-a-british-postcode?forum=sqlreportingservices).)
Comment: `SELECT LEFT('WV14 7AR', 2)` or `SELECT SUBSTRING('WV14 7AR', 1, 2)`
Comment: because a postcode from Birmingham is: `B1 2AR` and therefore your LEFT suggestion will fail.
Comment: There are various things you might need to do but as usual, there are edge cases and therefore you need to describe whether you need to support 100% of cases or just the main ones. Most services that do something similar have to do a number of checks before they can provide what you want. There is no single answer that will work. Not all codes relate to area for instance: https://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Special_cases
Answer: This will show just the first letters of a UK postcode:
With Src (Postcode) As (
    Select 'B1 1AB' Union All
    Select 'W1A 1AB' Union All
    Select 'WV14 1AB' Union All
    Select 'GIR 1AB'
)
Select
    Postcode,
    RTRIM(LEFT(Postcode, PATINDEX('%[0-9]%', Postcode) - 1)) As FirstLetters
From Src

Postcode    FirstLetters
--------    ------------
B1 1AB      B
W1A 1AB     W
WV14 1AB    WV
GIR 1AB     GIR

Upd: non-UK Postcodes such as all-letter can be either filtered out with
Where Postcode Like '%[0-9]%'

or even stricter
Where Postcode Like '[a-z]%[0-9]%[a-z]'

or handled with
CASE WHEN Postcode Like '%[0-9]%'
    THEN RTRIM(LEFT(Postcode, PATINDEX('%[0-9]%', Postcode) - 1))
    ELSE Postcode
END As FirstLetters

Comment: If i run, "SELECT DISTINCT POSTCODE FROM CONTACT" i get Invalid length parameter passed to the LEFT or SUBSTRING function.
Answer: Assumtion : Extract part before the first integer
  DECLARE @v VARCHAR(30)
    SET @v='WV14 7AR'
    SELECT case when (PATINDEX('%[0-9]%', @v)) >2 then left(@v,2) else left(@v,1) end

Comment: There is GIR Postcode Area: [List of postcode districts in the United Kingdom](https://en.wikipedia.org/wiki/List_of_postcode_districts_in_the_United_Kingdom)

How to trim UK postcodes


Is this trig step correct?

Question: $\sin^{-1}(-\sin(x))$ = $-\sin^{-1}(\sin(x))$
Can the minus be taken out like this?
Comment: It can be done only if you are using a specific domain/range in defining arcsine. See my answer below. Many of the other answers make this assumption, but it is patently false except in a very specific circumstance. When you work with inverses of functions that are not 1-1, you have to be very very careful or you can gloss over something and arrive at a wrong answer.
Answer: Generally, it is not true that
$$f^{-1}(-f(x)) = - f^{-1}(f(x))$$
Try to cook up a counter-example!
However, in this case, since $\sin$ is odd we get that
$$\sin^{-1}(-\sin(x)) = \sin^{-1}(\sin(-x)) = -x = - \sin^{-1}(\sin(x))$$
Comment: I think principal value should find a place in the answer
Comment: It is not true that $\sin^{-1}(\sin(x)) = x \quad \forall x$.
Answer: Yes, that is valid, since the $\arcsin$, like $\sin$ is an odd function.
Here, that means that $\sin^{-1}(-f(x)) = -\sin^{-1}(f(x))$, and in this case, $f(x) = \sin x$. So ultimately, we have that $$\sin^{-1}(-\sin(x)) = -x$$
Comment: It is not true that $\sin^{-1}(\sin(x)) = x \quad \forall x$.  `arcsin` is odd, and so the manipulation the question asks about is correct, but it is not a true inverse of `sin`, because the sine function is not invertible.
Comment: Is arccos even and arctan odd?
Comment: Think about the range of the functions: $\arccos(1/2) = \pi/3$, but $\arccos(-1/2) = 2\pi/3$. Moral: $\arccos$ is not even (although $\cos$ is). However, $\arcsin$ and $\arctan$ are both odd.
Comment: Salman: you can always graph a function to help determine whether whether even, or odd, etc. $\arccos$ is not even, but it is true that $\arctan,$ like $\arcsin$, is odd.
Answer: It is only valid if you take the domain of $\sin^{-1}$ to be $[-1,1]$ and the range $[-\pi/2,\pi/2]$. There are other definitions for which this doesn't hold. For example, you could take the range to be $[\pi/2,3\pi/2]$.
Any restriction to a symmetric subinterval (open or closed) will work as well.
Comment: From my comment above on the OP's question:
"It can be done only if you are using a specific domain/range in defining arcsine. See my answer below. Many of the other answers make this assumption, but it is patently false except in a very specific circumstance. When you work with inverses of functions that are not 1-1, you have to be very very careful or you can gloss over something and arrive at a wrong answer"
Answer: Using the definition of principal value of inverse sine function,
we can always find an integer $n$ such that $\displaystyle x=n\pi+(-1)^n y$ with  $\displaystyle -\frac\pi2\le y\le\frac\pi2$
$\displaystyle\implies-\frac\pi2\le-y\le\frac\pi2 $
$\displaystyle\implies\sin x=\sin(n\pi+(-1)^n y)=\sin y $
$\displaystyle\implies-\sin x=-\sin y=\sin(-y)$
$\displaystyle\implies\sin^{-1}(\sin(-y))=-y$ as $\displaystyle-\frac\pi2\le-y\le\frac\pi2 $
Similarly, $\displaystyle\sin^{-1}(\sin x)=\sin^{-1}(\sin y)=y$ as $\displaystyle-\frac\pi2\le y\le\frac\pi2 $
Answer: Yes you are correct. It can be taken out since the value of $sin(x)$ is taken as an angle.

Is this trig step correct?


"This type is final so it cannot be inherited from" - ViewPager2

Question: I"m trying to extend the ViewPager2 class so I can allow dragging my SeekBarPreference left and right.
class ViewPager2Custom(context: Context) : ViewPager2(context) {

}

However I'm getting a "This type is final so it cannot be inherited from" red line on my ViewPager2(context).
Any idea?
Comment: Well, it's like the message says. The class is final so you cannot extend it.
Comment: Any idea how I can prevent the viewpager from executing when I swipe left/right on my `SeekBarPreference`?
Comment: The link you have added Says its define as `public final class ViewPager2` .. And you can not extends a final class ..
Answer: The NestedScrollableHost class does exactly what you're looking for: https://github.com/android/views-widgets-samples/blob/master/ViewPager2/app/src/main/java/androidx/viewpager2/integration/testapp/NestedScrollableHost.kt
The basic idea is that you override onInterceptTouchEvent and request the parent of the NestedScrollableHost (in this case the ViewPager2) to disallow it to intercept touch events, through the requestDisallowInterceptTouchEvent method.
// Pseudo-code for NestedScrollableHost

@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
    handleInterceptTouchEvent(event);
    return super.onInterceptTouchEvent(event);
}

private void handleInterceptTouchEvent(MotionEvent event) {
    // Early return if parent viewpager is null or child can't scroll in same direction as parent
    if (getParentViewPager() == null ||
            (!canChildScrollVertically(-1f) && !canChildScrollVertically(1f))) {
        return;
    }

    switch (event.getAction()) {
        // You can tailor your class to handle the event in the way you want to,
        // e.g. do something on down and move events:
        case MotionEvent.ACTION_DOWN:
            // Disallow the parent (and all subsequent parents) to intercept touch events.
            getParent().requestDisallowInterceptTouchEvent(disallow);
        case MotionEvent.ACTION_MOVE:
            // Some other logic.
    }
}

You would place the NestedScrollableHost in between your ViewPager2 and (in your case) SeekBarPreference in your XML.


Diagonalizable $3×3$ Matrix with columns $\overrightarrow{v}$, $\overrightarrow{2v}$, and $\overrightarrow{3v}$

Question: If $A$ $\in$ $\mathcal{M_{3\times3}}$ has columns equal to $\overrightarrow{v}$, $2\overrightarrow{v}$, and $3\overrightarrow{v}$ for some $v \in \Bbb{C^{3}}$ and $A$ has a non-zero eigenvalue, then $A$ is diagonalizable.
Apparently, this is true. Any help conceptualizing this would be appreciated.
Comment: Hint: what can the Jordan blocks of a $3 \times 3$ matrix look like? (There's a chance this hint is useless because you don't have the background knowledge - there's a reason we ask you to provide context here.)
Comment: By direct evaluation, the Eigenvalues are $0,0,v_x+2v_y+3v_z$.
Answer: Note that $u_1=(1,1,-1)^t$ and $u_2=(-1,2,-1)$ are linearly independent and $Au_1=Au_2=0$. Therefore, $u_1,u_2$ are eigenvectors of $A$ for the eigenvalue $0$.
If $A$ has a non-zero eigenvalue $r\neq0$, then there is a vector $u_3$ such that $Au_3=ru_3$. Moreover, $u_3$ must be linearly independent with $u_1,u_2$, since it is an eigenvector for a different eigenvalue.
Therefore, $A$ diagonalized in the basis $u_1,u_2,u_3$.


Is it ever okay to ignore a warning about an inconsistent Database schema?

Question: Can it ever be ok to ignore a Database schema = Inconsistent report?
The schema module is reporting the following mismatches:
contact
page_title: unexpected column in database
page_info: unexpected column in database

search_dataset
column type - differences on: length, default
declared: array('description' => 'TODO: please describe this field!', 'type' => 'varchar', 'length' => 16, 'not null' => TRUE)
actual: array('description' => 'TODO: please describe this field!', 'type' => 'varchar', 'length' => '64', 'not null' => TRUE, 'default' => '')

search_index
column type - differences on: length, default
declared: array('description' => 'TODO: please describe this field!', 'type' => 'varchar', 'length' => 16, 'not null' => TRUE)
actual: array('description' => 'TODO: please describe this field!', 'type' => 'varchar', 'length' => '64', 'not null' => TRUE, 'default' => '')

search_node_links
column type - difference on: length
declared: array('description' => 'TODO: please describe this field!', 'type' => 'varchar', 'length' => 16, 'not null' => TRUE, 'default' => '')
actual: array('description' => 'TODO: please describe this field!', 'type' => 'varchar', 'length' => '64', 'not null' => TRUE, 'default' => '')

Answer: It could be okay, for a time, until the module that has an out of date schema attempts to read, save, update, or delete data from an out-of-date database table. At that point, you'd get inconsistent data in your database at least, and possibly end up with a corrupted database or have your site return the WSOD (white screen of death) at worst.
The warning simply means there is at least one update that hasn't yet been run. It's always a good idea to run updates by visiting update.php or using drush updatedb whenever you update any modules or Drupal core.
Comment: Thank you @geerlingguy
The thing is, that message is there even after a run the update.php script.

How can I fix it?
Comment: Hmm. Try installing the schema module (http://drupal.org/project/schema) and see if it's report pages warn you of any mismatched tables, then edit your question and add details there.
Comment: Thank you @geerlingguy.

It's reporting 4 mismatches. Tables for which the schema and database are different: Search & Contact

contact

    page_title: unexpected column in database
    page_info: unexpected column in database

search
Show search_dataset
Show search_index
Show search_node_links
Comment: In that case, it sounds like there are some extra columns for some reason; maybe an old module you had in the past and deleted before uninstalling?

In this case, it's probably harmless to keep running the site with the mismatched schema, but it's best if you make sure you've uninstalled any modules that are no longer in use (especially before deleting them).
Comment: Thank you @geerlingguy
Is it too late for me to uninstall them now? Or will it not fix the problem?
Comment: Uninstalling the contact forms module has removed the first set of mismatches. However the search ones are still there. But when I go to my list of modules available for uninstall, there are no search related modules... :S
Comment: One way to fix the search tables would be to disable and uninstall, then re-enable search.module. I don't know how the schema would be out of sync unless one of your Drupal core updates went haywire sometime.
Comment: Thanks for that @geerlingguy.
Is there a reason why the Custom Search module would still be available in the list of Modules, even after I uninstalled it? I disabled it, uninstalled it, yet it's still appearing in the list...
Comment: Did you also delete the module out of your modules folder?
Answer: Do you have the contact module enabled?
Do you have the search module enabled?
As stated in other comments, it looks like your site wasn't re-configured properly. The correct steps for removing a module are:

Disable the module
Uninstall the module
For contrib modules: delete the code

The other possibility is that one or more update hooks were skipped, or run out of order. This can happen if you are running "unstable" code, like dev releases, or you had patched a module directly.
For now, it looks like none of those are fatal. No code should be trying to access an "unexpected column". In the case of the search module, each time the actual amount is larger than the declared amount. So, any code trying to use a larger value won't have any problem.