Correct way to use IdlingResource in Espresso Android

Question: I'm writing UI tests with Espresso. App cooperates tightly with server, so in many cases, I need to wait for either value to be calculated, or data is got and displayed, etc. Espresso suggests using IdlingResource for this.
My IdlingResource classes look like this (simple and clear example).
public class IRViewVisible implements IdlingResource {

private View view;
private ResourceCallback callback;

public IRViewVisible(View view) {
    this.view = view;
}

@Override
public String getName() {
    return IRViewVisible.class.getName();
}

@Override
public boolean isIdleNow() {
    if(view.getVisibility() == View.VISIBLE && callback != null) {
        callback.onTransitionToIdle();
        return true;
    }
    return false;
}

@Override
public void registerIdleTransitionCallback(ResourceCallback resourceCallback) {
    this.callback = resourceCallback;
}
}

Please correct me if I'm wrong anywhere (as sometimes it seems to me that my IdlingResources do not work properly).
I register the idling resource in setUp() like this:
IRViewVisible ir = new IRViewVisible(View v);
Espresso.registerIdlingResources(ir).

Unregister it on tearDown().
I found this article (there is a section called "Register a component tied to an Activity instance") — I do not use his schema, but I checked hashcode of view that was set to IdlingResource after registering (in each method), and it's not the same view — all hashes are different.
Another question: One Test class (it's results) can't have any effect on another Test class, can it?
Comment: Espresso uses IdlingResource.getName() as identifiers for idling resources, so that if you register two resources with the same name only one will be used. In your code **all** the resources have the same name, which means only the first you register will work. Maybe this helps, I'm still not sure what the role of hashCode here is.
Comment: Can you explain the behavior of this custom idling resource when it does not work properly? Also can you explain again what you do with hashcodes and why? To answer a bit here, tests **should** be independent from one another but it is your responsibility to do so. An easy way **not** to follow this best practise is to rely on global state in your code, e.g. static fields
Comment: about when it doesn't work: I register this IdlingResource, do NOT get timeout idling exception but test fails (it doesn't happen always, just sometimes but I want to understand why..) because, e.g. cannot read value from filed, caused by View.visibility is GONE.. And sure, my tests are totally independent from each other.
Comment: And with hashcode.. If I understood the article right and if the author was right with his idea (see link), the framework after calling Espresso.registerIdlingResource(ir) more that onece, using the same type of idlingResource do not contain actual link to Activity so View as well.. so I decided to check if my class contains the actual View or the old one..
Answer: I'm guessing your problem stems from getName() returning the same name for all instances of IRViewVisible. This means you can only have one registered instance of it at a time - any subsequent registrations will fail (silently!).
You mention that you clear the IdlingResources at the end of each test, but if you are register multiple instances of it at once, you need to make sure each instance has a unique name. it's not clear from your question if you're registering multiple instances of IRViewVisible in a single test.
As to your final question: Yes, it is possible. Android doesn't completely shut down the Application between test runs - just the Activities. Common things which can cause problems:

Failing to clear persistent state (saved data).
Failing to clear global state - e.g. static variables/singletons
Not waiting for background threads to finish running.

As an aside, it's worth noting that you only call onTransitionToIdle() inside isIdleNow(). This works (thanks @Be_Negative for the heads up!) but it could slow down your tests a lot, since Espresso will only poll isIdleNow() every few seconds. If you call onTransitionToIdle() as soon as the view becomes visible, it should speed things up considerably.
I needed something similar to your IRViewVisible myself, here's my effort.
Comment: 1. Espresso polls isIdleNow() every 5 seconds if onTransitionToIdle() isn't explicitly called. 2. It was mentioned that idlingResource is unregistered in tearDown. In this case getName() doesn't matter that much as long as tearDown method is called.
Comment: @Be_Negative: Re. 1: Where did you get this information? I'll update my answer if you can point me to proof. :) Re. 2: It's going to be a problem if there is more than one instance of IRViewVisible being used in a single test. I'll update my answer to make this clear.
Comment: @Be_Negative: OK, confirmed you are correct so I'll update my answer.
Comment: @Be_Negative: where in the Espresso code did you find the 5-second polling logic?
Comment: @GilVegliach I actually didn't find where 5 seconds is coming from. But if you add a log statement into you isIdleNow() method of your IdlingResource you will notice that it's being called every 5 seconds.
Comment: @vaughandroid: can you please tell me how you confirmed Be_Negative's statement? The point is that from the code there seems to be no polling, see `UiControllerImpl.loopUntil(EnumSet conditions)`.
Comment: @Be_Negative: thanks, I'll check that as soon as I have some time. In the meanwhile, read my comment above.
Comment: @vaughandroid thank you for your answer. In my code I have only several tests when register the same idlingresource several times in a single test (in others - just once for a test). But I call Espresso.unregisterIdlingResources before a next call, so I think it shouldn't cause the problem. But your suggestion with static variables and singletons may be the problem. I'll check this.
Answer: So the isIdleNow() method will never return true if you don't set a callback to the idlingResource?
I reckon it's better to refactor it like this:
@Override
public boolean isIdleNow() {
    boolean idle = view.getVisibility() == View.VISIBLE;
    if(idle && callback != null) {
        callback.onTransitionToIdle();
    }
    return idle;
}

Comment: Invoke transitions to the idle state outside idle checks.
see:
https://developer.android.com/training/testing/espresso/idling-resource
Answer: Well, first of all you shouldn't need to use Espresso IdlingResource to test server calls. If you use AsyncTasks in your server calls, Espresso will be able to know when to be idle and when not. If this is not enough: try to refactor your code in this way:
  IRViewVisible idlingResource = new IRViewVisible(yourView);
  IdlingPolicies.setMasterPolicyTimeout(waitingTime * 2, TimeUnit.MILLISECONDS);
        IdlingPolicies.setIdlingResourceTimeout(waitingTime * 2, TimeUnit.MILLISECONDS);

        // Now we wait
        Espresso.registerIdlingResources(idlingResource);

        // Stop and verify

        // Clean up
        Espresso.unregisterIdlingResources(idlingResource);

Hope to be helpful.


Find expectation and variance in balls problem.

Question: Consider a game with following rules : in initial state we have $m$ black and $n$ red balls in urn. We may randomly choose one ball from the urn and if it black, we return red ball, if it red ball - we take it back. So number of red balls non-decrease random value.
Let $\xi_k$ is a number of red balls after $k$ iterations. We want to determine $\mathbb{E}(\xi_k)$ and $\mathbb{Var}(\xi_k)$.
My attempts :
1) Let $$a(k,l) = \mathbb{P}(\xi_k = l) = \mathbb{P}(\xi_k=l, \xi_{k-1} = l-1) \mathbb{P}(\xi_{k-1} = l - 1) + \mathbb{P}(\xi_k=l, \xi_{k-1} = l) \mathbb{P}(\xi_{k-1} = l) = \frac{n+m-l + 1}{n+m}a(k-1,l-1) + \frac{l}{n+m} a(k-1,l)$$ So we have some reccurence relation. However I don't think it's possible to solve it (at least for me).
2) $\displaystyle \mathbb{P}(\xi_{k-1} = l) = \frac{m (m-1) \dots(m-l + n )}{(n+m)^k} \cdot \sum_{i_1 + \dots i_{l-n} = k+n-l} n^{i_1}\cdot(n+1)^{i_2} \dots l^{i_{l-n}}$ . The denominator always the same after $k$ repetitions, because total amounts of balls is the same, the part $m \dots(m-l + n)$ occurs because we need to pick $l - n$ times black ball. But how can we calculate the last sum? I thought it can be calculated with multinomial coefficients.
Any hints?
Answer: Equivalently, we can consider colouring those black balls when picked. Number those balls from $1-m$ (black balls) and from $m+1 - m+n$ (red balls)
Note that we're only interested in the number of black balls which were coloured red, because $\mathbb E[X(k)+n] = \mathbb E[X(k)] +n$, while $Var(X(k)+n) = Var(X(k))$, where $n-$number (before starting a game) of red balls and $X(k)$ number of red balls after $k'$th iteration which have replaced black balls.
At the beginning we have $m-$black balls, so let $X(k) = \sum_{j=1}^m Y_j(k)$, where $Y_j(k)$ is $\{0,1\}$ random variable, $1$ when $j'$th black ball is coloured red at $k'$th iteration (or before), and $0$ if it's still black after $k'$th iteration.
Then $\mathbb E[X(k)] = \sum_{j=1}^m \mathbb E[Y_j(k)] = m\mathbb E[Y_1(k)] = m \mathbb P(Y_1(k) = 1) = m - m\mathbb P(Y_1(k)=0) = m - m (\frac{m+n-1}{m+n})^k$
Second equality sign due to the same distribution, and the last one $\mathbb P(Y_1(k) = 0) = (\frac{m+n-1}{n+m})^k$, since $k-$ times we need to pick ball different from $1$.
So your $\mathbb E[\xi_k] = \mathbb E[X(k) + n] = n + m - m(1-\frac{1}{m+n})^k$
Now looking at variance, we have:
$Var(X(k)) = \mathbb E[X^2(k)] - (\mathbb E[X(k)])^2$
So all we are left with is to compute $\mathbb E[X^2(k)] = \sum_{j=1}^m \mathbb E[Y_j^2(k)] + 2\sum_{1 \le i < j \le m} \mathbb E[Y_i(k)Y_j(k)] = \mathbb E[X(k)] + 2{m \choose 2} \mathbb E[Y_1(k)Y_2(k)]$.
The last thing is $\mathbb E[Y_1(k)Y_2(k)] = 1 - \mathbb P(Y_1(k)Y_2(k) = 0) = 1 - (\frac{m+n-2}{m+n})^2$
I'll leave you with all those components to glue up together
Comment: I would like to edit : $\mathbb{P}(Y_1 Y_2 = 0)$ iff $Y_1 = 0$ or $Y_2 = 0$. In your solution it's looks like that $Y_1 = 0$ and $Y_2 = 0$


when is fileUploadListener invoked?

