magic.MagicException: no magic files loaded

Question: On OSX, I have installed python-magic through pip on a virtual env.
I get a magic file not found error, when I do this,
import magic

print magic.Magic(mime=True).from_file("/opt/local/bin/python2.7")

And I get this
magic.MagicException: no magic files loaded

I tried with setting magic_file parameter and I still get it.
print magic.Magic(mime=True,
     magic_file="/opt/local/share/misc/magic").from_file("/opt/local/bin/python2.7")

And yes, I have verified the magic file exists.
I use Python installed through macports.
EDIT: I tried the same thing with homebrew. Installed libmagic through brew and installed
python-magic. And the results are the same.
Comment: Ok. I figured this out. Versions 0.4.3 and above have a bug in them See https://github.com/ahupp/python-magic/issues/44. I could not install it from pip(did pip-review --interactive, it shows me there is version 0.4.6 but won't install it). Since the bug was fixed in version 0.4.6 I got the python-magic.egg from pypi and installed it with easy_install, and it works!!!
Comment: Please add an answer here (and if it solved problem accept), Your question is useful.
Answer: Ok, I posted this a while ago in the comments. Just adding it here to mark the question answered:
Ok. I figured this out. Versions 0.4.3 and above have a bug in them See github.com/ahupp/python-magic/issues/44. I could not install it from pip(did pip-review --interactive, it shows me there is version 0.4.6 but won't install it). Since the bug was fixed in version 0.4.6 I got the python-magic.egg from pypi and installed it with easy_install, and it works!!!


How to convert a Byte* from C++ to Byte[] in C#

Question: I have a library in C++ containing a library returning a Byte* :
typedef unsigned char Byte;
Byte* RotateImage90(Byte* data, int w, int h);

I'm using this library in a program in C# (Xamarin) :
[DllImport("libCpp", EntryPoint = "RotateImage90")]
public static extern IntPtr rotate90(byte[] data, int w, int h);

Byte[] test(Byte[] data, int w, int h)
{
    IntPtr ptr = rotate90(data, w, h);
    Byte[] img = ????;// <= function missing
    return img;
}

It works good, but I don't know how to convert the pointer to a Byte array. Someone know a function to do that ?
Comment: This function is impossible to use correctly in a C++ program, that does not get better when you pinvoke it.
Comment: Don't return a pointer but force the caller to pass in an already-allocated byte array (along with the size). Return the number of bytes written to the byte array. This way the caller can allocate / free the array any way they see fit.
Comment: It seams that it work in C++. I added a breakpoint in my function `RotateImage90` (in C++) and it received a pointer, I checked values, it correspond to values in `data` sent by C#.
Comment: Who frees up the byte array returned by the C++ code? And how do you know how many bytes to read at the address pointed by the pointer? Is the returned pointer the same as the byte array going in?
Comment: @xxbbcc the byte array returned as same size, height and width are reversed (it's a image rotation ). So I know number of bytes to read. C++ function return a pointer for the new image. The C# fonction have to get all bytes in a array and have to free it at the end.
Comment: @A.Pissicat If you're controlling both sources (C++ / C#) I strongly suggest you change the C++ call interface. If you don't control the C++ source, this will become a maintenance nightmare for you.
Comment: @xxbbcc I'm actually developing the C++ library. I received a Byte[] and I have to return a new Byte[].
I'm using C#/xamarin to test interface but the library will be used with java too. So returning the pointer is the only way I found.
Answer: A problem of your function interface is that the memory that the function dynamically allocates to return the rotated image byte array, must be allocated with the same memory allocator that the C# side (or whatever client code) will use to release the memory.
In other words, the module that allocates the memory and the module that frees it must use the same allocator.
When I needed to pass some array data between native code and C# code I successfully used Safe Arrays. On the C++ side, you can use ATL's CComSafeArray to simplify the safe array programming; on the other hand, C# and the CLR understand safe arrays well, so it's easy to get the array data in C# and consume it in managed code.
You can use a function like this to produce a safe array of bytes in C++ (in your case, the safe array will store the rotated image data):
extern "C" HRESULT __stdcall ProduceSafeArrayOfBytes(/* [out] */ SAFEARRAY** ppsa)
{
    HRESULT hr = S_OK;

    try
    {
        // Create the safe array to be returned to the caller
        CComSafeArray<BYTE> sa( /* Element count */);

        // Fill the safe array data.
        // You can use a simple sa[i] syntax,
        // where 'i' is a 0-based index
        ...

        // Return the safe array to the caller (transfer ownership)
        *ppsa = sa.Detach();
    }
    // Convert exceptions to HRESULT return codes
    catch (const CAtlException& e)
    {
        hr = e;
    }
    catch (const std::exception& )
    {
        hr = E_FAIL;
    }

    return hr;
}

On the C# side, you can use this PInvoke signature:
[DllImport("NativeDll.dll", PreserveSig = false)]
public static extern void ProduceSafeArrayOfBytes(
    [Out, MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_UI1)]
    out byte[] result
);

The VT_UI1 enum field tells the .NET Marshaller that the safe array contains bytes.
You can get the array data in C# with simple code like this:
byte[] data;
ProduceSafeArrayOfBytes(out data);

As you can see, in your C# code you deal with a simple byte[] array; all the proper data marshalling (including freeing memory) happens automatically under the hood.
You can modify the aforementioned skeleton code, adding the other function parameters, like your image width and height.

As an alternative, another option would be developing a tiny bridging layer using C++/CLI, to convert from raw C-style arrays to .NET managed arrays.
Anyway, the note on your DLL function interface to use a common memory allocator for allocating and releasing the array memory is still valid.

As a third option, if you can modify your DLL function interface, you can require the caller to allocate an array and pass it to the DLL function. The function will write the result data in this caller-allocated array.
This would simplify the memory management, as you give the DLL function a block of memory that is already allocated by the caller. The caller will have the responsibility for both allocating and releasing that memory.
So, your DLL function would look like this:
extern "C" void __cdecl RotateImage90(Byte* result, Byte* data, int width, int height);

The result array is allocated by the caller, who is also responsible to free it.
The function just writes its output in this caller-allocated array.
PInvoke would look like this:
[DllImport("NativeDll.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void RotateImage90(byte[] result, byte[] data, int width, int height);

Comment: .net also understands raw byte arrays (when used correctly), SAFEARRAY are a bit overkill if nothing (read: COM, Automation clients, VB/VBA/Scripts, etc.) forces you to use them.


Writing PHP into views field template twig

Question: I'm less familiar with D8, but I need to re-write a views field output using some PHP. I've made a custom field template HTML.twig file, but I'm not sure what I need to do to be able to run a PHP execution on my field to render it out as I want.
edit:
I am trying to run a function on the User ID as I have a module which hashes it before sending it to an external platform, however, now the client wants the understand which user is which, and the only way I can think to do this is by performing the same hashing code on the User ID in a format I can easily cross reference the user with their hashed output
I have a very basic view table showing only the User ID and email address, and I've managed to create a views field override using this page which has overwritten my field successfully. But now I want to run a command I'm going to copy from my contrib module, the below to be specific, so that I can work out which User ID relates to which hashed code
<code>return Crypt::hmacBase64($uid, \Drupal::service('private_key')->get() . Settings::getHashSalt());
</code>
Comment: I guess this question needs a bit more detail than "a views field" and "some PHP". What exactly are you trying to achieve? What view? What Views field? Where does it come from? What does it display now? What should it display instead? Please edit your question and add more detail and context. Please try to make this a reproducible issue. Many thanks
Comment: @leymannx, I've edited it a bit, I wasn't necessarily looking for someone to do the whole job for me, I was just wondering how it's possible to do it in D8 as I'm more familiar with D7
Comment: There is no PHP code in Twig. If you want to to do the D8/Symfony way, I'd recommend to google for "Drupal custom twig filter". e.g. [this blog](https://medium.com/@yuseferi/how-to-write-custom-twig-filter-in-drupal-8-1c2981dbf1e3)
Comment: perhaps you can do that in a preprocess function and pass the result as variable to your twig template. Twig is only for presentation and not computation or as suggested create your own twig filter but I guess preprocessing might be easier.
Answer: You can write Twig directly into your view with a Custom text field.

Using Twig as an entry point, you can use all of the Twig functionality and filters that ship with Drupal, as well as expanding on these with modules like Twig Tweak and Twig Field Value. You can also write your own Twig extensions, which are written in PHP. Here are two suitable tutorials:

https://opensenselabs.com/blog/tech/twig-extension-drupal
https://medium.com/@yuseferi/how-to-write-custom-twig-filter-in-drupal-8-1c2981dbf1e3


Android ListView Bitmap Optimization

Question: I have a ListView that display Bitmap pictures. These Bitmaps get to be quite large. When i scroll on the ListView it seems to be very heavy. What techniques can i use to optimize the ListView ? This may cover compressing the Bitmap in memory, or ways to enhance the List View memory management ?
Answer: First, read this,

http://developer.android.com/training/improving-layouts/smooth-scrolling.html

It talks about the view holder pattern, and loading images in a threads. also, read this,

http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html

This talks about how to build an efficient memory cache for bitmaps.
If that's not enough, another technique you can employ is to avoid loading images until scrolling stops. This prevents the listview from loading all of the images if the user say flings to the bottom of the list. Basically, something like this,
    pagerList.setOnScrollListener(new OnScrollListener() {

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            if (scrollState != OnScrollListener.SCROLL_STATE_IDLE) {
                return;
            }
            // load images for adapter views between first and first+count.
            // depending on your memory requirements, you can pre-load additional
            // images before first and after first+count to give a better
            // user exp
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            first = firstVisibleItem;
            count = visibleItemCount;
        }
    });

This requires that you keep a handle to the ImageView for each item in your adapter, so you can find it later and set the appropriate bitmap into it. This could be as simple as keeping an array of image views in your adapter, where the index == the position in the list view.
Comment: Thanks! I've been wondering on how to solve this problem for a while now :)
Answer: I mostly use LruCache to optimize list and load images from cache LruCache
add this in getView in BaseAdapter class
@Override
    public View getView(.....
   ..... . .
     Bitmap image = getBitmapFromMemCache(name);
        if (image == null)
        {
         image = decodeSampledBitmapFromUri(image_path.get(position), 64,64);
        }
        else
        {
            Log.i("loding. ", "from cache "+name);
        }
        // Bitmap ThumbImage = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(details), 64, 64);
         holder.img.setImageBitmap(image);
         addBitmapToMemoryCache(name, image);

Android ListView Bitmap Optimization


JIRA API attachment names contain the whole paths of the posted files

Question: I have been working with Jira API and have seen inconsistent results for my requests. Sometimes it works and sometimes it doesn't. Last week I was able to post attachments to issues just fine, but now an old problem occurred: the names of the attachments contain the whole path of the posted file, hence the attachments can't be opened. I use json representation to post files:
<code>$array = array("file"=>"@filename");
json_encode($array);
...
</code>
This gets the file posted but the problem is when it's posted the file names in JIRA are like this:

/var/www/user/text.text

Needless to say it can't be opened in JIRA. I had this problem before, then it suddenly disappeared, now it occurred again. I don't really get it. By the way I am not using curl for this request even though it might be recommended in the documentation.
Answer: I realize this question is somewhat old but I had a similar problem. It seems Jira doesn't necessarily trim the filename as expected. I was able to fix it with the following. If you're using PHP >= 5.5.0:
<code>$url = "http://example.com/jira/rest/api/2/issue/123456/attachments";
$headers = array("X-Atlassian-Token: nocheck");

$attachmentPath = "/full/path/to/file";
$filename = array_pop(explode('/', $attachmentPath));

$cfile = new CURLFile($attachmentPath);
$cfile->setPostFilename($filename);

$data = array('file'=>$cfile);

$ch = curl_init();

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "$user:$pass");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

$result = curl_exec($ch);

$ch_error = curl_error($ch);

if ($ch_error){
    echo "cURL Error: $ch_error"; exit();
} else {
    print_r($result);
}
</code>
For PHP <5.5.0 but > 5.2.10 (see this bug):
<code>$data = array('file'=>"@{$attachmentPath};filename={$filename}");
</code>
Answer: Yes, I filed an issue on this at https://jira.atlassian.com/browse/JRA-30765
Adding attachments to JIRA by REST is sadly not as useful as it could be.
Interesting that the problem went away - perhaps you were running your script from a different location?


Autopost is not working

Question: I want to autopost the contents in facebook.I installed Drupal for Facebook module and created Apps in facebook.
In this,the user can connect facebook.But the content doesn't get autopost.
I got an error like this
"Something went wrong while posting update to your facebook wall. The error has been captured by watchdog".
How to clear this error.
Comment: Do you have the dblog module switched on? If so, please post the watchdog error. Seems like your oauth authentication isn't going through.
Comment: "Post to facebook options not available. Possibly a temporary failure to reach facebook.com, or an expired access token."
Comment: "Failed to access facebook altering node-form.: fb_graph failed querying . OAuthException: Error validating application. Application has been deleted."@olyN I got this error
Answer: Your error says your application has been deleted. Go to https://developers.facebook.com and check your application under the "Apps" tab. If the app exists, check that your oauth details (on the drupal site) match. If the app doesn't exist, create an app (also under the "Apps" tab) and validate against that in your Drupal site's oauth settings.
Comment: My facebook app exists, I gave the same app id and secret key in facebook oauth settings.Still It shows the same error.

Autopost is not working


What function is on the graph?

Question:
I need to know what function is on the graph.
And how do I determine the function name by its graph?
Comment: Looks like a [triangle wave](https://en.wikipedia.org/wiki/Triangle_wave) (with some discontinuities).
Answer: How about this? $|\arcsin(\sin(x))|$
Comment: This is the best solution. Thanks!
Answer: This could be
$$f(x) = \left\{\begin{array}{l l} x-2n & \text{for } x\in [2n,2n+1] \\ 1-(x-2n-1) & \text{for } x\in [2n+1,2(n+1)] \end{array} \right.  \quad \  n \in \mathbb N.$$
Or more generally
$$f(x) = \left\{\begin{array}{l l} a(x-b2n) & \text{for } x\in \big[b2n,b(2n+1)\big] \\ a\big(1-(x-b2n-1)\big) & \text{for } x\in \big[b(2n+1),2b(n+1)\big] \end{array} \right. \quad \  n \in \mathbb N.$$
where $a$ determines the height of the triangles and $b$ the length of the basis.
Answer: You may like the followings :

The graph of $y=||x|-1|$ is this.
The graph of $y=|||x|-1|-1|$ is this.
The graph of $y=||||x|-1|-1|-1|$ is this.
Answer: You can never really determine a function by its graph... Because a graph is way to draw the function which is limited by the "real world".
Imagine your function being only defined on $Q$, you won't see that this is not defined on $R$ just by the graph.

What function is on the graph?


Suppose $C \subseteq B$ and $B \subseteq A$; prove that $ \sup_{A} C \leq \sup_{B}C$

Question: Suppose $C \subseteq  B$ and $B \subseteq  A$; prove that $$ \sup_{A} C \leq \sup_{B}C$$
That's the problem, let $s= \sup_{A} C$ and $t= \sup_{B}C$, by definition
$(x \leq s)( \forall x \in C) \:$  and $ \: (y \leq t)( \forall y \in B) $
Since $C \subseteq B$, then $(x \leq t)(\forall x \in C)$, so, here my question arises, can I deduce that $ s \leq t $?
Comment: Explaine your notation and do not use symbolic formulas that are not well forned.
Comment: If the class of lower bounds of $B$ in $A$ has a greatest element, then this element is called the greatest lower bound of $B$ in $A$.
Comment: The least upper bound of $B$ in $A$ is also called the supremum of $B$ in $A$ (abbreviated $sup_{A} B$)
Answer: this exercise is from the book of Pinter?
If you suppose  that $ C \subseteq B $ and $ B \subseteq A $, by transitivity $ C \subseteq B \subseteq A $. Let $ s $ be the minimum upper bound of $ C $ in $ A $ $ (s = \sup_ {A} C )$ i.e $ s \geq x $, $ \forall x \in C $, with $ s \in A $.
Let $ t \geq y $, $ \forall y \in C $, with $ t \in B $, i.e $ t $ is the $ \sup $ of $ C $ in $ B $ $ (t = \sup_ {B} C )$.
Since $ t \in B $ and $ B \subseteq A $, then $ t \in A $, but $ s $ is the minimum upper bound of $ C $ in $ A $, so $ s \leq t $.
$$ \therefore \: \: \: \sup_ {A} C \leq \sup_ {B} C $$


Como imprimir o conteúdo de uma página com Bootstrap e JQuery?

Question: Gostaria de adicionar um botão Bootstrap para invocar a impressão de conteúdo de uma página, consegui esse exemplo, mas ele funciona a partir de um link, vejam:
Exemplo
O código posiciona o link na parte superior da página, também vi um exemplo aqui mesmo, nesse link Exemplo Stackoverflow, mas não gostaria de abrir a página com conteúdo novamente, simplesmente clicar no botão, chamar a caixa de impressão e imprimir como no primeiro exemplo citado.
O código da primeiro exemplo é esse:

$(document).ready(function() {
    $('#container').prepend('Click aqui para imprimir');
    $('a#print').click(function() {
        window.print();
        return false;
    });
});
Answer: Se o seu objetivo é ter um botão que usa a classse do bootstrap e só usarbtn btn-primary por exemplo, e se não quiser que abra em nova abra e so remover o target_blank, pelo que entendi seria algo assim:

        document.getElementById('btn').onclick = function() {
          window.print();
        };

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

Essa é a DIV

  <button id="btn" class="btn btn-primary">Clique para imprimir</button>

Comment: Olá @Gabriel Rodrigues, muito obrigado pela colaboração, foi de grande ajuda.


Heteroscedascity and sample size

Question: Can a small sample be cause of heteroscedascity? My guess is that it doesn't depends only on sample size, but also on sample bias or measurement error.
Answer: Just to frame the question, let's assume the data generating process is:
$$ y_i = a + b x_i + \epsilon_i$$

The sample size is the number of pairs $(x_i, y_i)$ you observe.
The error terms are homoskedastic if the variance of the error term $\epsilon_i$ doesn't depend on $x_i$ (i.e. the conditional variance $var(\epsilon_i | x_i)$ equals the scalar constant $\sigma^2$). The error terms are heteroskedastic if the variance is different for different values of $x_i$.

Sample size and heteroskedasticity are entirely different concepts.
Comment: I understand, but in small sample we could have missing observations of y given x that could cause unconstant variance of error terms?
Comment: Whether there is heteroskedasticity or not depends on the data generating process. A data generating process with heteroskedastic error terms will have heteroskedastic error terms whether you observe 1000 observations, 10 observations, 1 observation, 0 observations, it doesn't matter! Heteroskedasticity is a property of *how the data is generated.*

Sample size is how many times you see output from that data generating process.
Comment: In the classic regression model, observing (or not observing) more data does not change how the data was generated. (Caveat: in some situations, the act of collecting data can affect how the data is generated. Eg. administering tests to more students changes how much they study...  The data you collect can be entirely different than the data you don't collect.This can get quite tricky, quite complicated, and is more the topic of a whole course on selection bias in econometrics.) Anyway, the short answer is no. And if you define the data generating process carefully, it's always no.
Comment: Here, by data generating process, you mean the true regression equation, not estimated one?
Comment: @quirik Yes. I mean whatever algorithm *actually* generates the data.

Heteroscedascity and sample size


Android creating a filename path from user input

Question: I'm sure there is a simple answer to this but I'm new and can't seem to figure this out.
I need to save data to a text file. I have all the code to do that but the path and filename is hard-coded for now. I have an EditText field where the user enters the filename and then hits a button. I want it to create a path and filename based on what the user enters.
Basically a pre determined path of "/sdcard/"+Whateveruserentered.txt
Comment: Just get the value of whatever the use enters in the `EditText` you set up, turn it into a string and use the `+` operator to add it to file pathname.

`EditText filename = new EditText(this);
        filename.getText().toString();`
Answer: Ok , here is a simple answer,
suppose you have entered "myPath/myfile.txt" in EditText,
First you need to create "myPath" folder ( I am assuming you are giving foldername too in path ).
<code>String fullPath = myEditText.getText().toString().trim();
String folderPath = fullPath.substring ( 0, fullPath.indexOf ( "/" ) );
String fileName = fullPath.substring ( fullPath.indexOf ( "/" ) + 1 );

// First Create folder by coding,

File folder = new File(Environment.getExternalStorageDirectory().toString() + folderPath );
if (!folder.exists())
{
      folder.mkdirs();
}

// Note: your path must not have recursive folders like myPath1/myPath2/myFile.txt, otherwise you need to create folder in 2 steps.

// Now creating file
File file = new File(Environment.getExternalStorageDirectory().toString() + folderPath + fileName );

if ( !file.exists() )
{
    success = file.createFile();
}

// Now your file is created, you can do writing code now onwards.
</code>
Comment: Awesome! I already had the path defined but what worked was using your first line and changing it to my needs: String filename =edittextfield.getText().toString().trim();    Thank you so much!


How do I check if a link exists in a page?

Question: There is a form having a link clicking on which field set will be collapsed to show fields under it. HTML is shown as below.

    Hide
    Attach

How would I go about checking if this link exists (to click on it), and the fields under it are shown?
Answer: To answer my own question, I realized (even without clicking on the link) that fields can be asserted by DrupalWebTestCase::assertFieldByName().


Laravel: "Could not open imput file: artisan". O que pode ser?

Question: Estou aprendendo a usar o Laravel e estava baixando o Composer. Instalei via programa, tudo ok, mas na hora de instalar o Laravel e testar o php artisan serve, aparece isso na imagem. Me parece estar instalado mas não sei o que acontece, não entendo muito disso e quase não encontrei casos parecidos. Eu uso o Ampps
Comment: Você já criou o projeto usando `laravel new `?
Comment: C:\Users\DZ>laravel new appLaravel
Crafting application...

In CurlFactory.php line 185:

  cURL error 7: Failed to connect to localhost port 1080: Connection refused (see http://curl.haxx.se/libcurl/c/libcu
  rl-errors.html)

new [--dev] [--force] [--] []

Assim?
Comment: Esse comentário não ajuda em nada. Por favor, melhore a sua pergunta adicionando mais detalhes. Procure também ler a documentação [referente à instalação](https://laravel.com/docs/5.8/installation).
Comment: pelo jeito o seu projeto esta na pasta `appLaravel` da um `cd appLaravel` (nao sei como é no windows) e depois roda o `php artisan serve`
Answer: Requerimentos para a instalação:

PHP >= 7.1.3
OpenSSL PHP Extension
PDO PHP Extension
Mbstring PHP Extension
Tokenizer PHP Extension
XML PHP Extension
Ctype PHP Extension
JSON PHP Extension
BCMath PHP Extension

1º Passo, se você ainda não tiver o php instalado em sua maquina aconselho utilizar o laragon ele facilita o desenvolvimento de aplicações WEB instalando tudo o que você ira precisa para ter um servidor localhost configurado para desenvolvimento.
2º Passo, Instalar Composer você pode encontrar aqui
3º Passo, Baixar o instalador laravel com esse comando
composer global require laravel/installer

4º Passo, agora você pode instalar o laravel em qualquer diretório de sua escolha com o comando
laravel new nomeDaAplicação

Ou
composer create-project --prefer-dist laravel/laravel blog "5.7.*"

5º Passo, no diretorio onde você instalou o laravel com o 4º passo, você deve rodar o comando php artisan serve Agora você pode começar modificar os arquivos para construir seus sistema.
Comment: Foi tudo ok até o 4o passo, no 4o passo deu esse erro

  [InvalidArgumentException]
  Project directory blog/ is not empty.
Comment: Warning: require_once(C:\Users\DZ\blog\vendor/composer/autoload_real.php): failed to open stream: No such file or directory in C:\Users\DZ\blog\vendor\autoload.php on line 5

Fatal error: require_once(): Failed opening required 'C:\Users\DZ\blog\vendor/composer/autoload_real.php' (include_path='.;C:\php\pear') in C:\Users\DZ\blog\vendor\autoload.php on line 5

Já é um progresso, pelo menos mudou de mensagem
Comment: Cara deu certo. Muito obrigado. Eu não sabia da parte da pasta blog nem do composer update. Vlw de vdd :)
Comment: é por que no diretorio `/blog` já existe ua app laravel digite `cd blog` para entrar no diretório blog através do `CMD` depois digite `php artisan serve`
Comment: Atá está faltando as dependências da vendor digite `composer update` se não der certo digite `composer dump-autoload` se der certo avisa aqui...
Answer: Eu tive o mesmo problema na hora de mandar para o GIT , pois a pasta vendor não estava indo e fiquei horas quabrando a cabeça, ai uma amiga resolveu o problema informando que tem que enviar a pasta vendor.
Pronto feito o download da Pasta vendor para o projeto não precisou de mais nenhuma configuração e resolveu o problema.
Espero ter ajudado
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Setting up file sharing in Drupal 7

Question: I would like to set up simple file storing and sharing (for educational purposes) for my users. I considered creating Profile2 profile and put data uploads files there. But it seems little clumsy.
Now i have idea to set up content types "File" Which will contain title and File upload field. That way they could possibly be able to "send" those nodes to anyonther somehow.
I could create listing of user files with views or else.
I am also using User Relationships module.
Question:
What would you suggest, what would be best method to achieve this ?
Is there mechanism for user to "send" node to another (User Relationships) ?
What is the danger of having extreme number of nodes that user can produce this way ?
Is there an alternative ?
Thanks
Answer: I suggest using Privatemsg module it had a nice attachment field and now it is fieldable that means you can add highly customizable file fields.
Thou Privatemsg module will work not as content type but more like internal messaging tool I also suggest checking out Notifications which depends on Messaging module. It will send emails upon creation or edit of chose content for all users you chose. You may also look into Team Notifications module which will allow your users to create subscriptions for others. Which is integrated with Organic groups module (OG). OG is best way for grouping and allowing users to group themselves yet if you are looking for a simple solution this may not fit due to it`s extensive functionality which results in fairly complex results.

Setting up file sharing in Drupal 7


Question about exponential function construction

Question: Reading Rudin(pg. 22) the question 6 is about exponential function construction.

Fix $b>1.$

(a) If $m,n,p,q$ are integers, $n>0,q>0,$ and $r=m/n=p/q,$ prove that $$(b^m)^{1/n}=(b^p)^{1/q}.$$ Hence it makes sense to define $b^r=(b^m)^{1/n}.$
(b) Prove that $b^{r+s}=b^rb^s$ if $r$ and $s$ are rational.
(c) If $x$ is real, define $B(x)$ to be the set of all numbers $b^t,$ where $t$ is rational and $t\le x.$ Prove that $$b^r= \sup B(r)$$ when $r$ is rational. Hence it makes sense to define $b^x=\sup B(x)$ for every real $x.$

My question is how can i prove item c) and more important Why does it make sense to define $B(x)$? It goes straight from rational to real, so that already takes the irrational, right? and it makes sense for example $2^{\pi}$, or any irrational exponent. Any help with the construction, thanks in advance.
Answer: We are updating the definition of $b^x$ ($b>1$ fixed).

Originally, $b^x$ is defined for nonnegative integers $x=n\in\mathbb{N}$:
$$
b^n:=\underbrace{b\cdot b\cdots b}_{n \textrm{ factors}}
$$
where we use the convention that $b^0=1$.
We also define for positive integer $n$,
$$
b^{-n}:=\frac{1}{b^n}.
$$
By existence of $\sqrt[n]{b}$ for positive integer $n$, (see Rundin), we are allowed to define
$$
b^{1/n}:=\sqrt[n]{b},\quad,n=1,2,3,\cdots
$$
Then by Problem 6(a) in Rudin, we can define
$$
b^r:=(b^m)^{1/n},\quad r=\frac{m}{n},\quad m\in\mathbb{Z},n\in\mathbb{Z}\setminus\{0\}.
$$
For $r\in\mathbb{Q}$, observes from Problem b(c) that
$$
b^r=\sup B(r) \tag{1}
$$
where the set $B(r):=\{b^t\mid t\le r,t\in\mathbb{Q}\}$.
Now for general $x\in \mathbb{R}$, we define
$$
b^x:=\sup B(x) \tag{2}
$$
where the set $B(x):=\{b^t\mid t\le x,t\in\mathbb{Q}\}$.
This definition makes sense because (1) is true. It would not make sense if (1) is not true, because $\mathbb{Q}\subset\mathbb{R}$ and by (2) means (1) must be true.

To prove (1), i.e., the statement in Problem (c), simply follow the definition and show the following:

show $b^r\leq \sup B(r)$ by observing that $b^r\in B(r)$;
show that $b^r\geq \sup B(r)$ by observing that $b^r\geq b^t$ for any $t\in\mathbb{Q}$ with $t\leq r$.
Comment: a last question, What would happen if $01$ and *any* $x\in\mathbb{R}$, when $b\in(0,1)$, one can defined $b^x:=(\frac{1}{b})^{-x}$. In real analysis, one does not consider functions $x\mapsto b^x$ for $b<0$. See also [this article](https://en.wikipedia.org/wiki/Exponentiation#Real_exponents_with_negative_bases). But in complex analysis, one can define such function by complex logarithm.
Answer: What is wrong with the definition of $B(x)$? There were irrational numbers in this context before its introduction; for instance, $2^{1/2}$ is irrational.
The set $B(x)$ is defined as the set of all real numbers of the form $b^t$, where $t$ is rational and $t\leqslant x$. It is a set of real numbers, which has an upper bound. And then Rudin defines $b^x$ as $\sup B(x)$. There is no problem here (except that one needs to prove that the set $B(x)$ has un upper bound).
Comment: $x$ is a real number. $B(x)$ is a $\textit{set}$. Its members are all $b^r$ for rational $r\le x$. Now define $b^x$ to be the sup of this set. There are some things to check but the definitions are clear, aren't they?
Comment: Since $B(x)$ is non-empty and has un upper bound, $\sup B(x)$ exists. Therefore, it makes sense to define something as $\sup B(x)$.
Comment: Yes, i want to know item c) and why make sense that definition for $x$ real also, maybe it's obvious but i dont understand
Comment: *What* is that you don't understand?
Comment: why make sense that definition for x real


MySQL use REGEXP with multiple rows

Question: I have a database with two tables. The first table has a single column which contains regex expressions (there are about 200 rows). The second table has multiple rows and I would like to get all the rows from the second table that matches all the regex from the first table.
For example, if the first table has:
^google.com/orp
^amazon.com/ssw
^stack/ik9

and the second table has
stack/ik9282
msifks0
amazon.com/ssw9a

the result should be
stack/ik9282
amazon.com/ssw9a

I have tried to do this using GROUP_CONCAT and get the regex from my first table as ^google.com/orp|^amazon.com/ssw|^stack/ik9, but GROUP_CONCAT has a maximum length of 1024 and I need more.
Answer: SELECT DISTINCT strings.value
FROM strings
JOIN patterns ON strings.value REGEXP patterns.pattern;

fiddle

GROUP_CONCAT has a maximum length of 1024

You may adjust group_concat_max_len variable setting.
Comment: Thanks! How can I modify it such as I will get the rows that are not matching the regex? I actually need a query to get what matches and another one to get what doesn't match.
Comment: @tatulea . . . That is not the question you asked here.  This answers the question that you did ask.  You can modify this answer using `left join` and `where` to get the values that don't match.

MySQL use REGEXP with multiple rows


$p$ is a positive integer and $(p)$ is a maximal ideal in the ring $(\mathbb Z, +,\cdot)$, then $p$ is a prime number

Question: I need to prove: $p$ is a positive integer and $(p)$ is a maximal ideal in the ring $(\mathbb Z, +,\cdot)$, then $p$ is a prime number.
My attempt:
1) $(p)$ is a maximal ideal, so it is a prime ideal.
2) Assume $p$ is not prime, then $p = ab, a,b \in \mathbb Z, a>0, b>0,a \ne 1,p$.
3) Because $(p)$ is a prime ideal, it means that either $b=z_1p$ or $a=z_2p, z_1>0,z_2>0, z_1,z_2 \in \mathbb Z$.
4) Assume that $b=z_1p$, then $1=az_1$ so $a= 1, z_1 =1$.
5) Assume that $a=z_2p$, then $1=bz_2$, so $b= 1, z_1 =1$, but then $a=p$.
Thus $p$ must be prime.
Is it a correct proof?
Comment: Yes, this is a correct proof.
Answer: I find the contrapositive to be the clearest approach:

If $p$ is not prime, then $(p)$ is not maximal.

Indeed, if $p$ is not prime, then $p$ has a proper divisor $a$ with $1 < a < p$.
But then $ \mathbb Z=(1) \supset (a) \supset (p)$, where all inclusions are strict, and $(p)$ is not a maximal ideal.
Answer: $\langle p \rangle$ is a prime ideal of $(\Bbb Z,+,\cdot)$.
Then we have that $ab\in \langle p \rangle \implies a\in \langle p \rangle$ or $b\in \langle p \rangle$
If $p$ is not prime, then take its prime factors $p=p_1^{\alpha_1}p_2^{\alpha_2}\cdots p_n^{\alpha_n}$ and clearly $$p=p_1^{\alpha_1}p_2^{\alpha_2}\cdots p_n^{\alpha_n}\in \langle p \rangle$$
$$\forall i \in \{1,\cdots,n\}: p_i^{\alpha_i}\not\in\langle p\rangle\quad \text{ (maximal) }$$
Hence $\langle p \rangle$ is not prime(also these would generate a larger ideal), contradiction, hence $p$ is prime.
Comment: Could you please explain why $\forall i \in \{1,\cdots,n\}: p_i^{\alpha_i}\not\in\langle p\rangle\quad$
Comment: @SergeyZykov If $p_i^{\alpha_i}\in \langle p \rangle$ then $\langle p \rangle$ is  non-maximal. (If $\langle p_i^{\alpha_i}\rangle = (\Bbb Z,+,\cdot)$, then $p_{i}^{\alpha_i}$ is a unit, and is not prime, so it generates an ideal(which is larger than our maximal ideal)).
Comment: Sorry not getting your reasoning here. If you claim that if $p_i^{\alpha_i}\in\langle p\rangle$, then $\langle p\rangle$ is not maximal, then you need to show that there is an ideal $\mathcal I: \langle p\rangle \subset \mathcal I \subset \mathbb Z$ where all inclusions are strict.
Answer: Let $p$ be a nonprime number, thus $p$ can be factored in to two non-unit coprime  numbers, say $x$ and $y$ ($p = xy$, $\gcd(x, y) = 1$). Since $x$ and $y$ are non-units, so $\langle p \rangle \subset \langle x \rangle \neq \textbf{Z}$ and $\langle p \rangle \subset \langle y \rangle \neq \textbf{Z}$ (if $\langle p \rangle = \langle x \rangle$, then $x = nxy$, so $y$ is a unit). This shows that $\langle p \rangle$ is not maximal ideal.
Comment: are you sure about $p=xy, \gcd(x,y)=1$? How would you factor then $125=5*5*5$ into $x$ and $y$ such that $\gcd(x,y)=1$.
Answer: As you noticed yourself ideal $\left(p\right)$ is also a prime ideal.
So $nm\in\left(p\right)\implies n\in\left(p\right)\vee m\in\left(p\right)$,
or equivalently $p\mid nm\implies p\mid n\vee p\mid m$.
This combined with $p\notin\{0,1,-1\}$ makes us say that $p$ is a so called
prime element of $\mathbb{Z}$.
This combined with the positivity of $p$ makes us say that $p$ is a prime number.

edit:
Every prime element is an irreducible element. Proof:
Let $p$ be a prime element and let $p=ab$.
Then $p\mid a\vee p\mid b$. If $p\mid a$ then $a=rp$ for some $r$.
Then $p=ab$ leads to $p(1-rb)=0$ and consequently $rb=1$ showing that $b$ is a unit.
Of course $p\mid b$ will lead to the conclusion that $a$ is a unit.

Applied to $\mathbb Z$ this shows that a prime number can be described as a positive integer that has exactly $2$ positive divisors: $1$ and itself.
Comment: What is your definition of prime numbers? Is it like this: a positive integer that is divisible by exactly $2$ positive integers ($1$ and itself)? Then I understand your difficulty. Almost always that's the way a prime number is defined, but actually it is the definition of an *irreducible* positive number. In $\mathbb Z$ and also more rings, these concepts coincide.
Comment: Thanks for the answer, but I think in it you take as obvious exactly the things I find (at my level) worth discussing. E.g. if $p$ is a positive prime element, then I am not sure why it should be a prime number (i.e. to satisfy the definition of prime numbers.
Comment: $b$ can also be $-1$, so we conclude that either $b= \pm 1$ and then $a = \pm p$ or $a= \pm 1$ and then $b = \pm p$, so the only positive divisors of $p$ are $1,p$, thus $p$ is prime according to the [definition](https://en.wikipedia.org/wiki/Prime_number)
Answer: Let my try to elaborate answering this.
Assume $I=\langle p \rangle$ is an ideal of $\Bbb Z$ for some prime $p$. Let $J$ be an ideal of $\Bbb Z$ with $I\subseteq J$. Since $\Bbb Z$ is a PID, $J=\langle a \rangle$ for some $a\in \Bbb Z$. Thus, $\langle p \rangle \subseteq \langle a \rangle$. If $\langle p \rangle \subsetneq \langle a \rangle$, then $a\notin \langle p \rangle$ (since otherwise $\langle a \rangle\subseteq \langle p \rangle$). So $p\nmid a$ and hence $\gcd(p,a)=1$. So, $1=sp+ta$ for some $s,t\in \Bbb Z$. Since $p\in \langle a \rangle$, is is $1\in \langle a \rangle$ and therefore $\langle a \rangle = \Bbb Z$. Hence $I$ is maximal.
Conversely, let $I=\langle a \rangle$ be a maximal ideal of $\Bbb Z$, so $a\neq \pm 1$. Also, $a\neq 0$, since $\{0\}\subsetneq \langle z \rangle \subsetneq \Bbb Z$ for all $z\in \Bbb Z\setminus\{0,\pm1\}$. If $a$ is not a prime number, then $a=xy$ for some non-zero integers $x,y\neq \pm 1,\pm a$. Thus, $\langle a \rangle \subsetneq \langle x \rangle,\langle y \rangle \subsetneq \Bbb Z$, contradiction by the maximality of the ideal. So, $a$ must be prime.

Alternative way: Let $n > 1$. We have $\langle n \rangle \neq \Bbb Z$ is maximal iff $\Bbb Z/\langle n \rangle=\Bbb Z_n$ is a field iff $n$ is a prime number.


Filter and Combine Nested Array in ES6

Question: I need to combine the gid and subGroups and output it into an array of strings without duplication.
My problem now is that it only gets the first level.

const oldGroup = [
    {
        "gid": "JFK",
        "subGroups": [
            "SFO",
            "LAX"
        ]
    },
    {
        "gid": "JFK",
        "subGroups": [
            "SFO",
            "LAX"
        ]
    },
    {
        "gid": "SFO",
        "subGroups": []
    },
    {
        "gid": "LAX",
        "subGroups": [
            "LGA"
        ]
    }
]

const newGroup = [...new Set(oldGroup.map((group) => group.gid))]

console.log(newGroup)
Comment: What's the expected result? Are you looking for ``const newGroup = Array.from(new Set(oldGroup.flatMap(({ gid, subGroups }) => subGroups.map((item) => `${gid} → ${item}`))))``?
Answer: There are several ways to achieve this, here is one with .reduce():

const oldGroup = [
    { "gid": "JFK", "subGroups": [ "SFO", "LAX" ] },
    { "gid": "JFK", "subGroups": [ "SFO", "LAX" ] },
    { "gid": "SFO", "subGroups": [] },
    { "gid": "LAX", "subGroups": [ "LGA" ] }
];

const newGroup = Object.keys(oldGroup.reduce((acc, obj) => {
  acc[obj.gid] = true;
  obj.subGroups.forEach(name => { acc[name] = true; } );
  return acc;
}, {}));

console.log(newGroup)

Explanation:

The .reduce() has two parameters:

a function parameter with two options acc, obj. The former is the accumulator that keeps track of the data needed, the latter is the array item object
an initial setting, and empty {} object in our case

Object.keys() is applied on the accumulated data
Answer: With .flatMap instead of .map, return an array in the callback - the .gid value, and also spread in the .subGroups array.

const oldGroup = [
    {
        "gid": "JFK",
        "subGroups": [
            "SFO",
            "LAX"
        ]
    },
    {
        "gid": "JFK",
        "subGroups": [
            "SFO",
            "LAX"
        ]
    },
    {
        "gid": "SFO",
        "subGroups": []
    },
    {
        "gid": "LAX",
        "subGroups": [
            "LGA"
        ]
    }
]

const newGroup = [...new Set(oldGroup.flatMap((group) => [group.gid, ...group.subGroups]))]

console.log(newGroup)
Comment: `Array.from(new Set(...))` maybe?
Comment: That's equivalent to `[...new Set()]` here
Comment: It seems harder to read, that might just be me.
Answer: You can use the Array.prototype.map() and Array.prototype.flat() methods to transform the oldGroup array into a new array that only contains the gid and subGroups values. You can then use the Array.prototype.filter() method to remove any duplicate values from the new array.
const oldGroup = [
    {
        "gid": "JFK",
        "subGroups": [
            "SFO",
            "LAX"
        ]
    },
    {
        "gid": "JFK",
        "subGroups": [
            "SFO",
            "LAX"
        ]
    },
    {
        "gid": "SFO",
        "subGroups": []
    },
    {
        "gid": "LAX",
        "subGroups": [
            "LGA"
        ]
    }
]
// Transform the oldGroup array into a new array that only contains the gid and subGroups values
const newGroup = oldGroup.map(group => [group.gid, ...group.subGroups]).flat();

// Remove any duplicate values from the new array
const dedupedGroup = newGroup.filter((value, index) => newGroup.indexOf(value) === index);

console.log(dedupedGroup); // ["JFK", "SFO", "LAX", "SFO", "LAX", "SFO", "LAX", "LGA"]

Filter and Combine Nested Array in ES6


Soft question about connection between flow and group actions

Question: I am learning about flow and came across the group action formal definition of flow on Wikipedia. First of all, why is it a group action of the real numbers on the set of particle positions? Is this because it corresponds to linear movement, or multiplication by a scalar? Does this definition break down if the underlying vector field is nonlinear?
Also, is it correct to say that the orbit of this group action is the set of all integral curves passing through the initial conditions by which the flow is defined and that this is the path relating to the flow, i.e. it passes from the point to the end point of the flow? The conditions on flow seem pretty weak. I assume the flow function has to be at least piecewise smooth, but other than that, is the only other condition that the flow function matches the solution to the ode at the initial point.
Answer: Here is the intuition:
Think of time as $(\mathbb{R},+)$, the group of additive real numbers. If the "system" is deterministic and reversible (for a loose interpretation of these words), then $(\mathbb{R},+)$ acts on the "system" by moving forward and backwards in time. (You can and should convince yourself of the associativity property for this action, and also that the unit acts by the identity.)
You can track the orbits of individual particles through space, as well as the system as a whole through some parameter space.
Here is a toy model:
$(\mathbb{R},+)$ acts on a vector space $V$ by $f(t)(w) = w + tv$, for some fixed vector $v$. $f(t)(w)$ denotes the position of the particle $w$ (represented by a vector) at time $t$. The vector field inducing this here is a copy of $v$ at every point.
A more interesting example: the vector field $(-y,x)$ on the plane. What does it do? I.e. what is the induced flow?
Here is a caveat:
It is not going to be the case that $(\mathbb{R},+)$ always acts - some systems "blow up" in finite time, or stop making sense in less dramatic ways. You can take the previous example and remove a point from the vector space. Some of the particles will be unaffected, but other particles will reach that point at some finite time $t$. Where can you put them at time $t$?
This counter-example is less artificial than it seems, as in fact when the space on which your flow lives is missing all holes - even holes at infinity, whatever this means - a flow generated by instructing particles to follow some sufficiently differentiable vector field is guaranteed to exist for all time. (The technical words are smooth vector field on a compact smooth manifold.)
Things to think about:
What is the role of the existence and uniqueness theorem for ODES? (This has to do with how you instruct particles to follow the vector field. You are right in that you need some hypothesis.)
Can you construct some examples that are not time reversible (which I am loosely taking to mean that you can make sense of what the system looked like for negative times?), but exist for all future times?
Is it possible to build examples that are not associative?
You can also construct discrete examples of this stuff, where for instance the group $\mathbb{Z}$ acts, or maybe $\mathbb{N}$ acts if the construction isn't reversible (like the map on polynomials sending each polynomial to its square). This shows up in stuff having to do with random walks and dynamical systems.
Hope that is helpful.
Comment: This was very helpful! Thank you!


How to start a jQuery effect when a user visualizes a point of the page

Question: I saw a lot of sites with this feature. Eg: I scroll the page until the footer, and when I see the footer an image inside it starts animating. In short, that image will start the animation only when I'll visualize the footer. How can I do that with jQuery?
Comment: Something like `$(window).scroll(function(){ if ("window bottom == footer bottom") { /*start some animation*/ } });`
Answer: You can do the following:
$(window).on('scroll', function() {
    if ($('#footer').offset().top <= $(window).scrollTop() + $(window).height()) {
        console.log('footer is inside viewport');
    }
});

Basicly you are checking the distance to the top of the document. The height of the window has to be added, otherwise it would only trigger if the #footer element is at top of the window which would be too late.
Comment: Thanks. Anyway i tried the code but the animation starts as soon as i scroll, it doesn't wait that i arrive at the page footer.
Comment: Please check my answer again. The calculation was wrong. You have to check the scroll amount + the window height to get the window bottom to document top distance. Compare this to the elements absolute position to the document top and you are ready to go.
Answer:
$(window).height() gives the height of the viewport.
$(window).scrollTop() is how far down the window has been scrolled.
$('#footer').offset().top is how far the top of the footer element is from the top of the document.

By subtracting 2 from 3, you get how far it is from the top of the viewport to the top of the footer element. If that is less than 1 (the height of the viewport), the footer is in view.
$(window).on('scroll', function() {
    if (($('#footer').offset().top - $(window).scrollTop()) < $(window).height()) {
        // Start animation
    }
});

Comment: Thank you very much, this is the right solution for me. Just a curiosity: do you think there's some way of using window pageYOffset property for the same purpose?
Comment: @FabyKennedy - I think for modern browsers, `window.pageYOffset` will give the same value as `$(window).scrollTop()`, but if you are using jQuery, you should just use `$(window).scrollTop()`.


Linear mixed effects – using all participant data in R

Question: I'm trying to analyse a data set from 16 participants. Each participant has a continuous numerical measurement over time (blood flow), and 4 different conditions. I have put all the data from each participant and each condition in a data frame (each condition has ~4000 data points). Each row of data has blood flow, participant ID, and condition in it.
I don't really know what I'm doing, but can I run a linear mixed effects using the following equation: blood flow ~ Condition + (1 | Participant)?
I've run it using each participant's mean value but was wondering if using more data would be better?
model2 <- lmerTest::lmer(s1_d1_hbo ~ 0 +
                           Condition +
                           subject_age +
                           (1|subject_ID),
                           hbo_group_trimmed, na.action = na.omit, REML = F)
summary(model2)
anova(model2)
model2_pairwise <- emmeans::emmeans(model2, pairwise ~ Condition, adjust = "Tukey", lmer.df = "satterthwaite")
model2_pairwise

Since the dataset is so large it uses an asymptotic method for calculating degrees of freedom, not Satterthwaites', by the way.
Comment: What is your research question ?
Comment: @RobertLong I'm hypothesising that blood flow will differ between conditions.
Answer: It is not only unlikely that the approximations used in mixed effects models will not work well enough with your configuration, but it's also unlikely that compound symmetry holds. I.e., you are assuming the correlation between measurements at two different times within subject are the same no matter how far apart in time those measurements are taken.  Consider an AR(1) continuous-time correlation pattern using generalized least squares.  A detailed case study with R code may be found in the longitudinal modeling chapters of RMS and BBR.
Comment: Thanks @Frank; this was very helpful. I've been trying to implement a GLS model but it keeps returning an error.
```
fnirs.gls <- Gls(model = s1_d1_hbo ~ Condition + (1 | subject_ID),
                 data = hbo_summary,
                 correlation = corCAR1(0.2, ~Time))
summary(fnirs.gls)
```
Error in catg(xi, name = nam, label = lab) : Condition has no non-missing observations
Comment: Generalized least squares (growth curve models) do not contain random effects.  Remove `subject_ID` in the model but add it to `correlation`.  Look at the code in my case studies.
Comment: I think you mean "... will work well ..." in the first sentence


Como acessar o valor de um ponteiro que recebe um endereço?

Question: Como eu acesso o valor de um ponteiro que recebe o endereço de uma variável? Como no seguinte teste:
int main()
{
    int     p1;
    int     *p2;
    int     *ptr;

    p1 = 10;
    p2 = &p1;
    ptr = *p2;

    printf("%i\n%i\n%i\n\n", *p2, *ptr, p1);
}

Aprendi que ao apontar para o endereço de uma variável com &, conseguimos acessar o valor com o operador *. Mas e quando a variável já é um ponteiro que recebe um endereço?
Ao compilar o programa, ocorre o erro:

Segmentation fault (core dumped)

Acho que até entendo o motivo (o ponteiro que estou tentando acessar p2 não possui um valor e sim recebe apenas o endereço).
Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo.
Answer: O problema está na atribuição do valor. Se você quer atribuir algo que é ponteiro para uma variável que espera um ponteiro, por que acha que precisa manipular este valor? Não basta fazer uma atribuição simples?
Os operadores de * e & não são diferentes de +, - e outros aritméticos, eles pegam dados, os manipulam por alguma regra e algoritmo estabelecido e dá um resultado. Se você quer o mesmo dado sem manipulá-lo não tem porque fazer alguma operação com esse dado, portanto não tem porque usar um operador nele.
Um bom compilador nem deixaria isso compilar.
O fato de ter atribuído separado da declaração pode ter ajudado um pouco a confundir.
Quando funciona vê que *p2 imprime 10, que é o valor apontado por p2. Então quando tenta usar o endereço 10 da memória acessa um local que não tem permissão e dá o erro. Já p2 tem um endereço de memória válido que é o que ptr espera, então é só usá-lo:
#include <stdio.h>

int main() {
    int p1 = 10;
    int *p2 = &p1;
    int *ptr = p2;
    printf("%i\n%i\n%i\n%p", *p2, *ptr, p1, (void *)p2);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
A não ser que queria fazer outra coisa, mas não tem nada na pergunta que indique isto.


Virtualmin and ProFTPd - cannot connect/browse FTP

Question: I am using Virtualmin 3.99 with Pro FTP 1.33 on Centos 6.4.
I have added a virtual server but cannot connect to the home directory via FTP. I have checked the user setup and it is set for FTP and SSH and ProFTP is running. I can connect fine via SSH.
When I try to connect via Filezilla, everything looks like it has worked but in the remote site window I get the message "Not connected to any server"
From reading around it appears this is an issue to do with MLSD and certain FTP clients - I found a suggested fix of adding below to proftpd.conf but this hasn't done anything for me.
<IfModule mod_facts.c>
FactsAdvertise off
</IfModule>

There is no ProFTP log file in /var/log/proftpd/ (the directory is empty).
I also tried creating a new FTP user and again tried to connect but got exactly the same thing and, considering SSH works, it sounds like a ProFTP issue rather than permissions etc. I also have tried connecting from WinSCP and Coffee Free FTP to no avail.
Can anyone help please?
Answer: The problem was actually a NAT/ports issue - as Filezilla was using Passive mode I needed to open enough ports and then tell ProFTP which ports were in use.
I got the solution from http://www.proftpd.org/docs/howto/NAT.html and followed their advice and opened posts 60000:65535 on CSF firewall as well as added
PassivePorts 60000 65535

to /etc/proftpd.conf then restarted both ProFTPd and CSF firewall and it has worked - I can now browse directories etc as I needed.


ZFS on Linux for RHEL/OEL Installation

Question: I'm trying Oracle Linux (OLE) 6.1 (Red Hat RHEL 6.1 compatible clone).
Actually I'm not familiar neither with RHEL nor with OLE.
I want to try ZFS on linux for RHEL as provided in this guide .
sudo yum groupinstall "Development Tools"

I added OL repositories and successfully installed "Development Tools".
Next in guide is
./configure
make rpm

But I do not know where should I run it.
So questions are:
Where should I run ./configure ?
Where should I run make rpm ?
By ZFS on linux guide
Thanks.
Comment: Did you attempt the regression test suite included in those instructions? I agree that their instruction list is confusing, but if you have successfully executed the yum command then, based on these instructions, you should have the necessary software installed.
Comment: After ./configure I have to make rpm and install spl, spl-modules-devel, spl-modules-devel RPMs. For now they are not installed.
Answer: You would need to download the release from the ZFS on Linux website and uncompress the tar.gz file (tar -zxvf filename.tgz) in a directory. Changing into the directory, you should then be able to run the rest of the configuration.
Comment: Thanks for very immediately answer. It was very silly of me. You are right. I have to download and unpak spl and zfs tarballs first.
Answer: Go Here and download the packege you want (probably spl-0.6.0-rc6), then do the tar -zxvf filename.tgz where the filename is the file name of the downloaded file, then cd in to the directory that have benn created, then you should run the commands you have mentiond in the same order.
and it should run flowlessy.
BTW In the link above there is an already rpm or deb packeges so i think it would be more convinieate for you to install them.
Comment: Thanks. I already tried Ubuntu with ZFS on linux. It is pretty well and simple to install. There is unofficial [repo](https://launchpad.net/~zfs-native/+archive/stable).

ZFS on Linux for RHEL/OEL Installation


simple slope analysis for curvilinear mixed model

Question: I am a student currently working on a simple slope for mixed model and came upon a question.
As I am interested in a two-way interaction that involves a quadratic term of X variable and a moderator, I wanted to conduct simple slopes.
When I look into prior research, as interactions with quadratic term is difficult to interpret, they report by examining the simple slopes of the regression lines corresponding to all possible combinations of different levels of IV or the moderator. (see Table 3 below).

My question is, how do I conduct simple slope analysis in R as the above table? When I use simple_slopes function, they automatically lead to simple slope test (i.e., "sstest") of either my moderator or the independent variable. I understand the table above, but am confused how to look into it.
I would highly appreciate any comments regarding this question:) Thanks you in advance!
Comment: Plotting your model output always helps with interpretation.
Answer: "Simple slopes" aren't always the simplest way to illustrate a model with interactions. Here's a synthetic data set in R, a quadratic association of outcome yq with a continuous predictor c1 interacting with a 3-level factor f1. The data are modeled with a polynomial for c1 and the interaction.
set.seed(101)
c1 <- rnorm(99)
x1 <- rep(c(-1,0,1),33)
yq <- x1 + c1 + c1**2 + x1*c1 + 0.3*x1*c1**2 + rnorm(99)
f1 <- rep(c("low","med","high"),33) ## give names to the numeric x1 values
fitq <- lm(yq~f1*poly(c1,2))

The R emmeans package provides a generally useful way to calculate and evaluate "simple slopes" via its emtrends() function, if that's what you want. It can numerically estimate the local slope with respect to a continuous predictor having a nonlinear association with outcome, at a grid of predictor values.
Here's its report over a range of c1 values, broken down by the levels of f1. It's similar to what you show, except that it's in long rather than wide format and it omits "significance stars."
library(emmeans)
emtrends(fitq,~f1|c1,var="c1",
          at=list(c1=c(-1,-0.5,0,0.5,1)))
# c1 = -1.0:
#  f1   c1.trend    SE df lower.CL upper.CL
#  high  -0.8783 0.401 90 -1.67538  -0.0812
#  low   -1.4351 0.303 90 -2.03761  -0.8327
#  med   -0.6190 0.377 90 -1.36778   0.1297
#
# c1 = -0.5:
#  f1   c1.trend    SE df lower.CL upper.CL
#  high   0.5015 0.257 90 -0.00885   1.0118
#  low   -0.6681 0.207 90 -1.07998  -0.2563
#  med    0.1996 0.233 90 -0.26371   0.6629
#
# c1 =  0.0:
#  f1   c1.trend    SE df lower.CL upper.CL
#  high   1.8812 0.188 90  1.50696   2.2554
#  low    0.0989 0.214 90 -0.32560   0.5233
#  med    1.0182 0.227 90  0.56731   1.4691
#
# c1 =  0.5:
#  f1   c1.trend    SE df lower.CL upper.CL
#  high   3.2609 0.264 90  2.73718   3.7847
#  low    0.8659 0.316 90  0.23768   1.4941
#  med    1.8368 0.365 90  1.11113   2.5625
#
# c1 =  1.0:
#  f1   c1.trend    SE df lower.CL upper.CL
#  high   4.6407 0.410 90  3.82631   5.4550
#  low    1.6329 0.454 90  0.73121   2.5345
#  med    2.6554 0.548 90  1.56704   3.7438
#
# Confidence level used: 0.95

Does that list of simple slopes describe the model better than this plot, as suggested in a comment from @mkt?

Code for the plot in base R; one could further overlay the observations, add confidence limits, etc.
plot(seq(-2,2,by=0.02), predict(fitq,newdata=data.frame(f1="high",c1= seq(-2,2,by=0.02))),type="l",col="red",ylim=c(-1,9),bty="n",xlab="c1",ylab="Prediction")
lines(seq(-2,2,by=0.02), predict(fitq,newdata=data.frame(f1="med",c1= seq(-2,2,by=0.02))))
lines(seq(-2,2,by=0.02), predict(fitq,newdata=data.frame(f1="low",c1= seq(-2,2,by=0.02))),col="blue")
legend("topleft","high, red\nmedium, black\nlow, blue",bty="n")


Is it necessary or advisable to preserve SSL certificates when moving to a new server?

Question: I have one domain that I'm serving a site on from a VPS. I used certbot to get certificates and automatically set up TLS on the nginx server. If I'm moving the site to a new VPS is there any reason to preserve the certificates and letsencrypt account information and migrate them or can I just run certbot again on the new server? If I am going to go from scratch and not migrate anything is there anything I need to do beforehand apart from revoking the existing certificates?
Comment: When I built a new server I just requested new certificates for all my websites through Let's Encrypt. I didn't have any issues.
Answer:
or can I just run certbot again on the new server?

as long you don't use certificate pinning (HPKP) there is no reason to carry old certificate. Just run certbot on new server and acquire new certificate.

apart from revoking the existing certificates

If you can safely destroy the key on existing system, I wouldn't even bother with revocation.


Is it possible to get value of an EReference by name?

Question: I want to get the value of the EReference from a Java program
I use this library: https://github.com/tesis-dynaware/graph-editor
Here is an example of xmi file generated :
<?xml version="1.0" encoding="ASCII"?>
<graph:GModel xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:graph="http://de.tesis.dynaware.grapheditor.model/1.0">
  <nodes type="tree-node" x="1217.0" y="556.0">
    <connectors type="tree-output" connections="//@connections.0 //@connections.1" connectionDetachedOnDrag="false"/>
  </nodes>
  <nodes type="tree-node" x="1020.0" y="756.0">
    <connectors type="tree-input" connections="//@connections.0"/>
    <connectors type="tree-output" connectionDetachedOnDrag="false"/>
  </nodes>
  <nodes type="tree-node" x="1260.0" y="775.0">
    <connectors type="tree-input" connections="//@connections.1"/>
    <connectors type="tree-output" connectionDetachedOnDrag="false"/>
  </nodes>
  <connections type="tree-connection" source="//@firstname.lastname@example.com" target="//@firstname.lastname@example.com"/>
  <connections type="tree-connection" source="//@email@example.com" target="//@email@example.com"/>
</graph:GModel>

What i want is to get the value of the EReference source, and i must get for exemple : /@email@example.com
I tried the code below
GModel gModel=model;
      EList<GConnection> connections=gModel.getConnections();
      for(GConnection connection : connections)
      {
          GConnector source=connection.getSource();
          System.out.println(" valeur source =" +source);
      }

but i obtain the result below :
valeur source=de.tesis.dynaware.grapheditor.model.impl.GConnectorImpl@21dd34be (id: null, type: tree-output, x: 0.0, y: 0.0, connectionDetachedOnDrag: false)
Comment: I don't fully understand what you're trying to accomplish. `/@email@example.com` is the cross reference to the first connector Object in the first node Object in the tree, therefore the `source` reference should retrieve it correctly.... Or do you want to actually retrieve the String value `/@email@example.com` ? Can you be a bit more specific?
Answer: After I read it again I suppose I understood your question.
You're trying to get the actual EObject at a specific location eg: //@email@example.com?
This path is called the URIfragment. With an URIfragment you can get the EObject which is stored at this position from the root of the resource tree.
You need to put your GModelin an emf org.eclipse.emf.ecore.resource.Resource, if does not have one yet (you can check gModel.eResource())
Suppose gModel.eResource() == null:
//create a new Resource
Resource resource = new ResourceImpl();
//add the gModel
resource.getContents().add(gModel);
//get the EObject from the URIfragment
GConnector connector = (GConnector)resource.getEObject("//@firstname.lastname@example.com");

assert resource.getURIFragment(connector).equals("//@email@example.com");

Comment: `resource.getURIFragment(EObject eObject)` returns the URI fragment as String (The path in the containment tree to the eObject)
Comment: Thank you for your answer. What i want is to get the URIfragment.
Comment: Is ot possible to get this : //@firstname.lastname@example.com as a String?
Comment: Yes it works. But in my file xmi above, I use : final URI fileUri = URI.createFileURI(absolutePath), if I want to generate only the id of the node, here (0), how can i process ? Thanks
Comment: Do you want to parse the XMI file to EObjects?
Comment: have a look at [how to read eobjects from a ecore file](http://stackoverflow.com/a/38249127/6242846) you can combine this, first load the EObject tree from the file and then you can use the resource to get the specific EObject from your uri fragment


Urn Probability Question

Question: An urn has 5 black balls and 4 white balls in it. We randomly sample a ball, and return it to the urn (sampling with replacement), until we get 2 balls with the same color. What is the probability that the first ball was white, if we know that the last one was white ? I tried building a tree, and realized that the experiment can have 2 or 3 stages, not more. Then I tried to fit conditional probability, but I got a fairly long fraction, which made no sense to me. Could you please help me to solve this problem ?
Thanks !
Comment: Since there can be no more than three stages, the tree would be particularly simple and small.  What's the matter with that approach?
Comment: I am getting the wrong number
Comment: Then you might find it most productive to show us *how* you are getting the wrong number (and why you know it is wrong: sometimes the answer you think is correct actually is not).
Answer: If my interpretation of "until we get $2$ balls with the same color" is correct then there are $6$ possibilities:

WW
WBW
WBB
BB
BWB
BWW

The corresponding probabilities are easy to find. E.g. $P(BWW)=\frac59\frac49\frac49$.
To be found is: $$\frac{P(WW)+P(WBW)}{P(WW)+P(WBW)+P(BWW)}$$

Urn Probability Question


Specify Credentials to run Powershell Script to Query AD

Question: I want to run a powershell script to query AD from a machine that is NOT on the domain.
Basically I want to query to see if there is computer account already on the domain for this machine and create it if there is not. Because this has to happen before the machine joins the domain I assume I will need to specify some credentials to enable it to run. (I'm pretty new to Powershell, so apologies if this is a newbie question!)
The script I am using to check the account is below, and then once this has run it will join the domain using the computername specified.
Can you tell me how to specify some domain credentials to run this section of the script as?
Cheers,
Ben
$found=$false
$thisComputer = <SERVICE TAG FROM BIOS>
$ou = [ADSI]"LDAP://OU=My Computer OU,DC=myDomain,DC=com"
foreach ($child in $ou.psbase.Children ) {
    if ($child.ObjectCategory -like '*computer*') {
        If ($child.Name -eq $thisComputer) {
            $found=$true
        }
    }
}

If ($found) { <DELETE THE EXISTING ACCOUNT> }

Answer: As far as I know, there is no way to pass alternate credentials using the ADSI type accelerator. Two ways you could try to get around this in your code are:

have powershell.exe run as the domain user instead of your local user - this will cause everything in the script to use the domain credentials
use the Invoke-Command cmdlet, which allows you to pass in a script block to execute, and alternate credentials.

I've never tried either of these, so it will take some trial and error.
Another option that could be more flexible for you is to not use the ADSI type accelerator. There are 2 ways to accomplish this.

Use the .NET framework DirectoryService classes. Here is a good article that walks you through this process. It includes an example using alternate credentials.
Use the Quest Active Directory Management cmdlets. These are wrappers around a lot of AD stuff that make a lot of things easier. They also let you pass in alternate credentials.
Comment: I have used the DirectoryServices namespace many times in both PowerShell and off-domain exactly as you describe. It can be a little verbose but it does and works well.
Answer: Sorry - this should be a comment really, not an answer, but I wanted to post the working code in case it is of use to anoyone else.
MattB was bang on the money! Got the following working:
$thisComputer = <SERVICE TAG FROM BIOS>
$found = $false

$strFilter = "(&(objectCategory=Computer))"

$objDomain = New-Object System.DirectoryServices.DirectoryEntry "LDAP://mydomain.com", <USER>, <PASSWORD>

$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.PageSize = 1000
$objSearcher.Filter = $strFilter
$objSearcher.SearchScope = "Subtree"

$colProplist = "name"
foreach ($i in $colPropList){$objSearcher.PropertiesToLoad.Add($i)}

$colResults = $objSearcher.FindAll()

foreach ($objResult in $colResults)
    {$objItem = $objResult.Properties;
        if ($objItem.name -eq $thisComputer) {
            $found = $true
        }
    }

if ($found) { <DELETE MACHINE ACCOUNT > }

Now I've proved the concept, will encrypt the password to make it a little more secure.
Thanks for your help!
Answer: You can continue to use the [ADSI] accelerator and pass credentials by adding the following line:
Get-Credential
This should be one of the first things in your script. In my own environment I needed to write a script to connect to a different domain.  With that different domain I had different credentials, so writing the following allowed me to do what I needed to do:
Get-Credential
Import-csv test.csv | foreach {
$ou = [ADSI]"LDAP://ou=users,dc=test,dc=com"
$newuser = $ou.Create("User", "cn=$name"
$newuser.SetInfo()
I understand that the above code was used to create a user, but the concept should hold true for any other action
Answer: Doesn't appear that you still need it, but here is a link about how to create a PowerShell credential.


Value of: $ \frac {1} {\sqrt {4} + \sqrt {5}} + \frac {1} {\sqrt {5} + \sqrt {6}} + ... + \frac {1} {\sqrt {80} + \sqrt {81}}$

Question: I have the following question:

Find the value of:
    $$ \frac {1} {\sqrt {4} + \sqrt {5}} +  \frac {1} {\sqrt {5} + \sqrt {6}} + ... +  \frac {1} {\sqrt {80} + \sqrt {81}}$$

The book already provide the answer for this question but it didn't include the ways. Hint or anything that will help is appreciated
Comment: Can you think of something that would make $\dfrac{1}{\sqrt{n} + \sqrt{n+1}}$ easier to handle?
Comment: [Rationalizing the denominator](http://math.stackexchange.com/a/60244/242) yields a telescoping sum.
Comment: What have you tried? Where did you get stuck? This question is missing lots of context. Please update it to show up your thoughts and attempt at the problem so we can more fully assist your learning as opposed to just doing your homework for you.
Comment: I didn't realize that you wanted someone to do your work for you.
Comment: Good edit. Why didn't you do the next step of collecting like terms?
Answer: Hint:
$$\frac1{\sqrt{n}+\sqrt{n+1}} = \sqrt{n+1}-\sqrt{n}$$
Comment: Another hint: "telescope".
Answer: $$\frac{\sqrt{4}-\sqrt{5}}{(\sqrt{4}+\sqrt{5})\cdot (\sqrt{4}-\sqrt{5})}+\frac{\sqrt{5}-\sqrt{6}}{(\sqrt{5}+\sqrt{6})\cdot (\sqrt{5}-\sqrt{6})}+ \ldots +\frac{\sqrt{80}-\sqrt{81}}{(\sqrt{80}+\sqrt{81})\cdot (\sqrt{80}-\sqrt{81})}= $$
$$=\frac{\sqrt{4}-\sqrt{5}+\sqrt{5}-\sqrt{6}+\ldots + \sqrt{80}-\sqrt{81}}{-1}=$$
$$=\frac{\sqrt{4}-\sqrt{81}}{-1}=$$
$$=\frac{2-9}{-1}=\frac{-7}{-1}=7$$


Como criar uma div com height em porcentagem?

Question: Boas, pessoal! Tenho uma dúvida. Quando crio uma div/footer/header e vou no css editar suas dimensões consigo tranquilamente colocar o width 100%, porém o height não consigo editar com porcentagem, apenas com px, poderiam me dar uma dica de como fazer isso?
No caso eu deveria colocar o body com height de 100% para os outros terem uma dimensão de quantos % ocupar?
Evito colocar px pois creio que o site não fica responsivo sem isso, porém caso tenho alguma dica agradeço.
Obrigado desde já!
Answer: Se você tentar definir a altura de um contêiner div para 100% da janela do navegador usando a altura da regra de estilo: 100%; não funciona, porque a porcentagem (%) é uma unidade relativa, portanto a altura resultante depende da altura da altura do elemento pai.
Por exemplo, se você considerar o exemplo a seguir, a div .container possui dois elementos pai: o elemento  e o . E todos sabemos que o valor padrão da propriedade height é automático. Portanto, se também definirmos a altura dos elementos  e  como 100%, a altura resultante da div do contêiner se tornará igual à altura de 100% do elemento janela do navegador.
<!DOCTYPE html>

<meta charset="utf-8">
<title>Set DIV Height to 100% Using CSS</title>

The height of this DIV element is equal to the 100% height of its parent element's height.

Answer: O elemento pai deve está com a position=relative Dessa forma, os elementos filhos podem estar com o height com porcentagem. Lembrando que o elemento pai deve estar com o height definido.


Define a shared .cshtml file and render it on a sub-page in ASP.NET Core MVC

Question: I have defined a very simple form on /Shared/Forms/_ContactForm.cshtml, let's say it's just a stack of labels like this (whole file):
@{

Lorem

Ipsum

Dolor

}

My objective is to reuse that form on my Contact.cshtml sub-page and at the foot of all my personal projects sub-pages
I'm editing my Contact.cshtml file and trying to use @RenderPage() in order to display my form, by using this (whole file):
@{
    ViewData["Title"] = "Contact";
}

@ViewData["Title"]

Contact with me!

    @RenderPage("~/Shared/Forms/_ContactForm.cshtml")

But I get an error Error CS0103: Name 'RenderPage' doesn't exist in the current context
I have tried to change the whole Contact.cshtml file by starting it with  as suggested in that Microsoft guide https://learn.microsoft.com/en-us/aspnet/web-pages/overview/ui-layouts-and-themes/3-creating-a-consistent-look and starting it with the <!DOCTYPE html>. But if I do that I loose the tab section defined in my _Layout.cshtml and it is cumbersome to add all elements again manually. I'm sure I'm doing it bad since I have just started with ASP.NET Core MVC (my last experience was Xamarin, first time programming webapps...), so any advice or link would be very helpful for me.
EDIT: Also tried like suggested in comments

    <partial>
        @Html.RenderPartialAsync("~/Shared/Forms/_ContactForm.cshtml")
    </partial>

It compiles but just shows this as text:
Comment: RenderPage only work in WebPages, for MVC use Html.RenderPartial
Comment: @DA it raises a can't implicit convert void in object, and a warning asking for using  tag or IHtmlHelper.RenderPartialAsync. I have tried with  tag with no success, and RenderPartialAsync() and the combination of two advices, it compile but my page shows this as text: System.Threading.Tasks.Task`1[System.Threading.Tasks.VoidTaskResult]
Answer: You can do it like this:

    <partial>
        @await Html.PartialAsync("~/Views/Shared/Forms/_ContactForm.cshtml")
    </partial>

Or use the name attribute of the partial tag directly:

    <partial name="~/Views/Shared/Forms/_ContactForm.cshtml" />

Please note its path.
Test Result:

For more detail, you can refer to this document.
Comment: You are right, the path was the problem since I moved the file and forget to change the path. It works with your purposed solutions and with the others mentiones on my EDIT, you all have been very helpful, thanks a lot


K-modes python installation using Anaconda

Question: I am trying to install K-modes package in Anaconda.
I cannot find it in Anaconda anywhere.
How do I download and get it to work through an Anaconda distribution?
Answer: I am on Mac and have just managed to install kmodes using pip and open in jupyter notebooks in Anaconda. If you are on Windows this might work differently, but you can try it.
First of all I opened the general terminal and I entered
conda info --envs
This shows you what virtual envs have been created in anaconda. It should show you one that says base/ at the start. Simply write source activate and then copy and past the base pathway, and press enter. This will open your anaconda environment.
Then you can do pip install kmodes and enter, and this will install kmodes into your anaconda environment.
I hope this works for you!
Comment: Tried on Windows. It works! Use only 'activate' for Windows. Also after installation, you will not see in the Conda Installed Packages list. But it will work in your Python script


Understanding a proof in Algebraic Number Theory

Question:
Lemma: Let $I$ be a proper ideal in the ring $R$ of all algebraic integers, and $\alpha_1,\dots,\alpha_n$ algebraic over $\mathbb{Q}$. Then there exists $\beta\in K=\mathbb{Q}(\alpha_1,\dots,\alpha_n)$ such that $\beta\alpha_i\in R$ and not all $\beta\alpha_i$ belong to $I$.

Proof: (1) Let $R_K$ be the ring of integers in $\mathbb{Q}(\alpha_1,\dots,\alpha_n)$; it is a Dedekind domain.
(2) Let $A$ be the $R_K$-module generated by $\alpha_1,\dots,\alpha_n$.
(3) Since $R_K$ is Dedekind, there is a finitely generated $R_K$-module $B$ inside of $R_K$ such that $AB=R_K$.
(4) Since $AB\nsubseteq I$, there is $\beta\in B$ such that $\beta A\nsubseteq I$.

I don't understand (3) and (4), can one explain a little bit.
I was also doing in following way: $\alpha_1,\dots,\alpha_n$ are algebraic numbers; we can certainly find an integer $m$ in $\mathbb{Z}$ such that $m\alpha_i$ are all algebraic integers. After this I couldn't proceed to complete proof.
Answer: (3) is false as stated, it should be changed to "there is a finitely generated $ R_K $-module $ B $ inside $ K $". For a counterexample, take $ K = \mathbf Q(i) $ and $ A = (2i) $, for instance.
The modified version of (3) follows from the invertibility of ideals in Dedekind domains. Any finitely generated $ R_K $ submodule of $ K $ is a fractional ideal, and it has an inverse. Take $ B $ to be the inverse of the fractional ideal $ A $.
(4) follows because $ I $ is a proper ideal of $ R $, thus $ 1 \notin I $, for example. Since $ AB = R_K $, we cannot have that $ AB \subset I $ (because it contains $ 1 $.)


unequal length data frame column replacment

Question: Given this two unequal size data frames, would like to compare dfx$v1 to dfy$p2 where they match, replace dfy$p2 with value of dfx$v2
dfx <- data.frame( v1 = c(1,2,3),
                   v2 = c("a1","a2","a3"))

dfy <- data.frame( p1 = c("c1","d1","e1","f1","g1","h1"),
                   p2 = sample(c(1:3)),
                   p3 = c("c3","d3","e3","f2","g2","h2"),
                   p4 = c("c4","d4","e4","f4","g3","h3")
                   )

Out put should look like this:
> dfy
p1 p2 p3 p4
c1  a2 c3 c4
d1  a1 d3 d4
e1  a3 e3 e4
f1  a2 f2 f4
g1  a1 g2 g3
h1  a3 h2 h3

Answer: You can use match to get the matching indices, then subset the replacement column by them
dfy$p2 <- with(dfx, v2[match(dfy$p2, v1)])


Migration of CSV into paragraphs fails with unexpected error

Question: I try to import CSV files into a Drupal 8 installation but I can't manage to make the relationship to paragraphs appear. I followed the steps of this tutorial but can't figure out how to make it work. I created a simple test case to find the error:
I extended the regular article content type with a paragraphs field called field_persons for linking each article to a list of persons with roles. This paragraphs entity has to fields called field_name (for now only text) and field_role (taxonomy_term).
The yaml file for paragraphs migration looks like that and import processes without error:
id: article_persons
label: Import persons for articles

source:
  plugin: csv
  delimiter: '|'
  enclosure: '"'
  path: article_persons.csv
  header_row_count: 1
  keys:
    - id
  column_names:
    0:
      id: 'ID'
    1:
      name: 'Name'
    2:
      rol: 'Role'

process:
  field_nombre: name
  field_para_rol:
    plugin: entity_generate
    source: role
    value_key: name
    bundle_key: vid
    bundle: rol
    entity_type: taxonomy_term
    ignore_case: true

destination:
  plugin: 'entity_reference_revisions:paragraph'
  default_bundle: article_persons

The yaml file for article migration looks like that and import processes without error:
id: article
label: Import articles

source:
  plugin: csv
  delimiter: '|'
  enclosure: '"'
  path: articles.csv
  header_row_count: 1
  keys:
    - id
  column_names:
    0:
      id: 'ID'
    1:
      title: 'Title'
    2:
      person: 'Persons'

process:
  title: title
  type:
    plugin: default_value
    default_value: article
  field_person/target_id:
    -
      plugin: migration_lookup
      migration: article_persons
      no_stub: true
      source: id
    -
      plugin: extract
      index:
        - '0'
  field_person/target_revision_id:
    -
      plugin: migration_lookup
      migration: article_persons
      no_stub: true
      source: id
    -
      plugin: extract
      index:
        - 1

destination:
  plugin: 'entity:node'
migration_dependencies:
  required:
    - article_persons
  optional: { }

But when I try to access the node I get an "unexpected error" with a huge log message:
Error: Call to a member function getEnabledBehaviorPlugins() on null en Drupal\paragraphs\ParagraphViewBuilder->buildMultiple() (línea 37 de /var/www/html/sites/all/modules/paragraphs/src/ParagraphViewBuilder.php)
#0 /var/www/html/core/lib/Drupal/Core/Entity/EntityViewBuilder.php(220): Drupal\paragraphs\ParagraphViewBuilder->buildMultiple(Array)
#1 [internal function]: Drupal\Core\Entity\EntityViewBuilder->build(Array)
#2 /var/www/html/core/lib/Drupal/Core/Render/Renderer.php(378): call_user_func(Array, Array)
#3 /var/www/html/core/lib/Drupal/Core/Render/Renderer.php(195): Drupal\Core\Render\Renderer->doRender(Array, false)
#4 /var/www/html/core/lib/Drupal/Core/Template/TwigExtension.php(490): Drupal\Core\Render\Renderer->render(Array)
#5 /var/www/html/sites/default/files/php/twig/5a008e9488529_field.html.twig_9MJB5waMfG4Lcal_NDL6EY6rM/NRByUw7bYmwhNIE9WTZfCRjJ3XUAFBB122RdQTC3JsI.php(128): Drupal\Core\Template\TwigExtension->escapeFilter(Object(Drupal\Core\Template\TwigEnvironment), Array, 'html', NULL, true)
#6 /var/www/html/vendor/twig/twig/lib/Twig/Template.php(432): __TwigTemplate_85d8aba47ed6496a0f2e8e6407c9fc1802c03e707a72d9d0c1465c62e125a308->doDisplay(Array, Array)
#7 /var/www/html/vendor/twig/twig/lib/Twig/Template.php(403): Twig_Template->displayWithErrorHandling(Array, Array)
#8 /var/www/html/vendor/twig/twig/lib/Twig/Template.php(411): Twig_Template->display(Array)
#9 /var/www/html/core/themes/engines/twig/twig.engine(64): Twig_Template->render(Array)
#10 /var/www/html/core/lib/Drupal/Core/Theme/ThemeManager.php(384): twig_render_template('sites/all/theme...', Array)
#11 /var/www/html/core/lib/Drupal/Core/Render/Renderer.php(437): Drupal\Core\Theme\ThemeManager->render('field', Array)
#12 /var/www/html/core/lib/Drupal/Core/Render/Renderer.php(450): Drupal\Core\Render\Renderer->doRender(Array)
#13 /var/www/html/core/lib/Drupal/Core/Render/Renderer.php(195): Drupal\Core\Render\Renderer->doRender(Array, false)
#14 /var/www/html/core/lib/Drupal/Core/Template/TwigExtension.php(490): Drupal\Core\Render\Renderer->render(Array)
#15 /var/www/html/sites/default/files/php/twig/5a008e9488529_node.html.twig_fOU7Z1faeO15YpZRrtd-F9Ksv/yHD4dpGBMlI8SMMqQ5z-QVQGNcCrpCuzsSt1E4ShcEU.php(111): Drupal\Core\Template\TwigExtension->escapeFilter(Object(Drupal\Core\Template\TwigEnvironment), Array, 'html', NULL, true)
#16 /var/www/html/vendor/twig/twig/lib/Twig/Template.php(432): __TwigTemplate_38fa5b6b1f6bdfd56bb4dba5e7d13d0f61126e79c913612089235f94cf12db1f->doDisplay(Array, Array)
#17 /var/www/html/vendor/twig/twig/lib/Twig/Template.php(403): Twig_Template->displayWithErrorHandling(Array, Array)
#18 /var/www/html/vendor/twig/twig/lib/Twig/Template.php(411): Twig_Template->display(Array)
#19 /var/www/html/core/themes/engines/twig/twig.engine(64): Twig_Template->render(Array)
#20 /var/www/html/core/lib/Drupal/Core/Theme/ThemeManager.php(384): twig_render_template('sites/all/theme...', Array)
#21 /var/www/html/core/lib/Drupal/Core/Render/Renderer.php(437): Drupal\Core\Theme\ThemeManager->render('node', Array)
#22 /var/www/html/core/lib/Drupal/Core/Render/Renderer.php(195): Drupal\Core\Render\Renderer->doRender(Array, false)
#23 /var/www/html/core/lib/Drupal/Core/Render/MainContent/HtmlRenderer.php(226): Drupal\Core\Render\Renderer->render(Array, false)
#24 /var/www/html/core/lib/Drupal/Core/Render/Renderer.php(576): Drupal\Core\Render\MainContent\HtmlRenderer->Drupal\Core\Render\MainContent\{closure}()
#25 /var/www/html/core/lib/Drupal/Core/Render/MainContent/HtmlRenderer.php(227): Drupal\Core\Render\Renderer->executeInRenderContext(Object(Drupal\Core\Render\RenderContext), Object(Closure))
#26 /var/www/html/core/lib/Drupal/Core/Render/MainContent/HtmlRenderer.php(117): Drupal\Core\Render\MainContent\HtmlRenderer->prepare(Array, Object(Symfony\Component\HttpFoundation\Request), Object(Drupal\Core\Routing\CurrentRouteMatch))
#27 /var/www/html/core/lib/Drupal/Core/EventSubscriber/MainContentViewSubscriber.php(90): Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object(Symfony\Component\HttpFoundation\Request), Object(Drupal\Core\Routing\CurrentRouteMatch))
#28 /var/www/html/core/lib/Drupal/Component/EventDispatcher/ContainerAwareEventDispatcher.php(108): Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object(Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent), 'kernel.view', Object(Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher))
#29 /var/www/html/vendor/symfony/http-kernel/HttpKernel.php(158): Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.view', Object(Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent))
#30 /var/www/html/vendor/symfony/http-kernel/HttpKernel.php(68): Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object(Symfony\Component\HttpFoundation\Request), 1)
#31 /var/www/html/core/lib/Drupal/Core/StackMiddleware/Session.php(57): Symfony\Component\HttpKernel\HttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#32 /var/www/html/core/lib/Drupal/Core/StackMiddleware/KernelPreHandle.php(47): Drupal\Core\StackMiddleware\Session->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#33 /var/www/html/core/modules/page_cache/src/StackMiddleware/PageCache.php(99): Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#34 /var/www/html/core/modules/page_cache/src/StackMiddleware/PageCache.php(78): Drupal\page_cache\StackMiddleware\PageCache->pass(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#35 /var/www/html/core/lib/Drupal/Core/StackMiddleware/ReverseProxyMiddleware.php(47): Drupal\page_cache\StackMiddleware\PageCache->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#36 /var/www/html/core/lib/Drupal/Core/StackMiddleware/NegotiationMiddleware.php(50): Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#37 /var/www/html/vendor/stack/builder/src/Stack/StackedHttpKernel.php(23): Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#38 /var/www/html/core/lib/Drupal/Core/DrupalKernel.php(657): Stack\StackedHttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#39 /var/www/html/index.php(19): Drupal\Core\DrupalKernel->handle(Object(Symfony\Component\HttpFoundation\Request))
#40 {main}.

This bug report seems to indicate that the paragraphs which is referenced doesn't exist. So it seems to have to do something with the ids, but I can't figure out what.
Answer: Finally I could make it working fixing two things in my code:
First. Adding the paragraph machine name as type to process statement:
process:
  type:
    plugin: default_value
    default_value: persona

Second. Changing the source parameter to the column which contains the id of the related paragraph.
After reading the Drupal issue list for Entity Reference Revisions I learned that now there is a more simple way to specify the target_id and target_revision_id. With the help from this thread I ended up using this process code for node import of field_person:
  field_person:
    -
      plugin: skip_on_empty
      method: process
      source: person
    -
      plugin: explode
      delimiter: ,
    -
      plugin: migration_lookup
      migration: article_persons
      no_stub: true
    -
      plugin: iterator
      process:
        target_id: '0'
        target_revision_id: '1'


Backup Master process fails to start -- HBase 1.0.1

Question: I am configuring HBase 188.8.131.52 in fully distributed mode over 3 nodes. Node-1 should run the Master server, zookeeper & regionserver; Node-2 should run zookeeper & regionserver; Node-3 should run Backup Master, zookeeper & regionserver. I am facing two issues with the setup and need your help — 1) when I run start-hbase.sh I can see that "HMaster" is running on Node-1; "HRegionServer" is running on both Node-2 & Node-3; "HQuorumPeer" is running on all the 3 Nodes. But the Backup Master process failed to start on Node-2…. Caused by: java.net.BindException: Address already in use 2) The second problem is, after running stop-hbase.sh the "HQuorumPeer" process continue to run on all the 3 nodes. They are not stopped by the stop-hbase.sh script.
Can you please help?
Regards, Gautam
Answer: If you are using Ubuntu, check this problem http://hbase.apache.org/book.html#loopback.ip
And check log files ( $HBASE_HOME/logs/hbase-hadoop-regionserver-{your_host}.log )
Answer: Answer for the first problem is port conflict. You either have started the backup master already on node-2 or you have someother process running on the port which hbase-master(backup) is trying to comeup on.I think the port for hbase master in newer version is 16010. so identify it and kill it.
And also you need to have the backup master hostname in the backup-masters file under the conf folder.
Second problem: Zookeeper has failed to stop. so you can manually kill them using kill command.


How to count the object inside the JsonArray?

Question: Below Json format is my input, i need to count the total based on Object
Students:[
        {
        "Student_id": "101"
        "Name": "Jon",
        "Course" : "Engineer"
        },
        {
        "Student_id": "102"
        "Name": "Snow",
        "Course" : "Medical"
        },
        {
        "Student_id": "103"
        "Name": "Walter",
        "Course" : "Chemistry"
        },
        {
        "Student_id": "104"
        "Name": "White",
        "Course" : "Chemistry"
        }
    ]

When i loop the JsonArray Am not able to count the total?? it will show always count 1,i want output like below format
No Of Students: 4
Total Chemistry Students :2

Below code i tried,
            JsonArray Students=Details.getAsJsonArray("Students");

            for(int i=0;i<Students.size();i++)
            {
                JsonObject Std=Students.get(i).getAsJsonObject();
                String SrdID=Std.get("Student_id").getAsString();

                System.out.println("Student Details----"+SrdID);
            }

            String [] Studentarr=new String[] {"Student_id"};
            int Count=Studentarr.length;

            System.out.println("Count ---"+ Count);

Any Help will be Appreciate!! Thanks In Advance
Comment: What have you tried so far?
Comment: *When i loop the JsonArray Am not able to count the total?? it will show always count 1* -- Share the code that *apparently* does this. Also, which json library are you using?
Comment: @NicholasK Gson
Comment: show the code whatever you tried?
Answer: Given that you know the structure for each element in the array is the same, could you create a Student class and have an array of Student objects?
In my experience, it's always better to manipulate objects than pure json, but you've not said in your question if that is a requirement or not, so I'll assume it is.
Therefore, you may find the answer on this similar question useful:
how to count length of the JSON array element
Hope this helps!
Answer: With this structure:
var object = {"Students":[
    {
    "Student_id": "101",
    "Name": "Jon",
    "Course" : "Engineer"
    },
    {
    "Student_id": "102",
    "Name": "Snow",
    "Course" : "Medical"
    },
    {
    "Student_id": "103",
    "Name": "Walter",
    "Course" : "Chemistry"
    },
    {
    "Student_id": "104",
    "Name": "White",
    "Course" : "Chemistry"
    }]};

Now, we can try with JS this:
print(object.Students.length) // print total
print(object.Students.filter(st => st.Course === 'Chemistry').length) // print occurrences

Output is:
> 4
> 2

Comment: in java we cant pass the pass  st => st.Course === 'Chemistry').length  in stream like this coz its not accepted 'Chemistry' it will accept single Char 'e'


How do I check if a column exists in SQL Server?

Question: How do I check if a column exists in SQL Server 2000?
Comment: possible duplicate of [How to check if column exists in SQL Server table](http://stackoverflow.com/questions/133031/how-to-check-if-column-exists-in-sql-server-table)
Answer: IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE  TABLE_NAME='tablename' AND COLUMN_NAME='columname' )

Answer: If col_length('table_name','column_name') is null
    select 0 as Present
ELSE
    select 1 as Present

Present will be 0, is there is no column_name present in table_name , otherwise 1
@CMS: I don't think that 'INFORMATION_SCHEMA.COLUMNS' have information about every table in DB. Because this didn't worked for me. But my answer did worked.
Answer: In query analyzer, select the Database that contains the table in which you need to check if the field exists or not and run the query below.
SELECT count(*) AS [Column Exists]
FROM SYSOBJECTS
INNER JOIN SYSCOLUMNS ON SYSOBJECTS.ID = SYSCOLUMNS.ID
WHERE
 SYSOBJECTS.NAME = 'myTable'
 AND SYSCOLUMNS.NAME = 'Myfield'

Answer: This should do nicely:
if COLUMNPROPERTY(object_id('table_name'), 'column_name', 'ColumnId') is null
  print 'doesn\'t exist'
else
  print 'exists'

Answer: I don't know if this script will work in sqlserver 2000, but in 2008 works:
SELECT COLUMNS.*
FROM INFORMATION_SCHEMA.COLUMNS COLUMNS, INFORMATION_SCHEMA.TABLES TABLES
WHERE COLUMNS.TABLE_NAME=TABLES.TABLE_NAME AND UPPER(COLUMNS.COLUMN_NAME)=UPPER('column_name')


B-spline curve fitting with conditions on derivatives

Question: I have 5 data points. I'm trying to make a b-spline that passes through these points. At each data point I also have a derivative. The b-spline must meet this condition. Anyone that has an idea of how to approach this?
Answer: I'm assuming your "points" are in 2D or 3D. So, you have 5 points and 5 derivative vectors. You can insert a cubic segment between each pair of points. This will give you a cubic b-spline that is $C_1$-continuous.
Specifically, suppose your 5 points are $P_1, P_2, P_3, P_4, P_5$ and your 5 derivative vectors are $V_1, V_2, V_3, V_4, V_5$. Assign parameter values $t_1, t_2, t_3, t_4, t_5$ to the 5 points. You can use $t_1=0$, and $t_5=1$, and $t_2, t_3, t_4$ should be spaced according to the spacing of the points. Let $h_i = (t_{i+1}-t_i)/3$ for $i=1,2,3,4$.
Your b-spline should have knot sequence
$$(0,0,0,0, t_2, t_2, t_3, t_3, t_4, t_4, 1,1,1,1)$$
and its control points should be
$$P_1, \quad P_1 + h_1V_1, $$
$$P_2 - h_1V_2, \quad P_2 + h_2V_2,$$
$$P_3 - h_2V_3, \quad P_3 + h_3V_3, $$
$$P_4 - h_3V_4, \quad P_4 + h_4V_4,$$
$$P_5 - h_4V_5, \quad P_5$$
So, 10 control points and 14 knot values, which works out correctly for a b-spline of degree 3 (order 4).
Comment: Thanks a lot. This really helped. Does this "method" have a name so that I can read more about it?
Comment: The general technology is called "deBoor-Fix dual functionals", but what I showed is a very very simple special case. You can read about this stuff in deBoor's book "A Practical Guide to Splines".