Question: Can anybody tell me when is the fileUploadListener invoked and also in which phase.I am using PrimeFaces.
Comment: Actually i am new to JSF. How can I print the current phase ID?
Comment: Why are you asking such a trivial question which you could answer yourself by just debugging the code and/or printing/logging the current phase ID? What exactly is the problem you're actually trying to solve? Ask a question about exactly that problem instead.
Answer: fileUploadListener is executed before phase APPLY_REQUEST_VALUES 2 (I'm using PF 3.5)
You can checkout current phase implementing a lifecycle listener, this way:
package mypackage;

import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

public class LifeCycleListener implements PhaseListener {

public PhaseId getPhaseId() {
    return PhaseId.ANY_PHASE;
}

public void beforePhase(PhaseEvent event) {
    System.out.println("START PHASE " + event.getPhaseId());
}

public void afterPhase(PhaseEvent event) {
    System.out.println("END PHASE " + event.getPhaseId());
}

}

Then, add your new Listener to faces-config.xml:
<lifecycle>
<phase-listener>mypackage.LifeCycleListener</phase-listener>
</lifecycle>

Don't forget to add your logs for primefaces messages!
Cheers!

when is fileUploadListener invoked?


Colorbox + jCarousel + slideshow + compact mode?

Question: I'm looking for a good solution (preferably as one integrated module) that would allow to display images in a multi-value image field in any kind of a lightbox, have a compact mode so that only the first image is shown, display a carousel beneath, and provide slideshow.
I've tried: Colorbox, Field Slideshow, jCarousel, Shadowbox.
Colorbox was nicely integrated with Field Slideshow and provided a pager, but it had a strange bug which causes certain images on the main page beneath to be cloned upon every click within the Colorbox layer. Shadows wins over it even though is paid. Colorbox does not have a compact mode - if I set explicitly number of images to show to 1, all remaining images become unavailable and the slideshow is automatically disabled, otherwise, all of them appear on the node.
A while ago I gave also a try to Lightbox2, but I gave up on it, being unsuccessful at enabling its compact mode.
Answer: You basically want to output the images inside an HTML list, using, say views, and then install a jQuery plugin to do the slideshow for you.
You can use an existing module, however we often find it's easier to just install the jQuery plugin, and initialise your slideshow yourself.
Assuming your view outputs an HTML list, which is pretty easy to get set up, the rest isn't so much a Drupal question as it is a case of following the instructions for the exact slideshow plugin you're using.
We quite like http://jquery.malsup.com/cycle/ which has all the usual options, good documentation, and works well in a lot of different ways.


Why is the covariace of a vector writen like this?

Question: Say I have a white noise process $w_a$.
Why is the co variance matrix of the vector written as $E(w_a*w_a^T)$?
Isn't the expected value equal to $E(x) =\int xf(x) $?
So for example isn't the first component of the covariance matrix going to be $E(w_{a1}^2) =\int w_{a1}^2f(w_{a1}) $ so how is that equal to $\sigma_{a1}^2$?
Comment: If you intend $w_a$ to be a vector, then just what do you mean by "$w_a^2$"?
Comment: @whuber, thanks! I calrified that it was just the first component
Answer: Denote the covariance matrix by $\Sigma = \text{E}(w_aw_a^T)$. As you note, the $i$th entry of the diagonal of the covariance matrix should be $\text{Var}(w_{ai}) = \sigma_{ai}^2 $. Since we're dealing with a white noise process, we assume $\text{E}(w_{ai}) = 0$ for each $i$. So
$$
\begin{align*}
\text{Var}(w_{ai}) &= \text{E}(w_{ai}^2) - \text{E}(w_{ai})^2 \\
& =\text{E}(w_{ai}^2) \\
& = \Sigma_{ii}.
\end{align*}
$$
This shows that the formula produces the correct values for the diagonal. Now the off-diagonal entries should be
$$
\begin{align*}
\Sigma_{ij} & = \text{Cov}(w_{ai},w_{aj}) \\
& = \text{E}(w_{ai}w_{aj}) - \text{E}(w_{ai})\text{E}(w_{aj}) \\
& = \text{E}(w_{ai}w_{aj}),
\end{align*}
$$
which is precisely the $ij$th entry of the matrix $\text{E}(w_aw_a^T)$. So that's where the formula comes from.


how to change node edit path from node/[nid]/edit to node/[nid]/update?

Question: I have Pathauto which changes node/[nid] to having a path of [title]; I then use subpathauto to change node/[nid]/edit to [title]/edit.
But now how can I change the edit fragment? I want to change all instances of edit to update. so the URLs would be [title]/update instead of [title]/edit.
I cannot use arguments or wildcards in Pathauto, so I cannot specify a path like */*/edit to be */*/alter, but that is effectively what I would like to happen.
Comment: I would also advise against changes that don't seem to add any value, but have to potential to introduce problems. Other modules will assume that the edit path is node/[nid]/edit so you could break other things, it could confuse any users who have prior experience with drupal, and as mentioned it could confuse future developers (although if coded properly and documented this should be avoidable).
Comment: Why would you want to implement a change that will confuse the succeeding developers who will potentially work on the same project by modifying a widely-known Drupal convention?
Answer: I think this is a legit request as long as you add an additional alias as opposed to overwriting system paths.
I would implement hook_node_insert() and then use path_save() to set your custom edit path on node creation. You will also probably need to make sure that this hook runs after the Pathauto module has set its path, so you can use the alias it sets as part of your additional edit alias.


How to open task scheduler ?

Question: The path to task scheduler is
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\System Tools

I tried to open it
public static void main(String[] args) {

Runtime.getRuntime().exec("cmd /c start \"+\"%ProgramData%\\Microsoft\\Windows\\Start Menu\\Programs\\Accessories\\System Tools\\Task Scheduler.exe\");

However, the above does not compile . How can I improve my code ?
Comment: if you want the platform-independent task scheduler, use http://quartz-scheduler.org/
Comment: Look at any syntax highlighting, and the error message the compiler's giving you. That string isn't terminated (you have a closing quote for the internal quoted path for `cmd`, but not one for the Java string literal).
Answer: If you're only wanting the compiler error fixed, you need to properly escape the path like below.
   public static void main(String[] args) throws IOException {
      Runtime.getRuntime().exec("cmd /c start \"" + "%ProgramData%\\Microsoft\\Windows\\Start Menu\\Programs\\Accessories\\System Tools\\Task Scheduler.exe\"");
   }

If you need quotes in the string, you escape with a \.
If you need to just open the task scheduler on Windows, try the following:
Runtime.getRuntime().exec("cmd /c " + "%windir%\\system32\\taskschd.msc /s");

Comment: Is there not an escaped quote missing in your last string, i. e. `..."%windir%\\system32\\taskschd.msc\" /s");`?
Comment: @FrankPl good point.  I guess it doesn't matter since there are no spaces in the path.  I have corrected.

How to open task scheduler ?


Como mudar a raiz do meu site, sendo que a pasta está em um nível acima?

Question: A minha dúvida está no escalonamento do .htaccess, porquanto só consigo fazer com que a raiz do meu site seja a pasta public_html ou alguma outra pasta dentro de public_html, mas preciso de uma pasta que está um nível acima.
RewriteEngine On

RewriteBase /
RewriteCond %{HTTP_HOST} ^www.meusite.com.br/$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www.meusite.com.br/$
RewriteCond %{REQUEST_URI} !meudiretorio/
RewriteRule (.*) /meudiretorio/$1 [L]

Comment: Sendo seu diretório `/var/www/public_html`, você precisa acessar `/var/www/outra_pasta`?
Comment: Exatamente, eu quero que minha pasta raiz seja outra.
Answer: Isso não é feito no .htaccess.
Você deve alterar a configuração do Apache, no httpd.conf. Veja DocumentRoot.
Comment: Entendi, porém o caminho que está na documentação está diferente e não consigo achar esse arquivo.
Tem algum lugar no cPanel que eu consiga alterar o arquivo?
Comment: Veja se este link te ajuda https://support.hostgator.com/articles/what-is-a-document-root-folder
Comment: Ainda não consegui localizar, o documento só me mostra como fazer essa alteração em subdomínios, mas quando é no domínio primário não acho a informação.
Comment: Aqui tem informações para alterar do domínio primário. Faz tempo que não trabalho com CPANEL então não sei orientar melhor. Mas por qual motivo precisa alterar o documentroot do domínio primário?


Linker error while attempting to create my own shared library using CMake

Question: I'm trying to build my own shared library and to build an other application to use it (nothing groundbreaking, I'm learning CMake). I have written theses CMakeLists :
For the lib:
cmake_minimum_required(VERSION 3.9)

project(MyLib LANGUAGES CXX VERSION 1.0 DESCRIPTION "MyLib")
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++20")

include(GNUInstallDirs)

set(SOURCES src/MyLibsources.cpp)
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)
add_library(MyLib SHARED ${SOURCES})
target_include_directories(MyLib PUBLIC ${CMAKE_CURRENT_LIST_DIR}/include)

#here is a reference to a static lib that I wrote and with which I have experienced no trouble for now
add_subdirectory(AKML-lib/)
target_link_libraries(MyLib PRIVATE AKML)
target_include_directories(MyLib PRIVATE src/AKML-lib/)
set_property(TARGET AKML PROPERTY CXX_STANDARD 20)

install(TARGETS MyLib
    LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
    PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
#install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/include/ DESTINATION include)

For the little applet :
cmake_minimum_required(VERSION 3.9)

project(MyUtility LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++20")

#set(CMAKE_PREFIX_PATH ${CMAKE_INSTALL_LIBDIR})
find_library(MyLib NAMES MyLib.dylib PATHS "/usr/local/lib/" REQUIRED NO_DEFAULT_PATH)
message(${MyLib})

set(SOURCES src/main.cpp)
add_executable(MyUtility ${SOURCES})
target_link_libraries(MyUtility PUBLIC MyLib)

Everything build and install fine for the lib, but when I try to build my applet I encounter this message in the main file of the application : fatal error: 'MyLibHeader.hpp' file not found in #include "MyLibHeader.hpp".
My project structure is as follows :
For the lib :
\include\
    -> MyLibHeader.hpp
\src\
    -> MyLibsources.cpp
\AKML-lib\
    -> files of the static lib which is not today topic
CMakeLists.txt

For the application :
\src\
    -> main.cpp
CMakeLists.txt

With the message command I have checked that CMake was actually finding the library that he does correctly.
I have tried for several hours now and I'm quite desperate. I give credit to theses previous answer that were a great help for previous debugging (How to create a shared library with cmake?) but, for this issue, I don't know what to do.
Thank you for your help!
PS: I'm building on Macos Sonoma
Comment: `find_library` just searches for a dynamic library and returns the path. You probably want to use the [CMakePackageConfigHelpers](https://cmake.org/cmake/help/v3.25/module/CMakePackageConfigHelpers.html) to write a MyLibConfig.cmake that you can then include with `find_package`
Comment: A library file (`MyLib.dylib` in your case) doesn't contain information about directory where its header files reside. Aside from linking your executable with MyLib library, you need to specify include directory, e.g. with `target_include_directories` command.
Comment: @Tsyvarev thank you for your answer! should I add target_include_directories in the CMakeLists of the application ? If I do so, I would have to link to the header files of the lib ? I was thinking that after "compiling" (I'm not sure for this term) the library, I would not have to bother anymore in the child applications with its source and header files and only use the dylib file : was I mistaking ?
Comment: "I was thinking that after "compiling" (I'm not sure for this term) the library, I would not have to bother anymore in the child applications with its source and header files and only use the dylib file : was I mistaking ?" - No, this is a false assumption. A `.dylib` file alone doesn't allow application to include a library header via `#include`.
Answer: find_library won't solve any related path and resouces for you (e.g., your .h or .hpp) but just .lib in this case. You need to exporting your target and use IMPORTED it later on or creating your package like @Botje said, and use find_package for your created package. Otherwise, you could use add_subdirectory to directly include your library project, but it must be located in subfolder.


React native gradlew assembleRelease build failed. Execution failed for task ':app:mergeReleaseResources'

Question: I'm encountering with this error, when run ./gradlew assembleRelease. I've tinkering about in some hours. Help pls. It was once builded successfully but, after my attempts of clearing something and combining different folders from my git history, nothing could rescue.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:mergeReleaseResources'.
> [raw/app] /home/horhi/code/projects/ankilan/android/app/src/main/res/raw/app.json [raw/app] /home/horhi/code/projects/ankilan/android/app/build/generated/res/react/release/raw/app.json: Error: Duplicate resources
  [raw/node_modules_reactnativevectoricons_glyphmaps_materialcommunityicons] /home/horhi/code/projects/ankilan/android/app/src/main/res/raw/node_modules_reactnativevectoricons_glyphmaps_materialcommunityicons.json[raw/node_modules_reactnativevectoricons_glyphmaps_materialcommunityicons] /home/horhi/code/projects/ankilan/android/app/build/generated/res/react/release/raw/node_modules_reactnativevectoricons_glyphmaps_materialcommunityicons.json: Error: Duplicate resources
  [raw/node_modules_reactnativevectoricons_glyphmaps_fontawesome5free_meta] /home/horhi/code/projects/ankilan/android/app/src/main/res/raw/node_modules_reactnativevectoricons_glyphmaps_fontawesome5free_meta.json[raw/node_modules_reactnativevectoricons_glyphmaps_fontawesome5free_meta] /home/horhi/code/projects/ankilan/android/app/build/generated/res/react/release/raw/node_modules_reactnativevectoricons_glyphmaps_fontawesome5free_meta.json: Error: Duplicate resources
  [raw/node_modules_reactnativevectoricons_glyphmaps_fontawesome] /home/horhi/code/projects/ankilan/android/app/src/main/res/raw/node_modules_reactnativevectoricons_glyphmaps_fontawesome.json[raw/node_modules_reactnativevectoricons_glyphmaps_fontawesome] /home/horhi/code/projects/ankilan/android/app/build/generated/res/react/release/raw/node_modules_reactnativevectoricons_glyphmaps_fontawesome.json: Error: Duplicate resources
  [raw/node_modules_reactnativevectoricons_glyphmaps_fontisto] /home/horhi/code/projects/ankilan/android/app/src/main/res/raw/node_modules_reactnativevectoricons_glyphmaps_fontisto.json   [raw/node_modules_reactnativevectoricons_glyphmaps_fontisto] /home/horhi/code/projects/ankilan/android/app/build/generated/res/react/release/raw/node_modules_reactnativevectoricons_glyphmaps_fontisto.json: Error: Duplicate resources
  [raw/node_modules_reactnativevectoricons_glyphmaps_feather] /home/horhi/code/projects/ankilan/android/app/src/main/res/raw/node_modules_reactnativevectoricons_glyphmaps_feather.json[raw/node_modules_reactnativevectoricons_glyphmaps_feather] /home/horhi/code/projects/ankilan/android/app/build/generated/res/react/release/raw/node_modules_reactnativevectoricons_glyphmaps_feather.json: Error: Duplicate resources
  [raw/node_modules_reactnativevectoricons_glyphmaps_entypo] /home/horhi/code/projects/ankilan/android/app/src/main/res/raw/node_modules_reactnativevectoricons_glyphmaps_entypo.json   [raw/node_modules_reactnativevectoricons_glyphmaps_entypo] /home/horhi/code/projects/ankilan/android/app/build/generated/res/react/release/raw/node_modules_reactnativevectoricons_glyphmaps_entypo.json: Error: Duplicate resources
  [raw/node_modules_reactnativevectoricons_glyphmaps_ionicons] /home/horhi/code/projects/ankilan/android/app/src/main/res/raw/node_modules_reactnativevectoricons_glyphmaps_ionicons.json   [raw/node_modules_reactnativevectoricons_glyphmaps_ionicons] /home/horhi/code/projects/ankilan/android/app/build/generated/res/react/release/raw/node_modules_reactnativevectoricons_glyphmaps_ionicons.json: Error: Duplicate resources
  [raw/node_modules_reactnativevectoricons_glyphmaps_fontawesome5free] /home/horhi/code/projects/ankilan/android/app/src/main/res/raw/node_modules_reactnativevectoricons_glyphmaps_fontawesome5free.json   [raw/node_modules_reactnativevectoricons_glyphmaps_fontawesome5free] /home/horhi/code/projects/ankilan/android/app/build/generated/res/react/release/raw/node_modules_reactnativevectoricons_glyphmaps_fontawesome5free.json: Error: Duplicate resources
  [raw/node_modules_reactnativevectoricons_glyphmaps_simplelineicons] /home/horhi/code/projects/ankilan/android/app/src/main/res/raw/node_modules_reactnativevectoricons_glyphmaps_simplelineicons.json[raw/node_modules_reactnativevectoricons_glyphmaps_simplelineicons] /home/horhi/code/projects/ankilan/android/app/build/generated/res/react/release/raw/node_modules_reactnativevectoricons_glyphmaps_simplelineicons.json: Error: Duplicate resources
  [raw/node_modules_reactnativevectoricons_glyphmaps_evilicons] /home/horhi/code/projects/ankilan/android/app/src/main/res/raw/node_modules_reactnativevectoricons_glyphmaps_evilicons.json [raw/node_modules_reactnativevectoricons_glyphmaps_evilicons] /home/horhi/code/projects/ankilan/android/app/build/generated/res/react/release/raw/node_modules_reactnativevectoricons_glyphmaps_evilicons.json: Error: Duplicate resources
  [raw/node_modules_reactnativevectoricons_glyphmaps_materialicons] /home/horhi/code/projects/ankilan/android/app/src/main/res/raw/node_modules_reactnativevectoricons_glyphmaps_materialicons.json [raw/node_modules_reactnativevectoricons_glyphmaps_materialicons] /home/horhi/code/projects/ankilan/android/app/build/generated/res/react/release/raw/node_modules_reactnativevectoricons_glyphmaps_materialicons.json: Error: Duplicate resources
  [raw/node_modules_reactnativevectoricons_glyphmaps_antdesign] /home/horhi/code/projects/ankilan/android/app/src/main/res/raw/node_modules_reactnativevectoricons_glyphmaps_antdesign.json [raw/node_modules_reactnativevectoricons_glyphmaps_antdesign] /home/horhi/code/projects/ankilan/android/app/build/generated/res/react/release/raw/node_modules_reactnativevectoricons_glyphmaps_antdesign.json: Error: Duplicate resources
  [raw/node_modules_reactnativevectoricons_glyphmaps_foundation] /home/horhi/code/projects/ankilan/android/app/src/main/res/raw/node_modules_reactnativevectoricons_glyphmaps_foundation.json   [raw/node_modules_reactnativevectoricons_glyphmaps_foundation] /home/horhi/code/projects/ankilan/android/app/build/generated/res/react/release/raw/node_modules_reactnativevectoricons_glyphmaps_foundation.json: Error: Duplicate resources
  [raw/node_modules_reactnativevectoricons_glyphmaps_octicons] /home/horhi/code/projects/ankilan/android/app/src/main/res/raw/node_modules_reactnativevectoricons_glyphmaps_octicons.json   [raw/node_modules_reactnativevectoricons_glyphmaps_octicons] /home/horhi/code/projects/ankilan/android/app/build/generated/res/react/release/raw/node_modules_reactnativevectoricons_glyphmaps_octicons.json: Error: Duplicate resources
  [raw/node_modules_nativebase_dist_src_basic_icon_nbicons] /home/horhi/code/projects/ankilan/android/app/src/main/res/raw/node_modules_nativebase_dist_src_basic_icon_nbicons.json [raw/node_modules_nativebase_dist_src_basic_icon_nbicons] /home/horhi/code/projects/ankilan/android/app/build/generated/res/react/release/raw/node_modules_nativebase_dist_src_basic_icon_nbicons.json: Error: Duplicate resources
  [raw/node_modules_reactnativevectoricons_glyphmaps_zocial] /home/horhi/code/projects/ankilan/android/app/src/main/res/raw/node_modules_reactnativevectoricons_glyphmaps_zocial.json   [raw/node_modules_reactnativevectoricons_glyphmaps_zocial] /home/horhi/code/projects/ankilan/android/app/build/generated/res/react/release/raw/node_modules_reactnativevectoricons_glyphmaps_zocial.json: Error: Duplicate resources

* Try:
Run with --stacktrace option to get the stack trace. Run with --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.5/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 58s
65 actionable tasks: 11 executed, 54 up-to-date

Answer: I had this exact same errormessage today. Those are the things I have done to get the error solved. Additional, I add the things I have done previously, in case, they are correlated:
From this related Stackoverflow answer https://stackoverflow.com/a/55245362
1) Deleting /android/app/build/...
2) Deleting /android/build/...
3) Comment out the line apply from "../../node_modules/react-native/react.gradle" in ./android/app/build.gradle
4) Deleting /android/app/src/main/assets/index.android.js
5) Rebundle from Rootfolder of your project via:
react-native bundle --platform android --dev false --entry-file index.js --bundle-output
android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
Here i alteret the OG answer a little, decide for yourself which way you want to use
5) Build Releasebuild from ./android/... via
.\gradlew assembleRelease
This worked for me. Other things I done before in case it still wont work for you:

Deleting ./node_modules/... and refetch dependencies via npm install or yarn install
Link react-native-vector-icons via react-native link react-native-vector-icons from your projectroot

Hope it helps!
Comment: What is the need for step#3 ?
Comment: Thanks man, All step 1 to step 4 is working, except for step 5

I run react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res/ to make it work.
Comment: I tried use android studio for creating apk, and that helped. I'll try this when I'll create apk again


Inequality with fraction

Question: I have tried with some numbers and the following dependency is true. But I have no idea on how to prove it? Notice that, the maximal value of $\ell$ is $n$ and the values of $l$ can be $l=k+1, k+2, \ldots, n$. Thanks in advance!
$$ \frac{n}{n+1}\cdot\frac{l}{k}>1, l>k$$
Comment: are the variables assumed to be positive?
Comment: Yes, all variables are positive.
Answer: Note that
$$ \frac{n}{n+1}\cdot\frac{l}{k}>\frac{n}{n+1}\cdot\frac{n}{n-1}=\frac{n^2}{n^2-1}>1$$

Inequality with fraction


Proof by induction involving inequalities and summation.

Question: Show that
$$\sum^n_{j=1}\frac{1}{j^2}\leq 2-\frac{1}{n}$$
$\forall n\geq 1$
Let us denote our proposition by $P_n$. Testing for $P_1$ this shows us that
$$\sum^1_{j=1}\frac{1}{1}\leq2-1$$
$\therefore{\text{true for $P_1$}}$
Now, assuming that it holds for some natural number $m$. $P_m$ is true, where $m$ has the same boundaries as $n$. I.e $m\geq1$. Now we want to show as $P_m$ is true $P_m\rightarrow P_{m+1}$
$$P_m:\sum^m_{j=1}\frac{1}{j^2}\leq2-\frac{1}{m}$$
$$P_{m+1}: \sum^{m+1}_{j=1}\frac{1}{j^2}\leq2-\frac{1}{m+1}$$
We can manipulate the series to prove that it holds for $P_{m+1}$ too.
rewriting the sum we get $$\sum^{m+1}_{j=1}\frac{1}{j^2}=\sum^{m}_{j=1}\frac{1}{j^2}+\frac{1}{(m+1)^2}$$
$$\leq2-\frac{1}{m}+\frac{1}{(m+1)^2}$$
$$=2-\frac{(m+1)^2-m}{m(m+1)^2}$$
$$\leq2-\frac{1}{m+1}-\frac{2m-1}{m(m+1)^2}$$
This is where I'm confused. I'm stuck with something that does not equals our hypothesis. Have I done something wrong? Cause how I see it, most of the tricks in induction is just being good at algebra.
Comment: Being good at algebra helps with induction, and keep the end goal in mind
Comment: Did you mean $2-\dfrac{(m+1)^2\color{red}-m}{m(m+1)^2}$?
Comment: yeah, i'll edit the question now
Answer: Just say
$2-\dfrac1m+\dfrac1{(m+1)^2}\le 2-\dfrac1m+\dfrac1{m(m+1)}=2-\dfrac1{m+1}$
Answer: Hint:
The proof can be based on the inequality
$$\frac1{(n+1)^2}<\frac1{n(n+1)}$$
where the RHS forms a well-known telescoping series.
Comment: Oh, I never knew about telescoping series until now! Thank you so much, i'll add this into my toolbox.


atan() returns Nan

Question: I am writing my first project in JavaScript. As I understand, Math.atan() returns a number (angle in radians).
But somehow, it returns Nan.
Using console.log(), I have checked all the variables (ry, rx, this.y, this.x), and all are numbers. But for
console.log(Bullet.q)

i get "NaN".
function createBullet(rx, ry){
    let Bullet = kontra.Sprite({
        x: player.x,
        y: player.y,
        v: 4,
        q: Math.atan((ry-this.y)/(rx-this.x)),
       // k: this.v/Math.sqrt((ry-this.y)*(ry-this.y)+(rx-this.x)*(rx-this.x)),
        //dx: (rx-this.x)*this.k,
        dx: Math.cos(this.q)*this.v,
        //dy: (ry-this.y)*this.k,
        dy: Math.sin(this.q)*this.v,

    });

    console.log(ry);
    console.log(Bullet.q);
    console.log(Bullet.dy);

}

I am new to this language, am I missing something?
Comment: you need to use a getter to reach sibling own properties using `this.property`, otherwise, `this` is lexical to the surrounding scope. in other words, `this.x` is not `Bullet.x`.
Comment: you need to return Bullet from the function, call it to retrieve the value.
Comment: actually the simple fix is to just change `this.x` to `player.x`, since that's what you need and it's right there anyway. same for `y`...
Comment: Is there a possibility of `rx-this.x` being `0` ?
Comment: @DominikMatis no.
Answer: There's also a "clever" way to do it by taking advantage of JS's leaky assignments and using an extra top-level var to store the property you need outside the object literal:
function createBullet(rx, ry){
    var q,v;
    let Bullet = kontra.Sprite({
        x: player.x,
        y: player.y,
        v: v = 4,
        q: q= Math.atan((ry-player.y)/(rx-player.x)),
        dx: Math.cos(q)*v,
        dy: Math.sin(q)*v,

    });

    console.log(ry);
    console.log(Bullet.q);
    console.log(Bullet.dy);

}

that said, i don't really like clever code and you might want to compute those properties before the literal, for better readability.
The way a getter could be used inline:
var obj = {
 a: 1,
 b: 2,
 get sum() { return this.a+this.b}
};

alert(obj.sum);

atan() returns Nan


Manually activate all audio playback

Question: I have developed an app that uses text-to-speech and speech-to text functionality. Upon testing on different devices, I discovered that some devices had audio playback preferences that were not activated, and even though the main sound levels were on, the artificial speech engine was not being played back outloud. I went in and turned on all audio levels, and the problem was solved. So, I'm wondering if its possible to manually activate all sound levels on a device upon launching my application. Thanks!
Answer: try to do something like this, under onCreate method, at the beginning:
<code>AudioManager am = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
if(am.getStreamVolume(AudioManager.STREAM_MUSIC)==0)
for(int i=0;i<5;i++) am.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
</code>
This will raise the music volume from 0 to 5 segments (100% volume is 15 segments, unless in any particular ROM) for STREAM_MUSIC, the audio channel of every classic app!
Comment: You've got skillz Maik, thank you, this works perfectly!

Manually activate all audio playback


Insert data into entity programmatically

Question: I've installed contact storage module, it's provide storage for Contact messages which are fully-fledged entities in Drupal 8.
What I want to do, is to insert data programmatically from my custom module into the entity of the contact storage
Comment: Sounds straightforward enough, where are you stuck? What does your code so far look like? Please edit it into the question so we can get an idea of the problem
Answer: Yep. Just use any of the methods available to create the entity and save it.
<code>use Drupal\contact\Entity\Message;

$message = Message::create([
    // And other fields required...
    'subject' => 'Subject',
    'message' => 'Message...',
    'recipient' => 1,
]);
$message->save();
</code>
Comment: @Hugo I've added bundle type before required fields like this  `Message::create([
          'contact_form' => 'feedback',
          'subject' => '.......',
          'name'=> ......,
          'mail' => ...........,
          'message' => '......',
    ]);`
Comment: Thanks so much, but when I used this, I got this error Missing bundle for entity type contact_message in Drupal\Core\Entity\ContentEntityStorageBase->doCreate()
Comment: It's solved now, it was missing the bundle type, thanks so much john
Comment: @MohamedOsamaGbril What did you have for the bundle?


Excluding all files that begin with X in .htaccess maintenance mode redirect

Question: Here's my maintenance mode redirect:
# MAINTENANCE-PAGE REDIRECT
<IfModule mod_rewrite.c>
 RewriteEngine on
 RewriteCond %{REMOTE_ADDR} !^0\.0\.0\.0
 RewriteCond %{REQUEST_URI} !\.(jpe?g?|png|gif) [NC]
 RewriteCond %{REQUEST_URI} !^/ads/.*$ [NC]
 RewriteCond %{REQUEST_URI} !^ad_([0-9a-zA-Z]+)\.php$ [NC]
 RewriteCond %{REQUEST_URI} !^/assets/.*$ [NC]
 RewriteCond %{REQUEST_URI} !/new/$ [NC]
 RewriteRule .* /new/ [R=302,L]
</IfModule>

I'm trying to exclude all files that begin with "ad_" from the redirect. I'm trying that with this line:
 RewriteCond %{REQUEST_URI} !^ad_([0-9a-zA-Z]+)\.php$ [NC]
Unfortunately, there are hundreds of these files in the public root folder, not in their own subfolder. Examples of these files:

ad_login.php
ad_message_editor.php
ad_manage_mm_account_1.php

These file names include anywhere from 1-4 underscores, but they all have at least one, starting with "ad_".
Answer: Try to add _ to your regexp, like
 RewriteCond %{REQUEST_URI} !^ad_([0-9a-zA-Z_]+)\.php$ [NC]
UPD Edit:
And as @MrWhite mentioned in comment - add slash prefix as you have in other rules.
Comment: They are also missing the slash prefix on the URL-path (as shown in the other conditions).
Comment: Ah, yeah, that's true @MrWhite !


How to add missing times in column in Excel for interpolation

Question: I have an Excel spreadsheet with data in two columns as Time and Temperature. The Time column has values such as follows, where there are some skipped seconds:
2017-10-17 14:18:15
2017-10-17 14:18:17
2017-10-17 14:18:18
2017-10-17 14:18:19
2017-10-17 14:18:21
2017-10-17 14:18:22

Is it possible to have Excel add in those missing times with a corresponding blank row (so then I can do interpolation on those blank spots?)
Comment: if you use PivotTable, you can probably group by seconds to get the missing dates http://www.contextures.com/xlPivot07.html
Answer:
I am not sure how your data look like but this is what you can do if you don't want to use VBA.
Use this formula from cell B2 and drag down:
=IF(B1="","",IF(N(B1),IF(ROW(A2)-ROW($A$1)-1<SECOND(MAX($A$2:$A$7)-MIN($A$2:$A$7))+1,B1+TIME(0,0,1),""),A2))

What this does is to determine how many seconds between max and min and then use the rows as a reference (you can change this part based on your data structure).  Try and see if this works for you or not.
Answer: Try this! It assumes your times are in column A, with a header in cell A1
Sub AddRows()

'Finds out what row to go up to
 Dim lRow As Long
 lRow = Cells(Rows.Count, 1).End(xlUp).Row

 For i = 2 To lRow + 1

'If the difference between the cell below is more than a second, then add a
row above and skip the next i
If Cells(i + 1, 1) - Cells(i, 1) > 0.000011575 Then
   Cells(i + 1, 1).Select
   Selection.EntireRow.Select
   Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
   lRow = lRow + 1
   Cells(i + 1, 1).Select
   Cells(i + 1, 1).Value = Cells(i, 1).Value + 0.000011575
   i = i + 1

Else

End If

Next i

End Sub


How to Find Top N Similar Words in a Dictionary of Words / Things?

Question: I have a list of str that I want to map against. The words could be "metal" or "st. patrick". The goal is to map a new string against this list and find Top N Similar items. For example, if I pass through "St. Patrick", I want to capture "st patrick" or "saint patrick".
I know there's gensim and fastText, and I have an intuition that I should go for cosine similarity (or I'm all ears if there's other suggestions). I work primarily with time series, and gensim model training doesn't seem to like a list of words.
What should I aim for next?
Comment: Does GloVe look something you want?
Answer: First, you must decide if you are interested in ortographic similarity or semantic similarity.
Ortographic similarity
In this case, you score the distance between two strings. There are various metrics for computing edit distance. Levenshtein distance is the most common: you can find various python implementations, like this.
"gold" is similar to "good", but not similar to "metal".
Semantic similarity
In this case, you measure how much two strings have a similar meaning.
fastText and other word embeddings fall into this case, even if they also take into account ortographic aspects.
"gold" is more similar to "metal" than to "good".
If you have a limited number of words in your list, you can use an existing word embedding, pretrained on your language. Based on this word embedding, you can compute the word vector for each word/sentence in your list, then compare the vector for your new word with the vectors from the list, using cosine similarity.
import fasttext
import numpy as np

# download English pretrained model
fasttext.util.download_model('en', if_exists='ignore')
ft = fasttext.load_model('cc.en.300.bin')

def cos_sim(a, b):
    """Takes 2 vectors a, b and returns the cosine similarity according
    to the definition of the dot product
    (https://masongallo.github.io/machine/learning,/python/2016/07/29/cosine-similarity.html)
    """
    dot_product = np.dot(a, b)
    norm_a = np.linalg.norm(a)
    norm_b = np.linalg.norm(b)
    return dot_product / (norm_a * norm_b)

def compare_word(w, words_vectors):
    """
    Compares new word with those in the words vectors dictionary
    """
    vec=ft.get_sentence_vector(w)
    return {w1:cos_sim(vec,vec1) for w1,vec1 in words_vectors.items()}

# define your word list
words_list=[ "metal", "st. patrick", "health"]

# compute words vectors and save them into a dictionary.
# since there are multiwords expressions, we use get_sentence_vector method
# instead, you can use  get_word_vector method
words_vectors={w:ft.get_sentence_vector(w) for  w in words_list}

# try compare_word function!

compare_word('saint patrick', words_vectors)
# output: {'metal': 0.13774191, 'st. patrick': 0.78390956, 'health': 0.10316559}

compare_word('copper', words_vectors)
# output: {'metal': 0.6028242, 'st. patrick': 0.16589196, 'health': 0.10199054}

compare_word('ireland', words_vectors)
# output: {'metal': 0.092361264, 'st. patrick': 0.3721483, 'health': 0.118174866}

compare_word('disease', words_vectors)
# output: {'metal': 0.10678574, 'st. patrick': 0.07039305, 'health': 0.4192972}

Comment: Thank you! Sorry I have been away for work. This is perfect!


Procurar carácter num array php

Question: Imaginando que tenho o seguinte array:
<code>$o_meu_array = array("123_rui", "125_joao", "287_manuel");
</code>
Agora quero encontrar dentro do meu array "123". Ao encontrar o 123, quero substituir o 123 por outro valor dado pelo utilizador. Por exemplo, se o utilizador meter "10", vai ficar "10_rui". É possível fazer isto?
Comment: quer o código ou o caminho das pedras ?
Comment: se possível o código senão todos os comentários são bem vindos. obrigado
Answer: Para substituir valores em um array você pode utilizar a função preg_replace()
<code>$meu_array = array("123_rui", "125_joao", "287_manuel");
$procurar = "/123/";
$substituir = "10";
$meu_array = preg_replace($procurar, $substituir, $meu_array);
</code>
Exemplo
Comment: @pc_oc Seria isso https://ideone.com/vGCmko ?
Comment: @pc_oc isso você faria `/123_([0-9])*/`, ou seja 123_qualquer_numero_qualquer_tamanho, você pode aceitar letras, números, caracteres e etc, para mais informações sobre expressões regulares veja este link http://www.ibm.com/developerworks/br/library/os-php-regex1/
Comment: Era mesmo isso. Agora só uma questão, é possível procurar pelo 123 e depois substituir o nome? por exemplo:
procurar: 123
quando encontrar substitui o nome por joaquim
resultado: $meu_array = array("123_joaquim", "125_joao", "287_manuel");
Comment: sim, isso mesmo! Muito obrigado!
Comment: caso fosse com números a expressão regular ficaria algo deste genero: $procurar = "/123_([0-9]|[1-9][0-9]|[1-9][0-9][0-9])*/";
certo? obrigado novamente
Comment: obrigado mais uma vez!

Procurar carácter num array php


Load mantine styles after Tailwind preflight

Question: I'm trying to use Mantine and Tailwind together, however Tailwind's "preflight" base styles are overriding Mantine's resulting in a simple button being invisible.

You can disable preflight:
  corePlugins: {
    preflight: true
  }

But I'd rather keep it enabled and load Mantine CSS after, per this suggestion.
Is there any way to specify order for this?
Comment: This GH issue might be relevant to your issue: https://github.com/mantinedev/mantine/issues/823.
Answer: Create an Emotion cache using createEmotionCache from Mantine core, and set prepend to false. Then, call it inside MantineProvider's emotionCache prop:
import {
  MantineProvider,
  createEmotionCache
} from '@mantine/core';

const myCache = createEmotionCache({
  key: 'mantine',
  prepend: false
});

<MantineProvider emotionCache={myCache}>{children}</MantineProvider>

Comment: When using this solution, it causes layout shift (my CSS jumps) when the page is loaded initially, seems like the emotionCache is loaded in afterwards...
Comment: this solution still doesn't work when deploying to production (without the preflight fix above)
Comment: It starts working after enabling both fixes (disable preflight and this one)
Answer: Two steps:
Add preflight: false in tailwind.config.js to disable the default
Copy out https://firstname.lastname@example.com/src/css/preflight.css refereed by https://tailwindcss.com/docs/preflight and import it in your entry point
Comment: module.exports = {
  mode: "jit",
  content: ["./src/**/*.{js,ts,jsx,tsx}"],
  corePlugins: {
    preflight: false // avoid conflict with mantine theming, https://stackoverflow.com/questions/72083381/load-mantine-styles-after-tailwind-preflight
  },
  theme: {
    extend: {},
  },
  plugins: [],
};
Comment: @Pencilcheck not sure what are you talking about...
Comment: I tried to copy the content of my tailwind config how preflight disable looks
Comment: Another method to fix this issue is to add your own mantine emotion cache and disable prepend: https://github.com/mantinedev/mantine/issues/823
Comment: This looked promising but didn't help. I tried `preflight: false` and replacing `@import 'tailwind';` with `@import 'tailwindcss/lib/css/preflight.css'`. It found that file successfully, but my styles are pretty messed up.
Answer: So, in your global stylesheet where you imported the tailwind styles remove the base styles as they will override some mantine styles. It should look like this
@tailwind components;
@tailwind utilities;

Answer: My SCSS is:
/* styles/globals.scss */
@tailwind components;
@tailwind utilities;

@layer tailwind {
  @tailwind base;
}

And I do not disable preflight in tailwind.config.ts.
See https://github.com/orgs/mantinedev/discussions/1672.
Comment: I tried it with ```"tailwindcss": "^3.3.6"``` and ```"@mantine/core": "^7.3.0"```, the Mantine Group and Grid weren't working right. The tailwind base styles were overriding them.
Comment: Works with Mantine v5. I tried it on v7 and it did not work. My tailwind.css file was a normal css file, not a scss.
Comment: @Zxeenu Mine is `  "@mantine/core": "^7.2.1", "@mantine/hooks": "^7.2.1",` with `"tailwindcss": "^3.3.0",`.
Answer: The way I solved it was by changing the order of 'globals.css' and '@mantine/core/styles.css'.
Below is the code sample:
import type { Metadata } from 'next'
import { Inter } from 'next/font/google'
import '@mantine/core/styles.css'; // import before globals.css
import './globals.css'
import { MantineProvider, ColorSchemeScript } from '@mantine/core';
import { Providers } from './providers';
const inter = Inter({ subsets: ['latin'] })

Here you can read more
Mantine
Answer: I used this solution to get it to work inside index.css add these
@layer base {
button[type="button"]:where([data-active]) {
    background-color: #2563eb;
}

}


ruby on rails 3.1 move .swf to asset pipeline?

Question: Is it possible to move SWF files to the asset pipeline, and if possible how can this be done?
Answer: I would recommend putting them in a folder called app/assets/flash.
Add this folder to your asset paths:
config.assets.paths << Rails.root.join('app', 'assets', 'flash')

They can be referenced like this in your views:
asset_path('name_of_swf')

The asset_path helper will ensure the correct file is referenced in development and production modes.
Comment: Any binary files that are put in the pipeline get a fingerprint added to them so that you can take advantage of far-future headers and client-side caching.
Comment: But isn't app/assets only for files that need to be precompiled? A swf is a binary and requires no precompilation.
Comment: Great great Did not knew you could extend assets paths like that, thx ! For reference you add this config.assets.path << etc in /config/application.rb
Comment: How would you refer to this in a script?
Comment: asset_path('name_of_file') assuming the file is somewhere in the assets folder. If it is in a folder than you need to include that.


Validação de width e height máximo com PHP

Question: Estou fazendo upload de uma imagem diretamente para uma database mas quero verificar o seu width e height e se não estiver entre (X,X) de width e (X,X) de height não insere os dados na base de dados e mostra uma mensagem de erro a dizer que as medidas da foto não são válidas!
Qualquer informação que achem importante por favor pedir! Espero ter me explicado corretamente.
Meu código
 if (isset($_POST['publicar'])) {
   $nomemembro = $_POST['nomemembro'];
 $cargo = $_POST['cargo'];

 $name = $_FILES['imgmembro']['name'];
 $target_file = basename($_FILES["imgmembro"]["name"]);

     // Select file type
    $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

     // Valid file extensions
    $extensions_arr = array("jpg", "jpeg", "png", "gif");

   // Check extension
    if (in_array($imageFileType, $extensions_arr)) {

    // Convert to base64
    $image_base64 = base64_encode(file_get_contents($_FILES['imgmembro']
 ['tmp_name']));
    $image = 'data:image/' . $imageFileType . ';base64,' . $image_base64;

    $query = "INSERT INTO equipa(nomeprof, foto, cargo) VALUES
  ('$nomemembro','" . $image . "' ,'$cargo')";
    $query_run = mysqli_query($conn, $query);

    echo '';
} else {
    echo '';
}
      }

Answer: pode usar getimagesize() :
list($width, $height, $type, $attr) = getimagesize("img/flag.jpg");
echo "";

tente assim :
if (isset($_POST['publicar'])) {
   $nomemembro = $_POST['nomemembro'];
 $cargo = $_POST['cargo'];

 $name = $_FILES['imgmembro']['name'];
 $target_file = basename($_FILES["imgmembro"]["name"]);

     // Select file type
    $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

     // Valid file extensions
    $extensions_arr = array("jpg", "jpeg", "png", "gif");

   // Check extension
    if (in_array($imageFileType, $extensions_arr)) {

    $img = $_FILES['imgmembro'] ['tmp_name'];
    list($width, $height) = getimagesize($img);

    echo 'SIZE : '.$width.'x'.$height;

    // Convert to base64
    $image_base64 = base64_encode($img);
    $image = 'data:image/' . $imageFileType . ';base64,' . $image_base64;

    $query = "INSERT INTO equipa(nomeprof, foto, cargo) VALUES
  ('$nomemembro','" . $image . "' ,'$cargo')";
    $query_run = mysqli_query($conn, $query);

    echo '';
} else {
    echo '';
}
      }

Comment: Nesse exemplo está verificando uma imagem e eu quero verificar uma imagem que vêm dum POST é possível?
Comment: uma imagem e uma imagem, que ela seja do POST o não e a mesma coisa, não faz nenhuma diferençia !
Comment: Não estou conseguindo tirar o valor de height e width!!
Comment: Ver meu EDIT !!!


use ESC key to enter fullscreen

Question: all keys can be used to enter fullscreen but seems like not the ESC one (It enters fullscreen but exits it immediately after, seems like preventDefault isn't helping)б any ideas?
function onkeydownP(b)
{
    switch (b.keyCode)
    {
    case 27: // KeyEvent.DOM_VK_ESC
        var el = document.documentElement
        var rfs = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen;
        rfs.call(el);
        b.preventDefault();
        break;
    }
}
window.addEventListener("keydown", onkeydownP, true);

EDIT: Fixed keycode in code to right one
Comment: `13` is return key, escape is `27` I think.
Answer: Change the event key to 27 (ESC). A helpful resource http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
Also, you're missing a semicolon at the end of your el declaration. Change your code to:
function onkeydownP(b)
{
    switch (b.keyCode)
    {
    case KeyEvent.DOM_VK_DOWN:
        var el = document.documentElement;
        var rfs = (el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen);
        rfs.call(el);
        cancelEvent(b);
        break;
    case 27: // KeyEvent.DOM_VK_ESC
        var el = document.documentElement;
        var rfs = (el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen);
        rfs.call(el);
        b.preventDefault();
        cancelEvent(b);
        break;
    }
}

Comment: I would try it out in a fiddle but it's down: http://www.isitdownrightnow.com/jsfiddle.net.html
Comment: It enters fullscreen with these fixed but exits it immediately after, seems like preventDefault isn't helping
Comment: What if you try to bind it to onKeyup instead? Maybe the browser's default action to leave full screen is bound to the keyup event? If you preventDefault on that action, it should probably work.
Comment: Thanks a bunch. This saved me a lot of trouble. I was wondering why you couldn't `e.preventDefault` escape when doing `keydown`. Using `keyup` did the trick.

use ESC key to enter fullscreen


Hadoop Pig: Extract all substrings matching a given regular expression

Question: I am parsing some data of the form:
<code>(['L123', 'L234', 'L1', 'L253764'])
(['L23', 'L2'])
(['L5'])
...
</code>
where the phrases inside the parens, including the brackets, are encoded as a single chararray.
I want to extract just the L+(digits) tags to obtain tuples of the form:
<code>((L123, L234, L1, L253764))
((L23, L2))
((L5))
</code>
I have tried using REGEX_EXTRACT_ALL using the regular expression '(L\d+)', but it only seems to extract a single tag per line, which is useless to me. Is there a way to create tuples in the way I have described above?
Comment: That's actually right, it should works if you use the FIND_ALL/EXTRACT_ALL define.
Comment: I can't find any documentation for FIND_ALL, but it sounds like what I'm looking for. can you point me in the right direction? Thank you so much.
Answer: If order does not matter, then this will work:
<code>-- foo is the tuple, and bar is the name of the chararray
B = FOREACH A GENERATE TOKENIZE(foo.bar, ',') AS values: {T: (value: chararray)} ;
C = FOREACH B {
    clean_values = FOREACH values GENERATE
                   REGEX_EXTRACT(value, '(L[0-9]+)', 1) AS clean_value: chararray ;
    GENERATE clean_values ;
}
</code>
The schema and output are:
<code>C: {clean_values: {T: (clean_value: chararray)}}
({(L123),(L234),(L1),(L253764)})
({(L23),(L2)})
({(L5)})
</code>
Generally, if you don't know how many elements the array will have then a bag will be better.
Comment: I'm new to pig. Can you explain to me what the T: is for inside of the bag?
Comment: Bags are unordered sets of tuples.  In this case clean_values contains n tuples called T, where T contains just clean_value, a string.


How to correct the output when using LPM (Linear Probability Method)?

Question: I have a .csv with 10 inputs and 1 output. The "problem" is that the output is binary ("0" or "1"). I am using multiple linear regression to predict the output. From searching I have found that this is called LPM (Linear Probability Model). The problem is that the y_predicted does not fall inside the [0,1] range every time, but I can get values such as -0.3 or +1.2 etc. I know that there exists the solution of logistic regression, but I do not want that, I have tested the Logistic Regression and works. But, what I ask is to use LPM and make it work, making it (the LPM) mathematically compliant. Because as it is now, I don't feel that outputs likes -0.3 or 1.2 etc are mathematically correct since probabilities must fall in the range [0, 1]. So, the outputs I get from LPM model needs some correction. What do you suggest? How to proceed?
Answer: Mathematical Problem :
When you have variables involved in some linear or Continuous calculations , & somehow you get only $0$ or $1$ , then when a variable (eg $x_1$) changes by a small amount (eg $\delta x_1$) , the Continuous Output (eg $y$) will have to vary by a small amount $\delta y$ , hence it will no longer be $0$ or $1$ , it will be $0 \pm \delta y$ or $1 \pm \delta y$ : there is no way out.
Mathematical Solution :
You have to use non-linear or Discrete calculations. In general , there is no other way.
There are many ways to achieve that Binary Output with non-linear or Discrete calculations.
One way is to use SVM or Decision Boundary or what-ever you wish to use to calculate the Intermediate Output $Y$ which is Continuous.
Then calculate the final output $y=sign(Y)$ or $y=sign(Y-Bias)$ or Etc , to get $-1$ or $+1$ , which we can easily convert to $0$ or $1$.
One more way is to convert the Intermediate Output $Y$ to a number between $-1$ & $1$ (eg with Exponentiation+logarithmic functions or inverse trigonometric functions or hyperbolic trigonometric functions) & then round up the numbers to nearest value & finally convert to $0$ or $1$ to get final Output $y$.
Always , we must use non-linearity or Discretization at the final calculations to get Discrete Output.
[[ You might be able to get more targeted Answers if you include the Inputs & Outputs to your Post ]]


Mysql table structure and designing

Question: I have two tables both i am working like below concept...
When any record will be inserted 'id' of first table ('id' is unique and auto_increment), I want to  use this id value for further insertion in my second table (that means id will be foreign key).How should I should to design my table?

If i am inserting values and further fetching last inserted value to again insert in second table then there will more query execute for a single insertion and this may take more time execution in mysql.
If i will make on extra table (counter_id_table) that will keep on id value with auto increment.When any new record will be going to insert first i will fetch value of 'counter_id_table' and this value will be the id of my first table and this value will be foreign id in second table.When i will fetch value from 'counter_id_table' again i will update with after one increment.

How i should to design my table for better execution?
Answer: The first option is how it's usually done. You can use MySQL's mysql_insert_id() to retrieve the id of the entry you inserted, right after the insert query. Don't worry about speed or load, this happens in a fraction of a second and MySQL can do this in its sleep.
So you'll get something like this:
`user`
- id
- name
- etc

`user_stuff`
- id
- userId // foreign key
- stuff
- etc

$sql = "INSERT INTO user (name) VALUES ('foo')";
mysql_query($sql) or die(mysql_error());

$userId = mysql_insert_id();

$sql = "INSERT INTO user_stuff (userId, stuff) VALUES ($userId, 'stuff')";
mysql_query($sql) or die(mysql_error());

Mysql table structure and designing


how using SQL IN operator in find method of cakephp ORM

Question: i am beginner in cakephp , and i want use SQL IN operator in find method , i have words table.
my code is :
$this->Word->find('Word.wordid in (83,82)');

, and this code create this query :
SELECT `Userword`.`userwordid`, `Userword`.`userid`, `Userword`.`wordid`,
`Userword`.`date`, `Userword`.`levelid` FROM `userwords` AS `Userword` WHERE
`Userword`.`wordid` = (82)

but i need this query
SELECT `Userword`.`userwordid`, `Userword`.`userid`, `Userword`.`wordid`,
Userword`.`date`, `Userword`.`levelid` FROM `userwords` AS `Userword` WHERE
`Userword`.`wordid` IN (83,82)

how can getting like this query (using IN operator )
thanks.
Answer: you need to let cake take care of that - simply use it as it was a string (but make sure it is an array):
$arrayOfIds = [1, 5, ...];
$this->Word->find('all', array(
    'conditions' => array('Word.wordid' => $arrayOfIds)
));

Comment: Note that this is only valid for CakePHP <= 2.x. In 3.x you will need to manually add IN again: `'Word.wordid IN' => $arrayOfIds`
Comment: not working
it build query like `SELECT `User`.`email`, `User`.`id` FROM `users` AS `User` WHERE `User`.`specialization_id` = '26,19'`
Comment: `$allUsers = $this->Query->User->find('all', array(
                    'fields' => array('User.email', 'User.email'),
                    'conditions' => array('User.specialization_id' => $specializationId)
                ));`
Comment: You didnt use an array!


How can I change an object variable through a method called in another class?

Question: I'm having a little trouble with this problem. It's simple:
I want to use defineBuyTax(6)/defineSellTax(5) to change txbuy/txsell, so I can use printTaxes and see the values in terminal. But, I'am receiving the values 0 and 0, not 6 and 5 as expected. So, basically it is not changing the values in Conversor();
I managed to fix it, creating a Conversor object to receive defineBuyTax and then manually prints it on the main function. Also, if I use System.out.print(cm.txbuy) inside the defineBuyTax method (as indicated in the code), it returns the right value.
So, what I want to know is: how can I change the variables in Conversor() so my printTaxes method do it's job correctly?
class Conversor {

    public double txbuy;
    public double txsell;

    public Conversor() {
        this.txbuy = 0;
        this.txsell = 0;
    }

    public Conversor defineBuyTax (double tax) {

        Conversor cm = new Conversor();
        cm.txbuy = tax;
        System.out.println(cm.txbuy);
        return cm;
    }

    public Conversor defineSellTax (double tax) {

        Conversor cm = new Conversor();
        cm.txsell = tax;
        System.out.println(cm.txsell);
        return cm;

    }

    void printTaxes() {
        System.out.println("Buy tax: "+txbuy);
        System.out.println("Sell tax : "+txsell);
    }
}

class Test {

    public static void main (String[] args) {

        Conversor cm = new Conversor();

        cm.defineBuyTax(6.0);
        cm.defineSellTax(5.0);
        cm.printTaxes();

    }

}

Answer: use this instead of creating new instance of Conversor in each call of  defineBuyTax or defineSellTax:
class Conversor {

    public double txbuy;
    public double txsell;

    public Conversor() {
        this.txbuy = 0;
        this.txsell = 0;
    }

    public Conversor defineBuyTax (double tax) {
        this.txbuy = tax;
        System.out.println(this.txbuy);
        return this;
    }

    public Conversor defineSellTax (double tax) {
        this.txsell = tax;
        System.out.println(this.txsell);
        return this;
    }

    void printTaxes() {
        System.out.println("Buy tax: "+txbuy);
        System.out.println("Sell tax : "+txsell);
    }
}

class Test {
    public static void main (String[] args) {
        Conversor cm = new Conversor();
        cm.defineBuyTax(6.0);
        cm.defineSellTax(5.0);
        cm.printTaxes();
    }
}

The this keyword refers to the current object in a method or constructor.
Answer: Since your define... methods return a new object you should chain your calls into one.
cm.defineBuyTax(6.0).defineSellTax(5.0).printTaxes();

If you on the other hand only want to work with a single instance, then the define... methods should update this and return void.
public void defineBuyTax(double tax) {
    this.txbuy = tax;
}

public void defineSellTax (double tax) {
    this.txsell = tax;
}

Note that the naming standard for setting a value for an instance variable is setX so if you want to use the second solution you should rename the methods to setSellTax and setBuyTax
Answer: Don't create a Conversor object inside the define methods.
Even if you need to chain the calls it will not work that way.
The following code should work as you intend.
public class Conversor {

    public double txbuy;
    public double txsell;

    public Conversor() {
        this.txbuy = 0;
        this.txsell = 0;
    }

    public void defineBuyTax (double tax) {
        txbuy = tax;
    }

    public void defineSellTax (double tax) {
        txsell = tax;
    }

    void printTaxes() {
        System.out.println("Buy tax: "+txbuy);
        System.out.println("Sell tax : "+txsell);
    }
}

Answer: What you're currently doing in defineBuyTax:

Create a comepletely new Conversor
Set this new Conversor's txbuy to the given tax
Return that new Conversor

So you're only working on a new Conversor that is then returned by the method. However, at your method call cm.defineBuyTax(6.0), you actually don't use the returned Conversor (that would be Conversor newConv = cm.defineBuyTax(6.0);).
I suspect that you actually want to work on the existing Conversor instead of a new one, so rewrite your function like this:
public void defineBuyTax (double tax) {
    this.txbuy = tax;
}

or
public Conversor defineBuyTax (double tax) {
    this.txbuy = tax;
    return this;
}

if you want to have the return value. Same for defineBuyTax, of course. The Test class doesn't need to be changed and should work now.


Bootstrap: impedir que o menu se feche quando clicado fora dele

Question: Estou usando o seguinte script para que o dropdown menu do Bootstrap não se feche quando se clica em algum outro ponto da página:
$(document.body).on('click', function(event){
    var windowWidth = $(window).width();
    if(windowWidth > 991){
        if (!$(event.target).closest('.dropdown-toggle').length) {
            event.stopPropagation();
        }
    }
});

O problema é que todos os outros módulos (carousel, panel, etc) param de funcionar. Alguma dica?
http://codepen.io/marcelo2605/pen/vGRyLr
Comment: Ola, para mim a sua questão está muito vaga. consegue fazer um jsfiddle que tenha o constragimento?
Comment: @TiagoGomes Coloquei um exemplo no CodePen.
Comment: Marque uma resposta como certa por favor. (Se já estiver resolvido) para a pergunta não ficar aberta.
Answer: A solução que encontrei foi:
Se não for para esconder então grava o que está aberto e depois abre novamente.
Ficou assim.:
$(document.body).on('click', function(event){
    var windowWidth = $(window).width();
    if(windowWidth > 991){
        if (!$(event.target).closest('.dropdown-toggle').length) {
            var obj=$('.dropdown.open');
            setTimeout(function(){obj.addClass('open');},0);
        }
    }
});

O exemplo no jsfiddle.
Comment: Legal. Resolveu o problema. Mas o menu dá uma piscada quando outro item da página é clicado. Tem como resolver?
Comment: Pois eu reparei mas não estou a ver como ultrapassar, se lembrar de algo edito :D
Comment: Tentei dar um return false no evento hide.bs.dropdown. Mas depois ele não volta a funcionar.
Comment: O problema da piscada é o setTimeout(), coloca -1
Comment: O -1 não resolveu
Comment: Estranho, aqui ele não pisca com -1.
Answer: Desculpe, entendi o que você queria, experimente fazer isso:

Editei a pergunta, veja se atende ao seu propósito:

  $(function() {
    $('.dropdown.opened')
    .on({
        "shown.bs.dropdown": function() {
            this.closable = ($('.dropdown.open').length > 1) ? true : false
         },
        "click": function() {
           this.closable = true;
           $('.dropdown.opened.open').trigger('click');
        },
        "hide.bs.dropdown":  function() { return this.closable; }
    });
 });

Aqui tem o exemplo funcionando no JSFiddle
Comment: O objetivo é mesmo detetar os clicks fora do menu e não dentro do menu. Para o que percebi.
Comment: @Ivan Ferrer Ivan, o Tiago está certo. Preciso detectar quando o menu não é clicado para mantê-lo aberto.
Comment: Editei a pergunta para ficar mais objetiva.
Comment: @IvanFerrer Ivan, no primeiro click, o menu se fecha. Ele só se mantém aberto se eu fechar e abrir de novo.
Comment: Veja se está certo agora, não entendi o negativo, mas a ideia é que você feche um para poder abrir o outro, já que você quer fixar o menu...
Answer: Achei essa solução:
HTML

  Dropdown1

Action

Another action

Something else here

Separated link

Javascript
$('.dropdown.keep-open').on({
    "shown.bs.dropdown": function() { this.closable = false; },
    "click":             function() { this.closable = true; },
    "hide.bs.dropdown":  function() { return this.closable; }
});

Comment: Ola, não tentei repetir, simplesmente estava a fazer a resposta quando criou a sua.
Answer: O componente dropdown do bootstrap tem eventos para manipular todas as interações.
show.bs.dropdown->This event fires immediately when the show instance method is called.
shown.bs.dropdown->This event is fired when the dropdown has been made visible to the user (will wait for CSS transitions, to complete).
hide.bs.dropdown->This event is fired immediately when the hide instance method has been called.
hidden.bs.dropdown->This event is fired when the dropdown has finished being hidden from the user (will wait for CSS transitions, to complete).
Fonte.:http://getbootstrap.com/javascript/#dropdowns
Pode usar este codigo.:
$('.dropdown.keep-open').on({
"shown.bs.dropdown": function() { this.closable = false; },
"click":             function() { this.closable = true; },
"hide.bs.dropdown":  function() { return this.closable; }

});
Fonte.:https://stackoverflow.com/questions/19740121/keep-bootstrap-dropdown-open-when-clicked-off

Entretanto ao fazer testes verifiquei que se abrirmos um segundo menu o 1º fica aberto.
Se não for o objetivo pode colocar este codigo.:
 $('.dropdown').on({
    "show.bs.dropdown": function() {
       $('.dropdown.open').removeClass('open');
    },
    "shown.bs.dropdown": function() {
       this.closable = false;
    },
    "click":function() {
       this.closable = true;
    },
    "hide.bs.dropdown": function() {
        return this.closable;
    }
});

Exemplo.:
http://jsfiddle.net/q6jGr/180/
Comment: Tiago: tens duas respostas. São abordagens diferentes ou são a mesma resposta?
Comment: @Sergio São respostas diferentes. A 1ª foi uma abordagem totalmente diferente onde foi de encontro a questão mas piscava e foi necessário verificar outra opção. Pensei em editar e mudar completamente a resposta mas a outra não está incorreta portanto achei positivo em ter 2 respostas diferentes.
Answer: Remova o data-toggle dos seus botoes de menu e faça o codigo de exibição deles sem afetar o comportamento do boostrap.
Utilizei a estrtuura do seu html para no click dos botoes, encontrar o menu interno e exibi-lo ou nao se estiver clicado.
Basta colocar esse script:
$(document).ready(function(){

    $('.nav-pills .dropdown a').on('click',function(){

        var jqMenu = $(this).closest('.dropdown').find('.dropdown-menu');

        if (jqMenu.length > 0)
        {
            if (jqMenu.is(':visible')) {
                jqMenu.hide();
            }
            else {
                jqMenu.show();
            }
        }
    })
})

Link para a solução - CODEPEN


Can 65 chords be arpeggiated?

Question: It should be clear but in case anyone objects with confusion over stylistic conventions: My question relates to tonal harmony and voice leading as is taught in the majority of the western worlds syllabus.
We are taught that a 7th should resolve down by step. When a 7th chord is inverted, the dissonant 7th is also usually resolved down by step.
When a 65 chord is arepeggiated however, all the intervals become linear against the bass so, in the case of a ii65 chord, all the notes become consonant against the bass and the dissonant 7th - which is the 5th above the bass and is supposed to resolve downward by step - may no longer be heard as a dissonance. Does my reasoning hold then that if a 65 chord is arpeggiated you lose the essential nature of the chord and its need for resolution in the following chord? Of course, a V7 in first inversion has a diminished 5th as the 7th so it definitely still pulls down to ^3 but in the case of a ii65 as below, I can't really hear ^1 as a tendendy tone anymore after arepggiation of this chord. Since it comes at the end of the arpeggiation whatever identification on the part of the listener as identifying the D as belonging to a ii65 is considereably weakened. This could be that I am listening on a piano which has less sustain however.
Here is an example of an arpeggiated ii65 chord in C major. you will notice I put the "dissonant tone" at the end to lead into the V chord as is correct in the resolution of the ii65 chord in tonal harmony.
Comment: Note that this chord can also be read as a chord with added 6th, in this case on the IV. This chord we also call _sixte ajoutée_.
Comment: Are you asking whether you could replace the B3 with a D4?  The answer is no, but there's no need to get into tendency tone analysis to reach that conclusion.
Answer: Generally, (at least in Goetschiu's "Exercises in Melody Writing"), all "good" chords can be arpeggiated. His definition of "good" chords includes I, V, V7, V9, IV, ii, ii7, II, and II7, (and by implication, secondary dominants but he implies this indirectly by "local tonics" or whatever was prevalent jargon at the time.) He does point out that arpeggiation allows all inversions. Minor chords follow the same "rules" including i, iv, v, V, V7, V9, ii0, ii07, ii, ii7, II, II7, etc.
One point he makes is that arpeggiating a V9 in minor keys does allow for a melody with an augmented second (steps 6 to #7).

Can 65 chords be arpeggiated?


coordinate free proof that $\text{div}(\nabla f \times \nabla g) = 0$

Question: Let $V$ be a Euclidean $3$-dimensional space. Does there exist a coordinate-free proof that for any two $C^1$-functions $f, g: \mathbb{R}^3 \to \mathbb{R}$ we have $$\text{div}(\nabla f \times \nabla g) = 0?$$
Comment: I think your functions need be at least $C^2$ for this to work, since second derivatives are involved.  Cheers!
Answer: I'm going to use $\nabla \cdot F$ instead of $\text{div}(F)$.
$\nabla \cdot (A \times B) = B \cdot (\nabla \times A) - A \cdot (\nabla \times B)$ is a well known vector calculus identity for $A, B$ vector fields.
If $A = \nabla f$ and $B = \nabla g$ then $\nabla \cdot (\nabla f \times \nabla g) = \nabla g \cdot (\nabla \times \nabla f) - \nabla f \cdot (\nabla \times \nabla g)$
It is also well known that $\nabla \times \nabla f = 0$ (also known as curl of gradient of function is $0$) for any $f: \mathbb{R}^3 \rightarrow \mathbb{R}$. So then
$\nabla \cdot (\nabla f \times \nabla g) = \nabla g \times 0 - \nabla f \times 0 = 0$.
Comment: Also, I forgot to mention that this probably requires $C^2$.
Answer: This is essentially the same as the other solutions here (esp. Kevin Dong's), but it exploits the efficiency of abstract index notation, and makes very clear what essential features we need for this identity to hold.
Given a metric $h_{ab}$ on a $3$-manifold with volume form $\epsilon_{abc}$, we can write the cross product as
$$(X \times Y)^a := h^{ad} \epsilon_{bcd} X^b Y^c.$$
Now, $(\nabla f)^b = h^{bc} f_{, e},$ and the cross product of two gradients takes a particularly simple form:
$$(\nabla f \times \nabla g)^a := h^{ad} \epsilon_{bcd} h^{be} f_{, e} h^{ci} g_{, i} = \epsilon^{eia} f_{, e} g_{, i}. \qquad (\ast)$$
In particular, notice that this expression doesn't depend on the metric directly, only the volume form $\epsilon$ and the covariant derivative $\nabla$.
Taking the divergence of this quantity, which coincides with $\text{tr} \circ \nabla$, gives
$$\text{div} (\nabla f \times \nabla g) = (\nabla f \times \nabla g)^a{}_{, a} = (\epsilon^{eia} f_{, e} g_{, i})_{, a} = \epsilon^{eia}{}_{, a} f_{,e} g_{,i} + \epsilon^{eia} f_{,e a} g_{,i} + \epsilon^{eia} f_{,e} g_{,i a}.$$
Now, the volume form $\epsilon^{eia}$ is parallel, so the first term on the right vanishes. Next, $f_{, ea}$ is a Hessian of a function, and so is symmetric in the $e$ and $a$ indices; but these indices are contracted with the $e$ and $a$ indices of the totally skew volume form $\epsilon^{eia}$, and so this term is zero; similarly, so is the last term, which gives
$$\text{div} (\nabla f \times \nabla g) = 0$$
as desired.
Note that if we we take the right-hand side of $(\ast)$ to be the definition of $\nabla f \times \nabla g$, then all we need for this identity to hold is a volume form $\epsilon_{abc}$ and a torsion-free connection that preserves it, that is, for which it is parallel. (Torsion-freeness here is necessary for the Hessian to be symmetric.)
Answer: Yes, there does. By definition of $\text{div}$, it suffices to show that $d(\lrcorner\nabla f \times \nabla g) = 0$. We want to use the fact that the cross-product $v \times w$ of two vectors can be defined by the formula $$v \times w = \mathcal{D}^{-1} \star (\mathcal{D}(v) \wedge \mathcal{D}(w)),$$ where $\star$ denotes the Hodge star operator. With this in mind, since we know that $\mathcal{D}(\nabla f) = df$ and similarly $\mathcal{D}(\nabla g) = dg$, this is the same as$$d\lrcorner\mathcal{D}^{-1} \star (df \wedge dg) = d \star \mathcal{D}\mathcal{D}^{-1} \star (df \wedge dg) = d(df \wedge dg) = d^2(f\,dg) = 0.$$In the above, we have used that $\lrcorner = \star\mathcal{D}$, $\star^2 = \text{Id}$, and $d^2 = 0$.
Comment: Yeah, I agree with Travis. Thanks so much!
Comment: This is especially nice, because it proves the result just as well for a general (oriented) (pseudo)-Riemannian $3$-manifold.
Answer: Assuming the functions involved are $C^2) as Robert Lewis pointed out, we have
$$\begin{aligned}
\operatorname{div}(\nabla f \times \nabla g) & = \nabla \cdot (\nabla f \times \nabla g) \\
 & = \nabla \cdot ( (\nabla f)_c \times \nabla g) + \nabla \cdot (\nabla f \times (\nabla g)_c) \\
 & = - (\nabla f)_c \cdot (\nabla \times \nabla g) + (\nabla g)_c \cdot (\nabla \times \nabla f) \\
 & = - \nabla f \cdot (\nabla \times \nabla g) + \nabla g \cdot (\nabla \times \nabla f) \\
 & = 0,
\end{aligned}$$
since $\nabla \times \nabla$ is zero. The subscript $c$ denotes a quantity held fixed when applying the operation. This means that in the product $\nabla \cdot ((\nabla f)_c \times \nabla g)$ we treat $ (\nabla f)_c$ as a constant vector and the result is $\nabla \times \nabla g$.
Answer: There is such a proof, assuming at least that $f$ and $g$ are $C^2$:  $$\text{div}(\nabla f \times \nabla g) = \text{div}(\text{curl}(f\nabla g) - f\text{curl}(\nabla g)) = \text{div}\, \text{curl}(f\nabla g) = 0.$$
Here we used that the divergence of a curl is zero and the curl of a gradient is zero.
Answer: This is basically Kevin Dong's proof, but using geometric calculus instead of differential forms notation.
Write the expression as
$$\nabla \cdot (\nabla f \times \nabla g) = \nabla \cdot [\epsilon^{-1} (\nabla f \wedge \nabla g)]$$
where $\epsilon$ is the right-handed pseudoscalar.  It can be pulled out as follows:
$$\nabla \cdot [\epsilon^{-1} (\nabla f \wedge \nabla g)] = [\nabla \wedge (\nabla f \wedge \nabla g)] \epsilon^{-1}$$
That evaluates to
$$[(\nabla \wedge \nabla f) \wedge \nabla g - \nabla f \wedge (\nabla \wedge \nabla g)] \epsilon^{-1}$$
But for any scalar field $h$, $\nabla \wedge \nabla h = 0$ by the equality of mixed partial derivatives, so this is identically zero.


Understanding Output of ur.df Test: What Do the z.diff.lag# Indicate?

Question: When reading the output of summary(ur.df(ts)) in R, what do the z.diff.lag# coefficients indicate?
Are they error terms for "at" in the Dickey-Fuller regression expression? For example:

To help with instruction, I'll generate some stationary data and run the ur.df function with summary wrapped around it.
# generate white noise
n <- 200
x <- rnorm(n,
           mean = 0,
           sd = 1)
# make into time series object
y <- ts(x)

Now, for example, I run an ADF test to check if my time series is not a random walk masquerading as stationary data.
For the ADF test, because the data is white noise (with no drift or trend), I leave the ur.df test type="none".
To generate lots of z.diff.lag# coefficients, I will run the ADF test at 5 lags:
summary(ur.df(y,
              type = c("none"),
              lags = 5))

And here is the output:
##
## ###############################################
## # Augmented Dickey-Fuller Test Unit Root Test #
## ###############################################
##
## Test regression none
##
##
## Call:
## lm(formula = z.diff ~ z.lag.1 - 1 + z.diff.lag)
##
## Residuals:
##      Min       1Q   Median       3Q      Max
## -1.82322 -0.81705 -0.08905  0.62597  2.30963
##
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)
## z.lag.1     -1.04664    0.17779  -5.887 1.78e-08 ***
## z.diff.lag1  0.02807    0.15987   0.176    0.861
## z.diff.lag2  0.11422    0.14319   0.798    0.426
## z.diff.lag3  0.06688    0.12474   0.536    0.593
## z.diff.lag4  0.07115    0.10538   0.675    0.500
## z.diff.lag5 -0.01979    0.07381  -0.268    0.789
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.9941 on 188 degrees of freedom
## Multiple R-squared:  0.5251, Adjusted R-squared:   0.51
## F-statistic: 34.65 on 6 and 188 DF,  p-value: < 2.2e-16
##
##
## Value of test-statistic is: -5.8871
##
## Critical values for test statistics:
##       1pct  5pct 10pct
## tau1 -2.58 -1.95 -1.62

Lo-and-behold, the data is stationary. No surprises.
In the summary(ur.df(ts)) results, I understand the t value for z.lag.1 is the test-statistic value at lag 5. I also understand the p-value for this coefficient and what it means for the Critical values.
But what I do not understand is the series of five z.diff.lag# coefficients. My only thought is these are error terms (the "at" values) for the Dickey-Fuller algebraic equation. But again, I do not understand what the p-value means for these five z.diff.lag# indicate.
Any insight is much appreciated.
Answer: In an augmented Dickey-Fuller test, the model equation (for type=trend specification) is
$$
\Delta y_t = \alpha + \beta t + \gamma y_{t-1} + \delta_1\Delta y_{t-1} + \dots + \delta_{p-1}\Delta y_{t-p+1} + \varepsilon_t
$$
(I used the notation from Wikipedia) where you may set $\beta=0$ (type=drift) and also $\alpha=0$ (type=0). The lagged first differences of $y_t$ are there to account for any autocorrelation in $\Delta y_t$, as $\Delta y_t$ could be e.g. an ARMA process. ur.df uses z instead of $y$, so z.diff.lagj corresponds to $\Delta y_{t-j}$. The corresponding coefficients, $p$-values and such characterize these lagged first difference terms in the model.


WARN: Unable to load JNA library (OS: Mac OS X 12.2) warning when running flutter app on release mode. (M1 Mac)

Question: I  built a simple tic-tac-toe app on Flutter. It works in debug mode without any problem, but when I run it in release mode it gives me an error:
WARN: Unable to load JNA library (OS: Mac OS X 12.2)
java.lang.UnsatisfiedLinkError: /Users/rza/Library/Caches/JNA/temp/jna10193542212619812140.tmp: dlopen(/Users/rza/Library/Caches/JNA/temp/jna10193542212619812140.tmp, 0x0001): tried: '/Users/rza/Library/Caches/JNA/temp/jna10193542212619812140.tmp' (fat file, but missing compatible architecture (have 'i386,x86_64', need 'arm64e')), '/usr/lib/jna10193542212619812140.tmp' (no such file)

I'm running the app in release mode in a virtual Android machine.
I am assuming it is about CPU architecture. How can I fix this?
Comment: Welcome to SO! Please take the [tour] and read "[ask]", "[Stack Overflow question checklist](https://meta.stackoverflow.com/questions/260648)", "[mre]" and their linked pages. We can't help you debug without the smallest example of runnable code that demonstrates the problem.
Answer: Just had this error as well. This happens with flutter 2.10.1 on a mac with M1.
I got rid of it by doing a
$ flutter clean

in my project directory.
Comment: In my case this command broke some things (gradle custom config) and did not solve the problem.
Comment: You are amazing thank you. But I would like to know how "flutter clean" works? Because the incompatible files are not located in project folder.
Comment: I don't know for sure what is done by flutter clean - however, it claims to clean up Xcode workspace which may include artifacts stored anywhere (as Xcode has a habit to store things in places one wouldn't expect or does even know that they exist). It cleans up several artifacts that may have been created during a previous flutter run or flutter build command and which may get reused by flutter upon further runs or builds. When migrating flutter to a new version it has a chance to resolve many issues encountered then.
Answer: It's an issue with old build files. Just delete build files manually or run
flutter clean
Answer: for me also it it was happening because of a switch to new flutter version (using fvm tool) and having other version with old flutter version installed in the emulator
flutter clean helped for sure after this + uninstall the app on the emulator


why is the following a vector space

Question: Which one of the following subsets of $P_3(F)$ is a vector space?
(A) $\{p: p(1) = 0\}$
(B) $\{p: p(0)p(1) = 0\}$
(C) $\{p: p~~ \text{is monic}\}$
(D) $\{p: p(0) = 1\}$
(E) $\{p(z)=a + bz + cz^2 + dz^3: a,b,c,d\}$
Answer is A, but just wondering why this is? Wouldn't this be all the polynomials of the form $x^0$? Also, why are only lines and planes through the origin considered vector spaces?
Why is $xyz=0$ not a vector space?
Comment: I suppose $P_{3}(F)$ is polynomials of degree 3 over $F$?
Answer: Options (B), (C) and (D) are incorrect because corresponding sets of polynomials are not closed under addition.
I am not sure what is wrong with (E), but I think you might have a typo because there are no conditions specified for $\,a,\,b,\,c,\,d.\,$
At the same time, the set of polynomials defined in answer (A) satisfies all conditions of vector (sub-) space.
Answer: Have you checked the axioms? https://en.wikipedia.org/wiki/Vector_space#Introduction_and_definition
Lines and planes that dont include the origin does not contain an additive identity for instane and hence does not meet the axioms. Try going down the list on the rest of your examples.
Comment: @user289419 Plug x=1 into x^0, what do you get? Plug x=1 into x-1, what do you get?
Comment: @anon I mean "the factor theorem" sorry.
Comment: @user289419 You overlooked all of them. Also, 1^0 is not 0.
Comment: Think of funamental theoreom of algebra, it means that 1 is a root i.e if we factor it one factor is (x-1).
Comment: the fundamental theorem of algebra is not relevant here, @User2313
Comment: @anon Oh right I completely overlooked that one. Thanks heaps
Comment: @anon Wait isn't $x^2$-1 also in the subset of p(1)=0.?That is not a vector space though.
Comment: @user289419 Yes $x^2-1$ is a polynomial such that $p(1)=0$. Yes, the set of polynomials satisfying $p(1)=0$ **is** a subspace. All you have to do is check the axioms, it doesn't take more than a minute.
Comment: Maybe I'm phrasing it wrong but what I mean is that if $x^2$-1 is part of the p(1)=0 subset,and since $x^2$-1 fails the T(a+b)=T(a)+T(b) test then how can p(1)=0 be a vector space?

why is the following a vector space


How can I get a report of changes made to Teams?

Question: I am using the script below to populate multiple Teams from a .csv:
# Read team users from CSV file
$TeamUsers = Import-CSV "Import_Path.csv"
$i = 0
# Group the objects by their TeamDesc property, so we only query each group once
$TeamUsers | Group-Object TeamDesc | ForEach-Object {
    #Get the GroupId of this Group
    $groupId = (Get-Team -DisplayName $_.Name).GroupId
    #If the Group couldn't be found, just skip below logic
    if(-not $groupId) { return }
    #If the Group could be found, create a hashtable for future splatting
    $params = @{ GroupId = $groupId }
    #now we can enumerate each object in each group of objects
    foreach($user in $_.Group){
        try {
            # create a hashtable for splatting progress
            $progress = @{
              PercentComplete = $i++ / $TeamUsers.Count * 100
              Activity        = 'Adding Users to MS Teams!!'
              Status = 'Working on Team: "{0}" and User: "{1}"' -f $_.Name, $user.UserPrincipalName
            }
            Write-Progress @progress
            # add this user with this role to the hashtable
            $params['User'] = $user.UserPrincipalName
            $params['Role'] = $user.Role
            Add-TeamUser @params
        }
        catch {
            ('Error occurred for {0} - {1}' -f $user.TeamName, $user.UserPrincipalName),
            $_.ToString() | Write-Warning
        }
    }
}

I would like to include the ability to export a report of the actions taken during the run. Ideally, at the end of the script, I would be able to collect a file that describes which users have been added to which Teams. Currently, the script will display actions in the PowerShell interface with the Write-Progress line, but I would like to be able to have a tangible report as well.
Answer: Not sure if there is an easier way, but I would create a new object containing the relevant information, and then at the end of the process, export a new CSV.
So at the start, declare a new array:
$AllActions = @()

Then, after the "Add-TeamUser" line, add these in:
$ActionObj = New-Object PSObject
$ActionObj | Add-Member NoteProperty -Name GroupID -value $GroupID
$ActionObj | Add-Member NoteProperty -Name User -Value $user.UserPrincipalName
$ActionObj | Add-Member NoteProperty -Name Role -Value $User.Role

$AllActions += $ActionObj

Now, down at the end, add in:
$AllActions | Export-csv .\AllActionsTaken.csv

So the final script would be:
# Read team users from CSV file
$AllActions = @()
$TeamUsers = Import-CSV "Import_Path.csv"
$i = 0
# Group the objects by their TeamDesc property, so we only query each group once
$TeamUsers | Group-Object TeamDesc | ForEach-Object {
    #Get the GroupId of this Group
    $groupId = (Get-Team -DisplayName $_.Name).GroupId
    #If the Group couldn't be found, just skip below logic
    if(-not $groupId) { return }
    #If the Group could be found, create a hashtable for future splatting
    $params = @{ GroupId = $groupId }
    #now we can enumerate each object in each group of objects
    foreach($user in $_.Group){
        try {
            # create a hashtable for splatting progress
            $progress = @{
              PercentComplete = $i++ / $TeamUsers.Count * 100
              Activity        = 'Adding Users to MS Teams!!'
              Status = 'Working on Team: "{0}" and User: "{1}"' -f $_.Name, $user.UserPrincipalName
            }
            Write-Progress @progress
            # add this user with this role to the hashtable
            $params['User'] = $user.UserPrincipalName
            $params['Role'] = $user.Role
            Add-TeamUser @params
            $ActionObj = New-Object PSObject
            $ActionObj | Add-Member NoteProperty -Name GroupID -value $GroupID
            $ActionObj | Add-Member NoteProperty -Name User -Value $user.UserPrincipalName
            $ActionObj | Add-Member NoteProperty -Name Role -Value $User.Role

            $AllActions += $ActionObj
        }
        catch {
            ('Error occurred for {0} - {1}' -f $user.TeamName, $user.UserPrincipalName),
            $_.ToString() | Write-Warning
        }
    }
}
$AllActions | Export-csv .\AllActioonsTaken.csv


Exercise 3.15 [Atiyah/Macdonald]

Question: I have a question regarding a claim in Atiyah, Macdonald. A is a commutative ring with $1$, $F$ is the free $A$-module $A^n$. Assume that $A$ is local with residue field $k = A/\mathfrak m$, and assume we are given a surjective map $\phi: F\to F$ with kernel $N$. Then why is the following true?

Since $F$ is a flat $A$-module, the exact sequence $0\to N \to F\overset\phi\to F\to 0$ gives an exact sequence $0\to k\otimes N \to k\otimes F \overset{1\otimes \phi}\to k\otimes F \to 0$.

I can see that $F$ is a free $A$-module, and that the first sequence is exact. But how does flatness of $F$ tell me something about the second sequence?
Thanks!
Answer: From the long exact sequence of Tor the second short exact sequence looks like
$$\text{Tor}_1^A(k,F) \rightarrow k\otimes N \rightarrow k\otimes F \rightarrow k\otimes F \rightarrow 0$$
But $\text{Tor}_1^A(k,F) = 0$ since $F$ is flat. Look at Chapter 2 exercise 24.
Comment: Thanks for your answer! I'm not familiar with Tor, yet. So I haven't done the exercise in chapter 2. I guess, I'll have to learn about Tor sooner or later anyways, so this might be a good time to do so.
Answer: A general principle in homological algebra is the following:

Every ses of chain complexes gives rise to a LES in homology.

One can apply this principle to many situations, in our case it can be used to show that every ses of $A$ - modules gives rise to a LES in Tor. The LES in your situation is exactly
$$\ldots \to \text{Tor}_1^A(k, N)  \to \text{Tor}_1^A(k, F) \to \text{Tor}_1^A(k, F)  \to k \otimes_A N \to k \otimes_A F \to k\otimes_A F \to 0.$$
Now we claim that $\text{Tor}_1^A (k,F) = 0$. Indeed because $F$ is free (hence projective) we can always take the tautological projective resolution
$$ \ldots \to 0  \to 0 \to F \to F \to 0 $$
and remove the first $F$, tensor with $k$,  to get the chain complex
$$ \ldots \to 0 \to 0 \to k \otimes_A F  \to 0$$
from which it is clear that the first homology group of this complex is zero, i.e. $\text{Tor}_1^A(k,F) = 0$.
Answer: A simple approach that doesn't use $\mathrm{Tor}$ is to show that $0 \to N \to F \to F \to 0$ is split. To do this, use the fact that $F$ is free (or more generally, projective) to find a map $\psi : F \to F$ such that $\phi \circ \psi$ is the identity. Because the tensor product distributes over direct sums, the resulting sequence $0 \to k \otimes N \to k \otimes F \to k \otimes F \to 0$ is split exact.
Note that this proof only works when $F$ is projective, which need not be the case if $F$ is an arbitrary flat module.

Exercise 3.15 [Atiyah/Macdonald]