Erro de NullPointer Exception ao trazer dados Fragment

Question: Estou com um erro de NullPointerException ao tentar retornar os dados de um Fragment. O erro de NPE é bem nesta linha:
String comentarioFoto = fragment_obj.campoComentarioFoto.getText().toString();

Vejam o meu código da activity:
public class LayoutActivity extends SherlockFragmentActivity {

     Fragment1 fragment_obj;

    private static final int SELECT_PICTURE = 1;
    private String selectedImagePath;

    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;

    private WrapData wd;
    private String answer;

    File caminhoFoto;
    File caminhoVideo;
    VideoView videoview;
    Spinner campoDepartamento;

    Button btnenviaVideo;
    Button btnenviaFoto;

    private String[] departamentoNome = new String[]{"Assistência Social", "Administração", "Agricultura", "Educação", "Finanças",
            "Indústria Comércio e Turismo", "Planejamento e Urbanismo", "Transportes", "Obras e Serviços Públicos e Urbanos"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ActionBar ab = getSupportActionBar();
        ab.setDisplayHomeAsUpEnabled(true);

        /* Variáveis dos botões do campo foto e Video */

        btnenviaFoto = (Button) findViewById(R.id.btn_salvarFoto);
        btnenviaVideo = (Button) findViewById(R.id.btn_salvarVideo);

        /* Recupera os dados do Fragment */

        Fragment1 fragment_obj = (Fragment1)getSupportFragmentManager().findFragmentById(R.id.containerFragment);
        String comentarioFoto = fragment_obj.campoComentarioFoto.getText().toString();
        System.out.println(comentarioFoto);

    }
}

Código do Fragment:
package br.com.example.souprogresso;

// FRAGMENTO RESPONSAVEL PELO LAYOUT DE FOTO

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.support.v4.app.Fragment;

public class Fragment1 extends Fragment {

    EditText campoComentarioFoto;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.layout_fragment_1, container, false);

        campoComentarioFoto = (EditText) rootView.findViewById(R.id.edt_comentarioFoto);
        //String comentarioFoto = campoComentarioFoto.getText().toString();

        return rootView;
    }

}

XML do fragment:
<?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:id="@+id/containerFragment"
     >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            >

            <ImageView
                android:id="@+id/img_camera"
                android:layout_width="match_parent"
                android:layout_height="120dp"
                android:background="#000"
                android:src="@drawable/bg"/>

            <Button
                android:id="@+id/btn_tirarFoto"
                android:layout_width="match_parent"
                android:layout_height="45dp"
                android:onClick="tirarFoto"
                android:text="Tirar Foto" />

            <Button
                android:id="@+id/btn_capturaFoto"
                android:layout_width="match_parent"
                android:layout_height="45dp"
                android:onClick="selecionarFoto"
                android:text="Capturar Foto do Celular" />

            <Button
                android:id="@+id/btn_abrirMapa"
                android:layout_width="match_parent"
                android:layout_height="45dp"
                android:text="Buscar Localização" />

            <TextView
                android:text="Digite um Comentário"
                android:textSize="15sp"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:paddingLeft="15dp"
                android:textColor="#000"
                />

            <EditText
                android:id="@+id/edt_comentarioFoto"
                android:layout_width="match_parent"
                android:layout_height="72dp"
                android:background="#FFF"
                android:ems="10"
                android:inputType="textMultiLine"
                android:hint="Digite um comentário"
                 />

            <Button
                android:id="@+id/btn_salvarFoto"
                android:layout_width="match_parent"
                android:layout_height="65dp"
                android:onClick="salvarBDFoto"
                android:text="Enviar Foto"
                />

        </LinearLayout>

</ScrollView>

Comment: cara tá muito estranho esse erro. Não consigo resolver. Ele simplesmente não pega os valores que tento passar
Answer: Estamos assumindo que você declarou o fragment no xml da Activity , ok? Porque se não tiver feito isso, o fragment ainda não está adicionado na activity.
O segundo ponto é que o fragment pode não estar adicionado a Activity no local onde você está tentando obter o valor do campo.
Então, você pode sobrescrever esse método para saber a hora certa de fazer essa operação:
 @Override
    public void onAttachFragment(Fragment fragment) {
        super.onAttachFragment(fragment);

        if(fragment instanceof Fragment1){
            ((Fragment1)fragment).campoComentarioFoto.getText().toString();
        }
    }

Esse código não faz muito sentido para mim, mas apenas para você entender o que possa estar acontecendo no seu caso.


Piecewise linear functions in constructive mathematics

Question: Is is possible to constructively prove that, for any function $f:\mathbb{R}\to\mathbb{R}$ piecewise linear, the absolute value $|f|:\mathbb{R}\to\mathbb{R}$ is also piecewise linear ?
"Constructively" is for example in the sense of Bishop's constructive mathematics, not in the sense of algorithms (recursive functions).
Piecewise linear can either mean to produce an ordered list of real numbers $a_1<\dots <a_n$ such as $|f|$ is linear on each $[a_i,a_{i+1}]$, or produce an unordered list of corner functions (only 1 angular point) of which $|f|$ is the sum. In both cases, the number of angular points of $f$ and $|f|$ is assumed to be finite.
It seems hard, because that would require to exactly compare the values of $f$ with $0$, to know when to insert angular points $a_i$ for $|f|$. Such a comparison of real numbers is not constructive.
Even on a single interval, $f : [a,b] \to\mathbb{R}$ linear, it seems hard. If there is a point $c\in \, ]a,b[$ such as $f(c)=0$, then $|f|$ is piecewise linear on the subdivision $a<c<b$. Otherwise $|f|$ is piecewise linear on $a<b$. Constructively you would need to know which case it is, but then you would need to exactly compare $f(a)$ and $f(b)$ with $0$.
Comment: It is constructive for _linear_ functions on an interval, though. Isn't it? Or am I missing something?
Comment: Do you mean an algorithm? For example the input would be the collection of intervals and the expression of the function on them, and the output would be the same for $|f|$. There is the problem that there could be infinitely many intervals.
Comment: How can yo produce an ordered list of real numbers, when comparison is not constructive?
Comment: @HagenvonEitzen You assume that ordered list given by $f$, then can hope to use that information on orders to insert new angular points for $|f|$. But actually the 1-interval case suggested by Arthur is almost a proof that this question is impossible I think.
Comment: Is perhaps the use of absolute value of a number allowed (perhaps in the form $|x|:=\sqrt{x^2}$)? That would also give us max and min and might be used to construct $|f|$ with possibly some redundant support points ...
Comment: @HagenvonEitzen Yes the absolute value is constructive. It is usually defined as the uniformly continuous completion of the absolute value of the rational numbers. It does give min and max as you mention, and redundant points are allowed, but I don't think that helps much.
Answer: Say that a function $f \colon \mathbb{R} \to \mathbb{R}$ is somewhere linear if there are rational numbers $p < q$ such that the restriction of $f$ to $[p, q]$ is linear. Note that every piecewise linear function is somewhere linear. I claim that it is not constructively provable that $|f|$ is somewhere linear whenever $f$ is linear.
It is consistent with Bishop style constructive mathematics that continuous choice holds: that if $(\forall \alpha \in \mathbb{N}^\mathbb{N})(\exists n \in \mathbb{N})\phi(\alpha, n)$, then there is a continuous function $F \colon \mathbb{N}^\mathbb{N} \to \mathbb{N}$ such that for all $\alpha \in \mathbb{N}^ \mathbb{N}$, we have $\phi(\alpha, F(\alpha))$. It follows that the same is true if we take the domain to be $2^\mathbb{N} \times 2^\mathbb{N}$, ie given $(\forall \alpha, \beta \in 2^\mathbb{N})(\exists n \in \mathbb{N})\phi(\alpha, \beta, n)$ we have continuous $F \colon 2^\mathbb{N} \times 2^\mathbb{N} \to \mathbb{N}$. I'll show that the above statement is non constructive, by showing it contradicts continuous choice.
Given $\alpha, \beta \in 2^\mathbb{N}$, write $a$ for $\sum_{i = 0}^\infty \alpha(i) 2^{-i}$ and $b$ for $\sum_{i = 0}^\infty \beta(i) 2^{-i}$. Then there exists a natural number encoding rationals $p, q$ such that the function $f(x) := | a x + b |$ is linear on $[p, q]$, by assumption. By continuous choice, in particular continuity at the point $(\lambda n.0, \lambda n.0)$, we have a single choice of rational numbers $p, q$ and a natural number $N$ that whenever $\alpha(n) = 0$ and $\beta(n) = 0$ for $n < N$, $| a x + b |$ is linear on $[p, q]$. However, this gives a contradiction, because for any given $p < q$ we can find $\alpha, \beta$ with $\alpha(n) = \beta(n) = 0$ for $n < N$, such that the corresponding function $a x + b$ crosses the $x$-axis between $p$ and $q$.
Comment: Very nice, thanks. That is probably the reason why Bishop's constructive measure theory starts with continuous functions with compact support, instead of continous piecewise-linear functions with compact support. The latter are not constructively stable by absolute value.


Error from running tensorflow models in parallel, when sequentially it works fine

Question: Trying to use multiple TensorFlow models in parallel using pathos.multiprocessing.Pool
Error is:
multiprocess.pool.RemoteTraceback:

Traceback (most recent call last):
  File "c:\users\burge\appdata\local\programs\python\python37\lib\site-packages\multiprocess\pool.py", line 121, in worker
    result = (True, func(*args, **kwds))
  File "c:\users\burge\appdata\local\programs\python\python37\lib\site-packages\multiprocess\pool.py", line 44, in mapstar
    return list(map(*args))
  File "c:\users\burge\appdata\local\programs\python\python37\lib\site-packages\pathos\helpers\mp_helper.py", line 15, in <lambda>
    func = lambda args: f(*args)
  File "c:\Users\Burge\Desktop\SwarmMemory\sim.py", line 38, in run
    i.step()
  File "c:\Users\Burge\Desktop\SwarmMemory\agent.py", line 240, in step
    output = self.ai(np.array(self.internal_log).reshape(-1, 1, 9))
  File "c:\users\burge\appdata\local\programs\python\python37\lib\site-packages\tensorflow\python\keras\engine\base_layer.py", line 1012, in __call__
    outputs = call_fn(inputs, *args, **kwargs)
  File "c:\users\burge\appdata\local\programs\python\python37\lib\site-packages\tensorflow\python\keras\engine\sequential.py", line 375, in call
    return super(Sequential, self).call(inputs, training=training, mask=mask)
  File "c:\users\burge\appdata\local\programs\python\python37\lib\site-packages\tensorflow\python\keras\engine\functional.py", line 425, in call
    inputs, training=training, mask=mask)
  File "c:\users\burge\appdata\local\programs\python\python37\lib\site-packages\tensorflow\python\keras\engine\functional.py", line 569, in _run_internal_graph
    assert x_id in tensor_dict, 'Could not compute output ' + str(x)
AssertionError: Could not compute output KerasTensor(type_spec=TensorSpec(shape=(None, 1, 4), dtype=tf.float32, name=None), name='dense_1/BiasAdd:0', description="created by layer 'dense_1'")

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "c:\Users\Burge\Desktop\SwarmMemory\sim.py", line 78, in <module>
    p.map(Sim.run, sims)
  File "c:\users\burge\appdata\local\programs\python\python37\lib\site-packages\pathos\multiprocessing.py", line 137, in map
    return _pool.map(star(f), zip(*args)) # chunksize
  File "c:\users\burge\appdata\local\programs\python\python37\lib\site-packages\multiprocess\pool.py", line 268, in map
    return self._map_async(func, iterable, mapstar, chunksize).get()
  File "c:\users\burge\appdata\local\programs\python\python37\lib\site-packages\multiprocess\pool.py", line 657, in get
    raise self._value
AssertionError: Could not compute output KerasTensor(type_spec=TensorSpec(shape=(None, 1, 4), dtype=tf.float32, name=None), name='dense_1/BiasAdd:0', description="created by layer 'dense_1'")

The creation of the pool is as follows:
if __name__ == '__main__':
    freeze_support()

    model = Sequential()
    model.add(Input(shape=(1,9)))
    model.add(LSTM(10, return_sequences=True))
    model.add(Dropout(0.1))
    model.add(LSTM(5))
    model.add(Dropout(0.1))
    model.add(Dense(4))
    model.add(Dense(4))

    models = []
    sims = []

    for i in range(6):
        models.append(tensorflow.keras.models.clone_model(model))
        sims.append(Sim(models[-1]))

    p = Pool()
    p.map(Sim.run, sims)

Basically, I am running a simulation using the model provided to the class sim. This means after the sim has run I can get use a fitness function on results, and apply a genetic algorithm to the results.
GitHub link for more information, under branch python-ver:
https://github.com/HarryBurge/SwarmMemory
EDIT:
In case anyone needs to know how to do this in the future.
I used keras-pickle-wrapper to be able to pickle the keras model and just pass it to the run method.
models = []
sims = []

for i in range(6):
      models.append(KerasPickleWrapper(tensorflow.keras.models.clone_model(model)))
      sims.append(Sim())

p = Pool()
p.map(Sim.run, sims, models)

Answer: I'm the author of pathos.  Whenever you see self._value in the error, what's generally happening is that something you tried to send to another processor failed to serialize.  The error and traceback is a bit obtuse, admittedly.  However, what you can do is check the serialization with dill, and determine if you need to use one of the serialization variants (like dill.settings['trace'] = True), or whether you need to restructure your code slightly to better accommodate serialization.  If the class you are working with is something you can edit, then an easy thing to do is to add a __reduce__ method, or similar, to aid serialization.
Comment: I am not to familiar with pickle, would I also have to add a rebuild method for the class?
Comment: No, if you add an appropriate reduce method, that should be it.


String.format prints 'question mark' as output

Question: I am fairly new to programming and was following a tutorial on youtube and I got stuck at this code:
public static void main(String[] args) {
   System.out.println(String.format("%02d", 1));
}

The code is supposed to print 01 as output but instead I get ??, just 2 question marks. Can someone explain what I am doing wrong ?
Comment: Your code prints  `01` [check](http://ideone.com/hPuQDx)
Comment: It doesn't. I've tried both in eclipse and cmd.
Plus I've tried another things as well, it always prints just "????"
Comment: try `System.out.format(Locale.US, "%02d", 1);`. Also set your project encoding as UTF-8.
Comment: Thanks, I found the mistake
Comment: What was the issue ?
Comment: The numbers were being displayed in hindi format. And the output just displayed them as question marks. Don't even know why eclipse is changing these numbers to hindi numbers
Answer: Nevermind, I figured it out. Eclipse was using hindi format numbers to display output (don't know why ?). Setting project encoding to UTF-8 allowed me to see them instead of 'question marks'.


Pager not displaying

Question: I am having problems getting a pager to display after a table in the block_view hook of a module
The code for the query is the following one.
$query = db_select('registry', 'r');
$query = $query->extend('PagerDefault')->extend('TableSort');

$query->limit(10)
    ->fields('r', array('name', 'type', 'filename','module','weight'));
$result = $query->execute();

I build and the table with no problem adding it to the content
Then I add the pager or rather I don't with the following code
$block['content'] .= theme('pager').'
mmm
';

the mmm bit was just there as a quick check to see what was happening.
I know that the extend needs to be assigned to a new variable and I believe that I am doing this.
Is there anything wrong I am doing?
This is the complete code of the module.
/**
 * @file
 * A block module that displays registry info.
 */

/**
 * Implements hook_help.
 *
 * Displays help and module information.
 *
 * @param path
 *   Which path of the site we're using to display help
 * @param arg
 *   Array that holds the current path as returned from arg() function
 */
function current_posts_help($path, $arg) {
  switch ($path) {
    case "admin/help#current_posts":
    return '
' . t("Displays registry info for testing tables and pager") . '
';
    break;
  }
}

/**
 * Implements hook_block_info().
 */
function current_posts_block_info() {
  $blocks['current_posts'] = array(
    'info' => t('Current posts'), //The name that will appear in the block list.
    'cache' => DRUPAL_CACHE_PER_ROLE, //Default
  );
  return $blocks;
}

function current_posts_block_view($delta = '') {
  switch($delta) {
    case 'current_posts':
      $block['subject'] = t('Modules list');
      if(user_access('access content')) {
        $query = db_select('registry', 'r');
        $query = $query->extend('PagerDefault');
        //$result = $query->limit(50)
        $query->limit(10)
          ->fields('r', array('name', 'type', 'filename','module','weight'));
        $result = $query->execute();

        // Array to contain items for the block to render.

        $rows = array();

        // Iterate over the resultset.
        foreach ($result as $node) {
          $rows[] = array(
            'name' => t($node->name),
            'type' => t($node->type),
            'filename' => t($node->filename),
            'module' => t($node->filename),
          );
        }

        // Table header.
        $header = array(
          'name' => t('Name'),
          'type'     => t('Type'),
          'filename'    => t('Filename'),
          'module'    => t('Module'),
        );

        $block['content'] = theme('table', array(
          'header'  => $header,
          'rows'    => $rows,
          'id'      => 'table-articles',
          'class'   => 'articles',)
        );

        $block['content'] .= theme('pager').'
mmm
';
      }

      return $block;
  }
}

/**
 * Implements hook_menu().
 */
function current_posts_menu() {
  $items = array();

  $items['admin/config/content/current_posts'] = array(
    'title' => 'Current Registry',
    'description' => 'Configuration for Current posts module',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('current_posts_form'),
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

/**
 * Page callback: Current posts settings
 *
 * @see current_posts_menu()
 */
function current_posts_form($form, &$form_state) {
  $form['current_posts_max'] = array(
    '#type' => 'textfield',
    '#title' => t('Maximum number of posts'),
    '#default_value' => variable_get('current_posts_max', 3),
    '#size' => 2,
    '#maxlength' => 2,
    '#description' => t('The maximum number of links to display in the block.'),
    '#required' => TRUE,
  );

  return system_settings_form($form);
}

Comment: Does the query return more than 10 rows?
Comment: Yes it does - it's 340 records

As additional info I have now tried the example pager. This works but it is a menucallback page rather than part of a module. If I cut and paste the code from here to the example it works.

Seems that I have a problem with it being in a module???
Comment: I tested your code on my test site, and it works.
Answer: I think I know what is going on. I've had this problem several times before.
The issue is that on some pages, multiple pagers may be in use. Which would explain why theme('pager'); wouldn't work.
I just had the same problem, and I got it working by doing this:
theme('pager', array('element' => 1));

On my end, I wasn't displaying multiple pagers, but I think something else on the page must have been doing this, because the above code made it work! I hope this helps anyone else who encounters the same problem.
Answer: I have just solved this myself. What a head-banger this one was.
Just try replacing:
$query = $query->extend('PagerDefault')->extend('TableSort');

with:
$query = $query->extend('PagerDefault')->element(0)->extend('TableSort');

Answer: After the code  $result = $query->execute(); try adding the following code for initializing a pager for theme('pager').
pager_default_initialize($total,5);

$total -> total result count and argument '5' means 5 results should show in each page.
Comment: that does work if I put in pager_default_initialize(340,5); problem is that according to the docs it should work from the ->extend('PagerDefault'); and the 340 that I have replaced $total with is the total number or records however I do not have immediate access to that. I have also had a game with just getting the query to work, maybe this is the root of the problem.
Answer: I'm assuming this is still some kind of bug in Views, but the pager tends to fail when trying to create an HTML template for it. In most cases your could manage with CSS.
Answer: The '->extend('PagerDefault') extension in the query had to be the first function in the daisy chain. If not there is no error but the function seems to not be called.And one more thing, fields('table',array('id','name','created','uid')) check you mention fields properly,This is working for me.
$query = db_select('address_book', 'n')
        ->extend('PagerDefault') //Pager Extender
        ->fields('n', array('address_id'))
        ->condition('status', 1)
        ->orderBy('created', 'DESC')
        ->limit(10);
see this link
https://stackoverflow.com/questions/9614549/drupal-7-themepager-table-gets-rendered-but-without-pager

Pager not displaying


Diferença de uso de objeto imutável em argumento de método ou fora dele

Question: Se eu tenho a seguinte String cuja mesma foi criada:
String s1 = "Primeira String";

Ao usar o método:
s1.toUpperCase();

nada acontece porque neste momento foi criada uma instância e não foi atribuída a nenhuma variável.
Mas se eu rodar:
System.out.println(s1.toUpperCase());

eu vejo o resultado em maiúsculo, qual é a diferença destes casos?
Answer: A diferença é só que um você não vê e a outra você vê, nada mais. A diferença é o método println().

nada acontece

Premissa errada.

neste momento foi criada uma instância

Contradiz a premissa.
O primeiro cria a instância nova e nada mais pode se fazer com aquilo. Teve custo para criar, ocupou memória e ficará lá até o objeto ser coletado. O segundo código passa esse objeto através de uma referência para o método println() fazer o que ele sabe fazer, então potencialmente terá um tempo de vida garantido um pouco maior, mas na prática sabemos que isso não importa em um exemplo simples, o objeto só estará disponível por um instante na sua criação e execução do método.
Na verdade o problema em si nada tem a ver com o fato do objeto ser imutável, isso é circunstancial, qualquer objeto que fosse criado ocorreria o mesmo.
Talvez falte entendimento do que é uma variável, ela é mais simples do que as pessoas imaginam.
Comment: A sua primeira fase esclareceu pra mim rsrs, obrigado.


SQL SERVER Agent stops working Automatically

Question: I have been experiencing a strange issue for last few weeks. On my two
different servers the sql server Agent stops working automatically,
All I have to do is to restart the agent and is back on running. But
because it stops working it misses the backup jobs I and few other
jobs I have scheduled on them Sql Agents.
It doesn't happen with any of the other servers but it only happens
on these two particular servers.
All the servers are SQL SERVER 2008 R2 , Data Centre Edition. 64-bit.
Has anyone ever experienced the same issue if yes what did you do to resolve it ?
Comment: do you have any error message, warning in the windows log? Do you have any services restarting during night? Is it happening always at the same time, after or before the same event?
Comment: I'm having the same issue - however whenever I start any of the other SQL services, the SQL Server Agent stops running.
Comment: Check the SQL Server log, too, as well as the history of SQL Agent jobs to see what might have been running when they last stopped.
Comment: Thank you guys for your quick replies. I dont get any error messages or anything else. When I check the Job history all it says it `Sql Agent not running` and thats all. I have been looking online for solutions and I am not alone facing this problem lots of people are having problems with Sql Agent. @PaulWilliams I have seen Log history nothing was running at that time when it stopped working and it has stopped at random times in the past. funny thing is it only happens with two particular servers never hapened with any of other servers.
Answer: <code>Start > search for "Services", Component Services, locar Services - "SQL Server Agent" in the list, and change Manual to automatic.
</code>
It will start the service the service automatically.
Answer: Just to add .02 cents, this was happening to me as well.  I figured out that my SQL Server Agent was stopping when my server was automatically restarted for Windows updates. The associated service for the agent was set to restart manually. I went straight to the Windows Services panel (Start > search for "Services"), found "SQL Server Agent" in the list, and set it to start automatically.
Answer: "You can configure SQL Server Agent to restart the SQL Server and SQL Server Agent services automatically if they stop unexpectedly"

Open the SQL Server Management Studio Management folder, right-click
the SQL Server Agent entry, and select Properties.
On the General page, select the Auto Restart SQL Server If It Stops Unexpectedly check box.
Here, you should also select the Auto Restart SQL Server Agent If It Stops Unexpectedly check box.
Click OK.

Read more about Configure SQL Server Agent to Restart Services Automatically
Also check Access control lists for the SQL Agent group in case its related.
Configure Windows Service Accounts and Permissions
Comment: thank you for your suggestion, I think it will do the job but is there any permanent fix for this problem ?? I mean if it stops working in the middle of a JOB, this solution will restart it but wont reschedule the job itself. I want to fix this issue once for all :)
Comment: I am not sure about that. But you will need to find what causing it to stop. Probably the windows error log might give you a clue!
Comment: Where is the "SQL Server Management Studio Management folder" located?
Answer:
Open The computer Management app
Select services & Applications
Select SQL Server Configuration Manager
Select SQL Server Service (double click)
Select First option SQL Server (MSSQLSERVER)
Right click and go to properties then authenticate
Select this account option and use your sign in credentials to authenticate service
Once done service will not drop all good.


HTML5 Video | Video Unsupported / Invalid File Type | IE

Question: Good Evening StackOverflowers!
I seem to have a problem with getting the HTML5 video tag to work in IE, or Safari (Firefox seems to load, but it wants to download the entire file before playing). It works in Chrome without issue.
In IE, I get the error: "Error: Unsupported video type or invalid file path".
I have done research, and it seems many find a solution by adding MIME types to their .htaccess file. I have done this to no avail. The next problem was that I needed to put the .mp4 first in the video listing, done - but no solution.
My .htaccess file looks like this: (WordPress Install)
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /wpress/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /wpress/index.php [L]
</IfModule>

# END WordPress

#Audio HTML5 Mime Types
AddType audio/aac .aac
AddType audio/mp4 .mp4 .m4a
AddType audio/mpeg .mp1 .mp2 .mp3 .mpg .mpeg
AddType audio/ogg .oga .ogg
AddType audio/wav .wav
AddType audio/webm .webm

#Video HTML5 Mime Types
AddType video/mp4 .mp4 .m4v
AddType video/ogg .ogv
AddType video/webm .webm

Additionally, this is what my video code looks like: (Yes, I know it's wordy...)
<video width="100%" height="100%" controls="controls">
  <source src="http://www.frozentears.org/wpress/wp-vlog/vlogVid/Rus/[RUS]Rossiyskaya.Imperia/[RUS]Rossiyskaya.Imperia.E01.Petr.I.PI.mp4" type='video/mp4' />
  <source src="http://www.frozentears.org/wpress/wp-vlog/vlogVid/Rus/[RUS]Rossiyskaya.Imperia/[RUS]Rossiyskaya.Imperia.E01.Petr.I.PI.webm" type='video/webm' />
  Video tag not supported. Download the video here.
</video>

The whole page that is giving me issues can be seen here: http://bit.ly/1g2quqe
I have checked the stack and found these threads here, here and here, followed their advice, but for some reason it still has yet to work for me.
Furthermore, some suggested that I put the file path in the address bar, if the file plays then the error is in the code. When I put the .mp4 file in the address bar, I was just prompted to download the file, the browser didn't play the file.
Any advice would be greatly appreciated.
Best regards,
Laura
Comment: Which versions of IE and Safari are causing you problems?
Comment: Sorry - Excellent question -
IE 11
Firefox 28
Answer: I could not get to play your files on any browser correctly. Chrome only played the audio after 30 sec download but no video. In Firefox when I tried to put the URL of the mp4 in the browser I got an error saying the file is corrupted. I think it could be a file format issue. If it the case it is probably some bad data or metadata in the file:

You can download the file at http://vjs.zencdn.net/v/oceans.mp4 and host it on your server. If it works fine then your MIME/TYPES config is fine otherwise you need to tune them right (look at adding them to the /etc/mime.types file).
You can try to use handbrake or MP4Box to repack your file. You need to activate the "web optimized" option (aka fast start) with handbrake.

You can read here for the underlying story.
Let us know if it works
Comment: You're remarkable. Thank you so much for taking the time to respond. You were absolutely right. Your .mp4 file worked excellently in all my browsers as well. I am now in the process of re-converting all my files with handbrake. (Previously, I had used Miro Video Converter).

Thank you so much for solving the headache I've had for weeks.
Comment: Sorry for necrobumping it in 2020, but I had a similar issue. Browsers I have tried, Firefox 77, Chromium 83, and Falkon, don't like to play h265 encoded mp4 videos. Convert your videos to h264 to play them...


Pegar IMEI via Javascript

Question: É possível através de uma página web conseguir pegar o IMEI do celular de quem acessa utilizando javascript ou qualquer outra coisa?
Comment: Não é possível! Como disse o nosso amigo @Articuno seria uma falha de segurança gravíssima! Talvez você consiga essa informação, mas criando uma APP nativo!
Comment: Duvido muito, seria uma falha de segurança gravissima permitir isso.
Answer: Não, não é possível. E isso é bom, por vários motivos, mas principalmente:

É possível bloquear um aparelho celular remotamente apenas com seu IMEI. Isso é feito geralmente em caso de furto ou roubo. Agora imagine uma pessoal mal-intencionada que tenha colhido seu email através de um site - essa pessoa poderia entrar em contato e tentar extorquir dinheiro de você sob a ameaça de bloquear seu aparelho caso você não pague.
Javascript nos navegadores não tem acesso a nada que possa identificar uma máquina de forma única. Você não tem como obter o nome do computador na rede, ou acessar a estrutura de diretórios do cliente, por exemplo. A razão segue uma linha parecida com a do motivo anterior: qualquer coisa que você pudesse fazer com essas informações seria uma violação de privacidade.

Se você quer alguma informação do cliente, crie uma página na qual ele possa informar essas coisas manualmente.

Pegar IMEI via Javascript


How to construct a Bernstein set and what are their applications?

Question:
Bernstein Set: A subset of the real line that meets every uncountable closed subset of the real line but that contains none of them. It's from wiki.

My question is this: How to construct a Bernstein set? And what's its application in mathematics?
Thanks ahead for any help:)
Answer: One uses the axiom of choice in some form to construct a Bernstein set. The most straightforward way is by transfinite recursion. There are $2^\omega$ uncountable closed subsets of $\Bbb R$, so we can list them as $\{F_\xi:\xi<2^\omega\}$, and it can be proved that each of them has cardinality $2^\omega$.
Now suppose that $\eta<2^\omega$, and for each $\xi<\eta$ you've chosen points $x_\xi,y_\xi\in F_\xi$ so that all of these points are distinct. Let $X_\eta=\{x_\xi:\xi<\eta\}$ and $Y_\eta=\{y_\xi:\xi<\eta\}$. Then $|X_\eta\cup Y_\eta|<2^\omega$, so $F_\eta\setminus(X_\eta\cup Y_\eta)$ is infinite, and we can choose distinct $x_\eta,y_\eta\in F_\eta\setminus(X_\eta\cup Y_\eta)$ to continue the construction.
Now let $X=\bigcup_{\xi<2^\omega}X_\xi$ and $Y=\bigcup_{\xi<2^\omega}Y_\xi$; by construction $X$ and $Y$ are disjoint sets meeting each uncountable closed subset of $\Bbb R$, so both are Bernstein sets.
Added: In my experiences they are most useful as a tool for constructing (counter)examples. This post in Dan Ma's Topology Blog is a good example of such use.
Comment: Very appreciatd your construction! (Please vote me:))
Comment: Does your construction imply that X U Y = R?
Comment: @user114634: No, it doesn't.
Answer: Notice that the usual construction of the Bernstein set can also yield $\mathfrak c$ disjoint Bernstein sets in an arbitrary uncountable Polish space by working diagonally, similarly to how you construct a bijection between $\mathbf N$ and $\mathbf N^2$: you take one point from the first closed set into the first Bernstein set, two points from what remains of the second closed set to first two Bernstein sets etc, resulting in a sequence of distjoint sets, each of which intersects all but possibly some $\kappa<\mathfrak c$ uncountable closed sets. Then you notice that every (uncountable) closed set contains $\mathfrak c$ other (uncountable) closed subsets, so each of those actually intersects ALL uncountable closed sets.
In many ways, Bernstein sets are "as pathological as possible" for a subset of a Polish space, and as such are often good source of examples of pathological behavior.
Bernstein sets are not only non-measurable (and extremely so: the outer measure of a Bernstein set with respect to any continuous Borel measure is full, while the inner is zero!), but also do not have Baire property.
They are also quite interesting as topological measure spaces. Every compact subset of the Bernstein set is countable, so it's impossible to define a (nontrivial) continuous Radon measure on Bernstein set, which makes them sort of the opposite of Polish spaces -- in a Polish space, any finite Borel measure is Radon.
Comment: "The usual construction of the Bernstein set can also yield c disjoint Bernstein sets in an arbitrary uncountable Polish space by working diagonally." It's nice:) Vote me!
Answer: This is exactly the Proposition 3.1 in Handbook of Game Theory, Volume 1, Chapter 3, Jan Mycielski.

There is a payoff set such that the Gale-Stewart game is not determined.

Proof: Let the payoff set be the Bernstein set. Given an arbitary strategy, the set of all possible outcomes generated by it is a perfect set(see Brian M. Scott's answer), so for any strategy of one player, there is pair of opponent's strategies that generate two outcomes that are in the payoff set and its complement respectively.
Answer: Since a Bernstein set is nonmeasurable, you can't do it without some form of the Axiom of Choice: there's no "explicit" construction.
An example of an application: show that every measurable set of positive measure contains a nonmeasurable set.
Answer: Here's one: If $\omega_1$ injects into reals then there is an uncountable set of reals without perfect subset. Hence the statement that every set of reals has the perfect set property implies that $\omega_1$ is inaccessible in $L$ (constructible universe).
Answer: Here's an "application": Let P be a partition of reals induced by the equivalence relation $x \sim y$ iff $x - y$ is rational. A choice set for P is called a Vitali set. Show that for each real $m > 0$ there is a Vitali set of outer measure $m$.
Answer: See this blog post of Dan Ma for a detailed construction of Bernstein set.
A Bernstein set $B$ intersect every closed uncountable sets and contains none of them. In other words the set $B$ and it's set theoretic complement $B^c$ intersect every closed uncountable sets.
Intersecting every closed uncountable sets can be replaced by intersecting every perfect sets( why?)

$A\subset \Bbb{R}$ is called saturated non measurable set iff$$m_i(A) =0=m_i(A^c)$$
Where $m_i(A) $ is the inner measure of $A$ and $A^c=\Bbb{R}\setminus A$
See here

Bernstein set is a saturated non measurable set.

Complement of a Bernstein is also Bernstein.

Bernstein set doesn't exists in ZF alone, one need some form of choice! (see here)

Bernstein set doesn't have the Baire Property i.e one can't express   Bernstein set as a symmetric difference of an open set and a meager set (see here).

Any measurable subset of a Bernstein set must be a null set (lebesgue outer measure $0$). See here

Any subset of Bernstein set having the Baire property must be of meager.

Two applications of Bernstein sets:
Theorem $1$: Any set of positive measure contains a set that fails to be measurable.
Proof: Let $A\in\mathcal{L}(\Bbb{R}) $ and $m(A) >0$.
Consider $A\cap B$ and $A\cap B^c$ where $B$ is a Bernstein set.
Then at least one of the sets $A\cap B$ or $A\cap B^c$ must be non measurable otherwise both the sets $A\cap B$ and $A\cap B^c$ being the measurable subsets of Bernstein set must have measure $0$ but it would contradict that $m(A) >0$.

Theorem $2$: Any non meager (second category) subset of $\Bbb{R}$ contains a set that fails to have the property of Baire.
Proof: Let $A\subset \Bbb{R}$ be a non meager set.
Consider $A\cap B$ and $A\cap B^c$ where $B$ is a Bernstein set.
Then at least one of the sets $A\cap B$ or $A\cap B^c$ doesn't have the Baire property otherwise both the sets $A\cap B$ and $A\cap B^c$ being the BP subsets of Bernstein set must be meager but it would contradict that $A$ is non meager.


Unable to integrate FixedSizeList (react-window) component with antd transfer component

Question: antd is great component library, however I am facing some challenges while integrating the react-window with Transfer component.
I am trying to render a huge list in the Transfer component and since the antd 3.x Transfer component lags as the items length increases so I thought of using the react-window component with the Transfer component.
In the link:- https://stackblitz.com/edit/react-ofcadv-gcds33?file=index.js
I am trying to integrate the react-window with the transfer component but unable to set up some of default behavior available in the antd transfer component.
To view the default behavior of the antd component we can check by setting perfMode to false in the code base.
Some of the basic things like selectAll etc. doesn't work when using FixedSizeList component with the Transfer component.
Any help which will point me in the right direction is appreciated.
Steps to reproduce:-

Visit https://stackblitz.com/edit/react-ofcadv-gcds33?file=index.js
To enable virtualization goto line number 126 of index.js and set perfMode to true.
Select some elements and click on the right arrow.
selected elements shifts to the right bucket but doesn't get unchecked.
Answer: it seems like you are missing to pass selectedKeys.
Have a look at completely working solution below:
const { Transfer } = antd;
const ReactDragListView = window["react-drag-listview"];

const dataSource = [];
for (let i = 0; i < 20; i++) {
  dataSource.push({
    key: i.toString(),
    title: `Item ${i + 1}`
  });
}

const targetKeys = dataSource
  .filter(item => +item.key % 3 > 1)
  .map(item => item.key);

class TransferDemo extends React.Component {
  state = {
    targetKeys,
    selectedKeys: []
  };

  handleChange = nextTargetKeys => {
    this.setState({ targetKeys: nextTargetKeys });
  };

  handleSelectChange = (sourceSelectedKeys, targetSelectedKeys) => {
    this.setState({
      selectedKeys: [...sourceSelectedKeys, ...targetSelectedKeys]
    });
  };

  getDragProps = () => ({
    onDragEnd: (fromIndex, toIndex) => {
      const targetKeys = [...this.state.targetKeys];
      const item = targetKeys.splice(fromIndex, 1)[0];
      targetKeys.splice(toIndex, 0, item);

      this.handleChange(targetKeys);
    },
    nodeSelector: ".ant-transfer-list:last-child .ant-transfer-list-content > div"
  });

  render() {
    const { targetKeys, selectedKeys } = this.state;

    return (

        <ReactDragListView {...this.getDragProps()}>
          <Transfer
            dataSource={dataSource}
            titles={["Source", "Target"]}
            targetKeys={targetKeys}
            selectedKeys={selectedKeys}
            onChange={this.handleChange}
            onSelectChange={this.handleSelectChange}
            render={item => item.title}
            listStyle={{ height: 300 }}
          />
        </ReactDragListView>

    );
  }
}

ReactDOM.render(
  <TransferDemo />,
  document.getElementById('root')
);

Referring a link as well for you.
Good luck!
Comment: Thank-you @James. The pen looks very clean.  Is it possible to add react-window so that it can work with huge data-sets something like 30k items in the source section.
Comment: Yeah, definitely. Actually it's written with react. In terms of huge data-sets, I have no idea, because it's provided from antd. Maybe there might be heavy loading in case. Accept my answer if it works fine on your situation, then it's wonderful. Thanks.


Mutual information between a time series and its delayed form

Question: According to Thomas Schreiber in the paper "Measuring Information Transfer", we need to calculate the Mutual Information between time series $t$ and itself with a delay of $k$ and let's call the delayed form $t^k$.
What I understand is that if $t=\{t_1, t_2, ..., t_n\}$, $t^k$ will be $\{t_{k+1},t_{k+2}, ..., t_{n}\}$. Therefore, their lengths are not the same. How can I compute the mutual information between these two time series? Do I have to pre-zero-pad $t^k$ or something like that?
Any help or reference in appreciated.
Answer: Using your notation, if you have a time series of length $n$ and you want to compute the mutual information between this time series and the time series delayed by $k$ positions, you should match $n-k$ values:
$$t_1 , t_{k+1}\\
t_2 , t_{k+2}\\
\vdots \\
t_{n-k} , t_{n}
$$
Mutual information between delayed time series is often computed to infer biological networks (See here and here).
So you will compute mutual information on $n-k$ data points rather than $n$. Be careful though when comparing mutual information estimated on a different number of data points: its estimates might be inflated if $n$ is small (See here).


Generating a new independent variable from other independent variables in the dataset

Question: I have a database of characteristics of a signal. The characteristics are a bunch of indicators (kurtosis,skewness,etc). The dependent variable is fault. The fault variable has as a value 1 if the signal corresponds to a faulty machine and 0 if it's not a faulty machine.
I would like to know if there is a method or an algorithm capable of generating indicators (new independent variable) from the ones in the database(e.g :the multiplication of 2 of them or division ) that would correlate better with the dependent variable and would consequently a better indicator of the existence of the fault.
Thank you !
NB : If technical terms are not well used or more details are needed, don't hesitate to ask me as I am new to the field.
Answer: You want to look at variable interactions. When building your model, consider something more of the form $y = (x_1 + x_2 + \dots +x_n)^2$, which will give you the pairwise interaction terms (higher exponents will reveal interactions between more variables). You can then see if these have low p-values, etc.
Also, since you say you're not up on the technical lingo, what you're trying to build is a binary classification model. You'll want to look into a linear regression linked to a logistic function.


Jquery, checking if a value exists in array or not

Question: I believe this question will be fairly easy for the ones who played around with java script / jquery.
var arr = new Array();

$.map(arr, function() {
 if (this.id == productID) {
   this.price = productPrice;
 }else {
  arr.push({id: productID, price: productPrice})
 }
}

I guess the code above explains what I want in really simple way. I would imagine this $.map would work like this but unfortunately I couldn't get results with this.
What is the most simple and elegant way to do this? Do I truly go through all array just to find if a key's value is there or not?
Does Jquery has something like isset($array['key'])?
EDIT
I tried to use inArray but it keeps adding object to array even if there is a match.
if ( $.inArray(productID, arr) > -1) {
   var number = $.inArray(productID, arr);
   orderInfo[number].price = parseFloat(productPrice);
}else {
   orderInfo.push({id:productID, price:parseFloat(productPrice)});
}

Comment: `$.inArray()` does not work most times. It's best to use `jQuery.inArray()`
Answer: http://api.jquery.com/jQuery.inArray/
if ($.inArray('example', myArray) != -1)
{
  // found it
}

Comment: Actually `$.inArray` performs a === instead of ==. So if you do `$.inArray( "4", [1,2,3,4])` you will get -1
Comment: Too bad community up-voting couldn't five years later result in something being marked as the right answer. :)
Comment: They should be marking the correct answers themselves by looking at the up votes after x amount of time
Answer: If you want to do it using .map() or just want to know how it works you can do it like this:
var added=false;
$.map(arr, function(elementOfArray, indexInArray) {
 if (elementOfArray.id == productID) {
   elementOfArray.price = productPrice;
   added = true;
 }
}
if (!added) {
  arr.push({id: productID, price: productPrice})
}

The function handles each element separately. The .inArray() proposed in other answers is probably the more efficient way to do it.
Comment: Just 1 extra info; `added = true` must be inside of the condition.
Answer: jQuery has the inArray function:
http://api.jquery.com/jQuery.inArray/
Comment: I tried to use inArray but it seems I'm doing wrong at some point. It keeps adding data.
Comment: @Revenant, [**Here**](http://stackoverflow.com/a/7881008/75500)'s an example.
Answer:     if ($.inArray('yourElement', yourArray) > -1)
    {
        //yourElement in yourArray
        //code here

    }

Reference: Jquery Array
The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.
Comment: This is what i am looking for, Thanks a lot for coool solution
Answer: Try jQuery.inArray()
Here is a jsfiddle link using the same code : http://jsfiddle.net/yrshaikh/SUKn2/
The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0
Example Code :

"John" found at

4 found at

"Karl" not found, so

         "Pete" is in the array, but not at or after index 2, so

Output:

"John" found at 3
4 found at 0
"Karl" not found, so -1
"Pete" is in the array, but not at or after index 2, so -1
Comment: This answer should be the accepted one. For those in the present future, use `jQuery.inArray()` instead of `$.inArray()`


How to place a custom javascript link/button in each row of a Views table

Question: I would like to place a link or button in each row of a Views table, and have custom javascript code executed, with field content taken from that particular row as input. The Javascript code already works fine outside of a Views table. How can I add such a custom Javascript link/button? Is this possible ?
Comment: Are u using content or fields in your view?
Comment: I am using fields from Content Types I created.
Answer: You can use a Global Text field to create the link, and, since Views wraps everything in all sorts of divs, use jQuery to grab any of the other fields there for your js
Comment: Could you give a hint how to use jQuery for that? Sorry, I am still on the learning curve. A short pointer will do..
Comment: I thought you said your js worked already?  Without knowing what you are trying to do exactly there is no easy hint.  But jQuery allows you to easily find things like $(this) and $(this).parent() or $(this).parent().find( ... ) to traverse the DOM to grab any information out of the document you need or want.
Comment: My js works.. but it doesnt use jQuery.. I will sit down and read more before asking anything else.
Answer: If your view is setup to show specific fields and not content:

Go in advanced > theming information.
Decide after or before which field your javascript should be.
Create a template file with the last suggestion name for that field in yourtheme/templates
In theming information, click on that field. Copy the whole code. (this is the base code for the template you just created.)
Open your template file, write something outside of php tags and save it.
Go in configuration > development > performance and clear all caches.
If the text you typed in your template shows in your view page. It worked. Simply paste your javascript instead.

You just learned how to modify views field templates! Hope that helped!
Comment: Then I **know** that the absove answer will resolve your problem :) I can give you more assistance if needed.
Comment: In your view page interface, to the right, click on "Advanced". "Theme: Information" is at the bottom of the list. You can also access it with this url : `example.com/admin/structure/views/nojs/display/[my_view]/[type]/analyze-theme` where my_view is the name of the view and type is the display type (page, block, etc.)
Comment: It's my pleasure to help you, I don't mind the questions :). You should be able to view all data from the fetched row in the `$row` object. Try `print_r($row);`. For instance, you can access the node title with `print $row->node_title;` and the nid with `print $row->nid;`.
Comment: Thanks. I have never themed before, but will try this. But I am also keen to know whether there is some way to do this with a custom field, for example.
Comment: Add a new field, click on it and look inside **Rewrite results** or **Style settings**. I could be wrong.
Comment: Rewrite results strips out any javascript code.
Comment: I am using the default theme "Garland". So do I put my template file into themes/garland/templates ? .. and I am not sure I got how to name my template file.. sorry.
Comment: ha. I did pretty much what i said just now. there is indeed a new word next to my field. nice. i will paste my javascript now.
Comment: Just one more question. The javascript works.. and its cool. But how can I access the node variables of that row ? I need to get the information contained as a text field from this content type. is theere a way? Sorry, and this is the last question.
Comment: it works. excellent.


Twisted and libtorrent - do I need to worry about blocking?

Question: I am looking into building a multi-protocol application using twisted. One of those protocols is bittorrent. Since libtorrent is a fairly complete implementation and its python bindings seems to be a good choice.
Now the question is:

When using libtorrent with twisted, do I need to worry about blocking?
Does the libtorrent networking layer (using boost.asio, a async networking loop) interfere with twisted epoll in any way?
Should I perhaps run the libtorrent session in a thread or target a multi-process application design?
Answer: I may be able to provide answers to some of those questions.
all of libtorrents logic, including networking and disk I/O is done in separate threads. So, over all, the concern of "blocking" is not that great. Assuming you mean libtorrent functions not returning immediately.
Some operations are guaranteed to return immediately, functions that don't return any state or information. However, functions that do return something, must synchronize with the libtorrent main thread, and if it is under heavy load (especially when built in debug mode with invariant checks and no optimization) this synchronization may be noticeable, especially when making many of them, and often.
There are ways to use libtorrent that are more asynchronous in nature, and there is an ongoing effort in minimizing the need for using functions that synchronize. For example, instead of querying the status of all torrents individually, one can subscribe to torrent status updates. Asynchronous notifications are returned via pop_alerts().
Whether it would interfere with twisted's epoll; I can't say for sure, but it doesn't seem very likely.
I don't think there's much need to interact with libtorrent via another layer of threads, since all of the work is already done in separate threads.


flutter test from sdk is forbidden

Question: I downloaded project from github and tried to run the project but it requires Get Dependencies and when I press Pub Get to for dependencies I receive the following error:
Because every version of flutter_test from sdk depends on path 1.7.0 and fstore depends on
path 1.6.4, flutter_test from sdk is forbidden.
So, because fstore depends on flutter_test any from sdk, version solving failed.
pub get failed (1; So, because fstore depends on flutter_test any from sdk, version solving
failed.)
Here is pubsbec.yaml file:
name: fstore
description: Mobile commerce app by Flutter
version: 1.6.5+33

environment:
sdk: ">=2.2.2 <3.0.0"

dependencies:
  logs:
    git: https://github.com/pq/logs
  flutter:
    sdk: flutter
  http: 0.12.0+4
  html_unescape: 1.0.1+3
  provider: 4.0.4
  after_layout: 1.0.7+2
  font_awesome_flutter: 8.7.0
  path: 1.6.4
  vector_math: 2.0.8
  carousel_pro: 1.0.0
  flutter_widget_from_html: 0.3.2+1
  configurable_expansion_tile: 1.0.0
  timeago: 2.0.26
  share: 0.6.3+6
  validate: 1.7.0
  country_pickers: 1.2.0
  shared_preferences: 0.5.6+3
  firebase_messaging: 6.0.12
  firebase_analytics: 5.0.11
  transparent_image: 1.0.0
  pull_to_refresh: 1.5.8
  localstorage: 3.0.1+4
  notification_permissions: 0.4.4
  flare_splash_screen: 3.0.1
  rate_my_app: 0.6.0+2
  page_indicator: 0.3.0
  extended_image: 0.7.1
  intro_slider: 2.2.9
  url_launcher: 5.4.2
  firebase_core: 0.4.4 # keep these version as there is new issue
  firebase_auth: 0.15.3 # with the latest firebase https://github.com/FirebaseExtended/flutterfire/issues/2084
  flutter_webview_plugin: 0.3.10+1
  connectivity: 0.4.8+2
  random_string: 2.0.1
  google_maps_flutter: 0.5.24+1
  place_picker: 0.9.11
  cached_network_image: 2.0.0
  image_picker: 0.6.3+4
  uuid: 2.0.4
  uni_links: 0.2.0
  flutter_staggered_grid_view: 0.3.0
  device_apps: 1.0.9
  auto_size_text: 2.1.0
  flutter_swiper: 1.1.6
  flutter_widgets: 0.1.12
  video_player: 0.10.8+1
  flutter_spinkit: 4.1.2
  percent_indicator: 2.1.1+1
  animated_text_kit: 2.0.0
  wave: 0.0.8
  http_auth: 0.2.9
  firebase_admob: 0.9.1
  facebook_audience_network: 0.5.0
  pin_code_fields: 2.4.0
  flutter_facebook_login: 3.0.0
  webview_flutter: 0.3.19+9
  rubber: 0.4.0
  flutter_localizations:
    sdk: flutter
  custom_splash: 0.0.2
  apple_sign_in: 0.1.0
  google_sign_in: 4.1.4
  google_fonts: 0.3.10
  flutter_statusbarcolor: 0.2.3
  app_settings: 3.0.1
  razorpay_flutter: 1.1.2
  animated_splash: 1.0.0
  firebase_database: 3.1.3
  event_bus: 1.1.1
  country_code_picker: 1.3.6
  flutter_typeahead: 1.8.0
  flash: 1.2.3

dev_dependencies:
  flutter_launcher_icons: 0.7.4
  flutter_test:
    sdk: flutter
  pedantic: 1.8.0+1 # Analysis

I tried already flutter upgrade but it did not work, is there any solution for this problem because
Comment: Remove version from "path: 1.6.4" -> "path:" and run flutter pub get
Comment: rate_my_app version is incompatible with something... https://github.com/Skyost/RateMyApp/issues/44 according to this issue, might need to downgrade firebase.
Comment: I receive this error now : Compiler message: ../../../Developer/flutter/.pub-cache/hosted/pub.dartlang.org/rate_my_app-0.6.0+2/lib/src/dialogs.dart:272:17: Error: No named parameter with the name 'onRatingChanged'. onRatingChanged: (rating) { ^^^^^^^^^^^^^^^ ../../../Developer/flutter/.pub-cache/hosted/pub.dartlang.org/smooth_star_rating-
Comment: Maybe try and downgrade your flutter version
Comment: Nuts you are right I think I need to downgrade flutter version
Answer: I have found the solution to this problem, you can use both versions of the path dependency through override_dependency, which will satisfy the requirnments.
Try Following solution:
dependencies:
  flutter:
    sdk: flutter
  dio: ^3.0.9
  hive_flutter: ^0.3.0+2
  hive: ^1.4.1+1
  path: ^1.7.0

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.3

dependency_overrides:
  path: ^1.6.4

dev_dependencies:
  flutter_test:
    sdk: flutter
  hive_generator: ^0.7.0+2
  build_runner: ^1.10.0

Answer: You can also just simply replace 1.7.0 with 1.6.4 as the error says.

flutter test from sdk is forbidden


PowerShell, Cannot read data file

Question: I have a PowerShell script that reads a register.psd1 file with contents as below.
@{
    # Building Zig compiler
    zig = @{
        name = "zig"
        path = ./python/buildzig.py
        language = "Python"
        os = "all"
    }

    # Building Windows Terminal for Windows 10.
    windowsterminal = @{
        name = "WindowsTerminal"
        path = ./powershell/msterminal.ps1
        language = "Python"
        os = "windows"
    }
}

I read the file using the following command.
Import-PowerShellDataFile -Path register.psd1

After running the script I get the following error message.
Import-PowerShellDataFile : Cannot generate a PowerShell object for a ScriptBlock evaluating dynamic expressions.

What am I doing wrong and what is the possible solution?
Comment: Enclose the paths in double quotes. `"./python/buildzig.py"`
Answer: *.psd1 files contain PowerShell hashtable literals and therefore require the same syntax as when defining such literals in code:
Therefore, if you want to create an entry with key path that contains the string literal ./python/buildzig.py (or ./powershell/msterminal.ps1), you must quote it - either form is OK here:

path = '.\powershell\msterminal.ps1'
path = ".\powershell\msterminal.ps1"

However, given that in the context of a *.psd1 file you're virtually limited to literal values, use of '...' (single quotes) makes more sense (see about_Quoting_Rules).

As for what you tried:
A hashtable entry such as  path = ./python/buildzig.py attempts to create an entry with key path and the value that is the result of executing file ./python/buildzig.py, because - in the absence of quoting - the token is interpreted as a command (see about_Parsing to learn about how PowerShell parses commands and expressions).
The - unfortunately vague - error message you saw (Cannot generate a PowerShell object for a ScriptBlock evaluating dynamic expressions.), stems from the fact that for security reasons, executing commands isn't permitted in *.psd1 files, which are (mostly[1]) limited to defining literal values.

[1] You can use the following "variables", which in effect are constants: $true, $false, $null. Additionally, depending on the purpose of the *.psd1 file, a select few additional automatic variables are permitted: $PSCulture and $PSUICulture, except in files to be read by Import-PowerShellDataFile, and, additionally, $PSScriptRoot, $PSEdition, and $EnabledExperimentalFeatures in module manifests - see about_Language_Modes.
Answer: I have just added ' ' for the path parameters as following after that the error was gone. hope this is the output you wanted.
path = '.\powershell\msterminal.ps1'

PowerShell, Cannot read data file


Redirecionar a partir de uma URL dentro do laravel

Question: Boa tarde, estou com um problema:
Tenho um sistema para a empresa que trabalho que é usado apenas internamente, então ele é acessado apenas através de VPN, porem vamos abrir esse sistema para clientes externos, então tenho a url:
https://sistemainterno.com.br

e o clientes:
https://sistemaclientes.com.br

O problema:
ambos os sistemas usam o mesmo backend e frontend, eu queria apenas redirecionar tudo que vem da url "https://sisteclientes.ocm.br" para "https://sistemainterno.com.br/clientes/", o sistema cliente seria apenas um aliás para proteger o caminho interno e liberar apenas as URLs com /clientes/, porem estou com duvida em como fazer isso no laravel... alguem tem alguma solução?
Obrigado desde já
Answer: Você tem as seguintes opções
OPÇÃO 1: criar uma rota Route::get('/clientes','SeuController@suaFuncao');
no seu controller criar a função que faz a chamada da view,
    public function getView() {

    ## SUAS FUNÇÕES E OBJETOS...

   $cliente = Clientes::all(); #por exemplo
   return view('seudiretorio.suaview')->with('clientes',$clientes);

}
OPÇÃO 2: configurar o APACHE para entender que ao invés de /public ele vá para /public/clientes
Exemplo: https://www.digitalocean.com/community/tutorials/como-configurar-apache-virtual-hosts-no-ubuntu-16-04-pt
OPÇÃO 3: Quando a pessoa realiza a autenticação você apontar para essa /clientes ao invés do /
No seu Controller >> Auth >> LoginController por exemplo :
$token = Users::where('email',$request->email)->select('token')->first();

##onde E-mail seria seu campo de login, se for código vc colocaria o input desse código.
Auth::attempt(['email'=>$request->email,'password'=>$request->password, 'token' => $token)

e no protected $redirectTo = '/clientes';


Função para botão adicionar e remover - para clonar formulario

Question: Boa tarde, tenho a seguinte questão:
tenho um formulário de ficha de treino, com o seguintes Campos em dropdown:
GRUPO  EXERCÍCIO SERIE REPETIÇÃO CARGA PAUSA
e gostaria de ter a opção de repetir o campo, ficando assim:
GRUPO EXERCÍCIO SERIE REPETIÇÃO CARGA PAUSA [BOTÃO ADICIONAR] [BOTÃO REMOVER]
e quando clicasse no botão, aparecesse novamente os mesmos campos, como eu poderia fazer isso?
Grata.[novata]
Comment: Podes editar a tua pergunta para conter algum código?
Answer: Você poderia fazer como está descrito abaixo. Porém terá de tratar de cuidar dos ids duplicados na hora do submit do formulário. Pode tratar no javascript para alterar o id do duplicado. Poderia me explicar o porque você quer essa duplicação? Talvez eu possa lhe dar uma solução melhor do que essa de duplicação

var newid = 1;
function adicionaForm() {
  var formulario = document.getElementById("form")
  var cln = formulario.cloneNode(true);
  cln.id = cln.id+newid;
  document.getElementById("div").append(cln);
  newid = newid+1;
}

function removerForm(){
document.getElementById("div").lastChild.remove();

}
#div form label{
  display: block;
  padding: 3px;
}

#div form input{
border-radius: 3px;
border: 1px solid #ccc;
width:100%;
}
#div form{
margin-bottom:10px;
}

  <form id="form">
    Grupo
    <input type="text">

    Exercício
    <input type="text">

    Série
    <input type="text">

    Repetição
    <input type="text">

    Carga
    <input type="text">

    Pausa
    <input type="text">

  </form>

  <button type="button" onclick="adicionaForm()" id="adicionar">Adicionar Exercício</button>
  <button type="button" onclick="removerForm()" id="adicionar">Remover Exercício</button>
Comment: preciso que duplique para que o professor possa adicionar exercicios à ficha do aluno, e caso ele queira remover o exercicio para atualizar o treino =D
Comment: Da uma olhada agora, fiz umas alterações vê se fica bom assim
Comment: Lucas, muitíssimo obrigada! me ajudou muito!!! Valew!!!
Comment: Se puder marca como resposta


Including 3rd Party Modules in Angular App

Question: I would like to include a couple of 3rd party Angular modules in my App.  Previously I have only created simple apps that I simply use ng-app to bootstrap and put my code inside the controller.
From my understanding I should have something like this in my html:

Then my JS should look something like this:
angular.module('myApp',['thirdPartyModule1','thirdPartyModule2']);

var myCtrl = function($scope, myApp, $http){

    //my stuff
};

But when I do this I get an error:
Error: Unknown provider: myAppProvider <- myApp

Answer: You don't need to inject myApp into the controller. Your controller should be defined like this:
angular.module('myApp',['thirdPartyModule1','thirdPartyModule2']);

var myCtrl = function($scope, $http){
 //my stuff
});

to make it a little more "standard":
var myApp = angular.module('myApp',['thirdPartyModule1','thirdPartyModule2']);

myApp.controller('myCtrl', function($scope, $http){
  //my stuff
});

This way you can have a reference to your app if you like.
Now to make it compatible with minifiers/beautifiers/closure compiler:
var myApp = angular.module('myApp',['thirdPartyModule1','thirdPartyModule2']);

myApp.controller('myCtrl', ['$scope','$http', function($scope, $http){
  //my stuff
}]);

That basically makes the controller argument an array, where the first members of the array are what you're going to inject. This is because a minifier will turn the arguments into random letters like function(a,b) and angular won't know what the heck you want to inject. By passing strings in the array thy will be minified like so ['$scope','$http', function(a,b)] which is fine because the first two arguments in the array tell angular what to inject.
Comment: Thanks and` it's always good to learn best practices like that.  Now when I try to access functions in a third party module like this: thirdPartyFunction.doSomething I get a "thirdPartyFunction" not defined.
Comment: You don't access them like that. Angular modules provide services, directives, filters, etc. Once they've done that, you can just use them in your app. So if `thirdPartyModule` has a `FunTimes` service, you can just inject `FunTimes` like you do `$http`. Similarly, if thirdPartyModule has a filter, you just use it... `{{something | thirdpartyfilter}}`
Comment: Wonderful...thanks...step by step I am getting my head around this.
Comment: So how would you then call functions from thirdPartyModule1 in your controller?
Comment: @dumbledad if the module included a service, yes... inject that service and call functions from it.


Routinely import LimeSurveys into custom tables

Question: Our Research company has got 3 servers (in house), 1 hosts Drupal - outward facing, 2nd hosts LimeSurvey - outward facing, 3rd is the database server (db for Drupal and LimeSurvey) - sits inside institute's firewall.
Drupal contains Participant's database, LimeSurvey hosts multiple Surveys (which are really long surveys varying from 200 - 400 questions!).
I want to import the survey responses from each survey into separate custom tables in Drupal EVERYDAY. (custom tables because don't want to create Content type which in turn creates 200 tables, 1 for each field!)
QUESTION: What is the best way to achieve this?
Work done so far:

was able to automate daily csv export from LimeSurvey and copy to    Drupal server in a private secure folder.
tried multiple Contrib modules for Drupal to import csv:

LimeSurvey Sync
was the better solution out of all other. works fine without having to automate csv export, copying, etc., except it's real time and don't really want to connect Drupal - LimeSurvey real time (want Drupal to be separate and super secure, and not connected to any other system!)
This also had some glitches with very long surveys. (random errors connecting to LimeSurvey)
Import CSV Data
Could create only 1 custom table, could not find out how to create separate custom tables for each survey
Data along with Feeds module. Could not get this working!
Created a new custom table using Data module config page. This was reflected in Feeds Imported config page. Configured to Attach to "Use standalone form" in basic settings, file uploader, csv parser, Node processor. And didn't know what to do next, how do I schedule import?
Please suggest if I am in the right way OR if there is any other better way of achieving this?
Answer: I am the author of the Drupal LimeSurvey Sync module. You definitively need that module !
About LimeSurvey Sync module :

You don't have to use the « realtime » feature. You can simply start
answering survey from your LimeSurvey site. Just create a simple rule (using the
Rules UI module) to fire LimeSurvey synchronization on Cron event on
your Drupal site in order to import.
Your Drupal site will still be secure : the LimeSurvey Sync module
provides protections from sql injection and datas are sanitized
before being imported.
About issue for very very big surveys : that can be solved by
appropriate server settings. Look at this issue on the Drupal module
issues section to get the good configuration.

Keep me In touch !


What's the proper name for these chain structured PGMs?

Question: I'm trying to find previous work that has dealt with this type of PGMs, but don't know what to call them:
a) "recurrent HMM"? $y_i$ are scalars and $x_i$ are discrete

b) "triangle HMM"? again, $y_i$ are scalars and $x_i$ are discrete
Comment: http://proceedings.mlr.press/v28/heaukulani13.pdf
This has a similar model. I don't think there is any special name. These are in the class of general dynamic bayesian networks.
Answer: These dependency graphs can represent Pairwise Markov Chains. Similar graphs can be seen in Figure 2 of this article.
In such case, you consider both (X,Y) as the Markovian process and the generalization of classical Markov chains algorithms such as Forward-Backward holds, as shown in http://www-public.imtbs-tsp.eu/~pieczyn/A29.pdf Section 3.


Are there keyboards that you can import sounds into for each key?

Question: Are there music keyboards with the possibility to import ANY sound onto each key and what are these keyboard / the function called?
Also any information regarding this would be helpful as well.
Answer: It's called Sampling.
I think the very first was the Akai, or possibly the Bel BD80, but they had no keyboard.
The Emulator was the first widely available keyboard sampler.
They cost about 5 grand at the time & were really rather limited, compared to a modern structure. You might still be able to pick up a second hand one on eBay, but they still fetch a couple of grand.
There were keyboards through the 90's & early 2k's that could do it, Yamaha's PSR 8000, 9000 & later Tyros had a limited sampling capability.
These days, no-one would dream of doing it in hardware, when any PC can do it in software.
Systems like Native Instruments' Kontakt are the kind of tool you'd use now.
Comment: Alright cool, for the keyboard to be able to communicate with the software (on a PC) which would change the key sounds, all the keyboard would need is MIDI compatibility am i correct?
Comment: yup, if you're working in software all you need is a method to get the note input. Midi or direct USB connection, either would work.
Comment: "*These days, no-one would dream of doing it in hardware, when any PC can do it in software.*" The Nord Electro line has a sample playback synth and "doing it in hardware" is so much easier to manage for a live gig. I took a software based rig to a few band practices several months ago and it was a nightmare. I sampled some of my nice analog synths into my Nord Electro 5D just this month and went to a band audition with it and it was awesome. You just turn it on and play your samples. Loading the samples does require a computer, but software sucks for performance, IMHO.
Answer: Yes
As Tetsujin wrote, it's called sampling. I wanted to add to his answer because it's not all about software these days, as he concluded.
Hardware sampling may be having a bit of a comeback. Many DJs and electronic musicians like the features of looping and sampling software like Ableton Live or Fruity Loops, but don't like working with or gigging with computers.
Two product lines that spring to my mind immediately for hardware based sample playback are the Clavia Nord Electro keyboard line and the Elektron line of hardware samplers.
Clavia just upgraded the sample playback capabilities of the Nord Electro line with the Electro 6. What it lets you do is take one or more sound files on a computer, load them into a sample management software package and determine how you want the keyboard to play the samples back (what notes play what samples, do the samples loop, scale with key pitch, etc.) and then you plug the keyboard in with a USB cable and it loads the samples into a sample bank on the keyboard. Once the sample bank is loaded, you can play the samples with the keyboard without a computer. What you can't do without a computer is record or load samples into the keyboard.
The Elektron products, including the Octatrack, Digitakt, and Rytm products, let you record right into the hardware sampler, change the start and end points of samples, playback rates, etc. All like a traditional hardware sampler. They are not keyboard products, as they are geared more towards DJs and electronic musicians, but you can connect a keyboard with MIDI for sample playback.
Akai still makes at least one hardware sampler, the MPC X.
Finally, many of the instruments that were popular in the 80s and 90s are available on the used market for very little money, including sampling keyboards and rack sampler modules. If you can put up with lower resolution and bit rates, you can get into hardware sampling for not much money.


Notation for strips in $\mathbb{R}^n$

Question: Let $L \subset \mathbb{R}^n$ be an $(n-1)$-dimensional affine subspace. Let $d >0$. Then let us consider the following "strip" of "core" $L$ and "width" $d$
$$
S := \{x \in \mathbb R^n : \text{dist}(x, L)< \frac{d}{2}\}.
$$
Are the names "strip", "core" and "width" standard in this contest? Is there any standardized notation for these kind of sets?
Comment: I've never seen those words in this context. Nor do I think there's are standard names. Define these as you have. Then you can use them in your document.
Comment: "width" is standard in the sense that everybody will always know what is meant. I haven't heard the name "core" in this context before, though...
Comment: I think core is fine. We definitely talk about the core of the Mobius band which is a strip of sorts, (but of an $(n-2)$-manifold), so the terminology isn't something that isn't used in something related. But I've never seen it used like this before. You might call it a $\frac{d}{2}$-neighbourhood of $L$.
Comment: @FlorianR Yeah, I think "width" is pretty safe, I'm more concerned about "core". I don't know if it is appropriate enough. I was also considering the word "soul", but it might sound too pretentious :D
Answer: I use B(L,d/2), the "ball" about L within d/2 of L.

Notation for strips in $\mathbb{R}^n$


Summing of Two Arrays in App Scripts (Google Sheets)

Question: I'm working with a Spreadsheet where I need to get the values of 2 ranges (in arrays) and return the sum of those.
I found code and tried to plug it in, but it seems to be just concatenating the 2 arrays instead of actually summing them up.
The data I'm pulling is from my spreadsheet. The arrays are 5 Columns and 23 rows. The arrays are of the same size.
Here is my function that grabs the values of each arrays. It will then run it through the Arrays_sum function I found and return and  update the table with the new totals.
    function updateBowl(){
      var row = mainSheet.getActiveCell().getRow();
      var tagCol = mainSheet.getRange("HP52");
      var rowNum = mainSheet.getRange("HO52");

      tagCol.setValue("N4:N" + row);
      rowNum.setValue(row);

  var humpedData = mainSheet.getRange("HL54:HP77").getValues();
  var processedTable = mainSheet.getRange("ID54:IH77");
  var currentData = processedTable.getValues();

  var newTotals = Arrays_sum(humpedData,currentData);

  var setNewTotals = processedTable.setValues(newTotals);

      Logger.log("New Totals: " + newTotals);

    }

This is a function I found that supposedly sums up each array that's plugged into it, but it is not working for me.
function Arrays_sum(array1, array2)
{
  var result = [];
  var ctr = 0;
  var x=0;

  if (array1.length === 0)
   return "array1 is empty";
  if (array2.length === 0)
   return "array2 is empty";

 while (ctr < array1.length && ctr < array2.length)
  {
    result.push(array1[ctr] + array2[ctr]);
    ctr++;
  }

 if (ctr === array1.length)
 {
    for (x = ctr; x < array2.length; x++)   {
      result.push(array2[x]);
    }
  }
  else
  {
  for (x = ctr; x < array1.length; x++)
    {
      result.push(array1[x]);
    }
  }
  return result;
}

Any help would be appreciated!
Edit 1: Pasted picture of the log.

Edit 2: In my log picture the first 1386 value is from the first cell in the FIRST array.
The second 1386 is the first value in SECOND array.
So it seems to concatenating the first row array with the second row array.
For my testing purposes the values are the same (because of lazy) but when I can figure out the array sum, the current values and incoming values will be different.
SOLVED
Coopers answer worked. I'm not sure exactly what I tweaked to get it to work but this is the final working script.
It gets 2 different arrays (of the same size) and sums the values in each cell, then pastes those values into the second array (the current totals).
function updateBowl(){
  var row = mainSheet.getActiveCell().getRow();
  var tagCol = mainSheet.getRange("HP52");
  var rowNum = mainSheet.getRange("HO52");

  tagCol.setValue("N4:N" + row);
  rowNum.setValue(row);

  var humpedData = mainSheet.getRange("HL54:HP77").getValues();
  var processedTable = mainSheet.getRange("ID54:IH77");
  var currentData = processedTable.getValues();

  var newTotals = sumarrays(humpedData,currentData);

  var setNewTotals = processedTable.setValues(newTotals);

  Logger.log("New Totals: " + newTotals);
}

function sumarrays(arr1,arr2) {
  var o=[];
  var html='[';
  arr1.forEach(function(r,i) {
    o[i]=[];
    if(i>0){html+=','};
    html+='[';
    r.forEach(function(c,j){
      if(j>0){html+=','};
      o[i][j]=arr1[i][j]+arr2[i][j];
      html+=o[i][j];
    });
    html+=']';
  });
  html+=']';
  return o;
  SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html), 'Output');
}

Comment: [How to sum elements of two multidimensional arrays?](https://stackoverflow.com/q/54287082/1595451) ,[Sum array columns and store the results in a bidimensional array](https://stackoverflow.com/q/41657820/1595451)
Comment: does it concatenate each array1 item to the equivalent array2  item?
Comment: It's a 2D array. See https://stackoverflow.com/questions/63720612/what-does-the-range-method-getvalues-return-and-setvalues-accept
Comment: @SaarDavidson I uploaded a picture of the log and explained what it's doing. :)
Answer: Try something like this:
function arraytest() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getSheetByName('Sheet1');
  const a1=sh.getRange(1,1,9,9).getValues();
  const a2=sh.getRange(1,10,9,9).getValues();
  sumarrays(a1,a2);
}

function sumarrays(arr1,arr2) {
  var o=[];
  var html='[';
  arr1.forEach(function(r,i) {
    o[i]=[];
    if(i>0){html+=','};
    html+='[';
    r.forEach(function(c,j){
      if(j>0){html+=','};
      o[i][j]=arr1[i][j]+arr2[i][j];
      html+=o[i][j];
    });
    html+=']';
  });
  html+=']';
  return o;
  SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html), 'Output');
}

Data:
1,10,19,28,37,46,55,64,73,82,91,100,109,118,127,136,145,154,163,172,181
2,11,20,29,38,47,56,65,74,83,92,101,110,119,128,137,146,155,164,173,182
3,12,21,30,39,48,57,66,75,84,93,102,111,120,129,138,147,156,165,174,183
4,13,22,31,40,49,58,67,76,85,94,103,112,121,130,139,148,157,166,175,184
5,14,23,32,41,50,59,68,77,86,95,104,113,122,131,140,149,158,167,176,185
6,15,24,33,42,51,60,69,78,87,96,105,114,123,132,141,150,159,168,177,186
7,16,25,34,43,52,61,70,79,88,97,106,115,124,133,142,151,160,169,178,187
8,17,26,35,44,53,62,71,80,89,98,107,116,125,134,143,152,161,170,179,188
9,18,27,36,45,54,63,72,81,90,99,108,117,126,135,144,153,162,171,180,189

Output:
[[83,101,119,137,155,173,191,209,227],[85,103,121,139,157,175,193,211,229],[87,105,123,141,159,177,195,213,231],[89,107,125,143,161,179,197,215,233],[91,109,127,145,163,181,199,217,235],[93,111,129,147,165,183,201,219,237],[95,113,131,149,167,185,203,221,239],[97,115,133,151,169,187,205,223,241],[99,117,135,153,171,189,207,225,243]]

You can put constraints on it depending upon how the data is collected.
Comment: Yep that's working! Only thing is, how do I put that into a return so my var newTotals equals that data and I can then use that new data to paste it to my Spreadsheet? Thanks a lot !
Comment: Maybe `processedTable.setValues(o);`
Comment: okay I tired that. when I log the return, it just says "undefined"

I had to use processedTable.setValue(o); (taking off the s, since it's an array I guess)
and when I plug it into my spreadsheet, it pastes that "undefined" text into every cell.
Comment: Trying sharing your updated code and ask another question
Comment: Okay I might do that. Thanks for the help. Definitely getting somewhere!

I changed the return from o to html and when logged, it actually returned the values, but in a string instead of an array. So I pasted that return and it set every single cell in the range to that string. haha.
Comment: It's working as intended. Post updated to reflect new working code. Thanks!
Comment: That's good. You can comment out the html and the dialog if you don't need it.
Answer: I hope this script will be an answer and a guide.
You can use this inside your spreadsheet as a normal function. Like this:
=arr_arr(A1:D5,"+",F6:K9)

The code:
/**
* Return the sum of total array one + array two
*
* @param {A1:D10} range - First range to sum.
* @param {"+ - / *"} operator - Operator to use.
* @param {E1:F10} range - Second range to sum.
* @return the sum of all the values
* @customfunction
*/
function arr_arr(range1,op,range2) {

  const one = [].concat(...range1);
  const two = [].concat(...range2);
  const sumOne = one.reduce((a, b) => a + b, 0);
  const sumTwo = two.reduce((a, b) => a + b, 0);
  let sum = 0;

  switch (op) {
    case "+":
      sum = sumOne + sumTwo;
      break;
    case "-":
      sum = sumOne - sumTwo;
      break;
    case "*":
      sum = sumOne * sumTwo;
      break;
    case "/":
      sum = sumOne / sumTwo;
      break;
  }

      return sum;

  }


Switching the Clef Positions

Question: Ok, so, basically, I wanted to play this song called Heaven's Lullaby by BigRicePiano on YouTube. The issue was that he had no tutorial. Thankfully, someone named LightPiano made a Synthesia tutorial along with the MIDI file. But, the issue is that the MIDI file, when converted to a PDF through things like Musescore and other MIDI to PDF File Converters, the clef positions are always switched up and it throws me off a lot.
I could just do it reversed, but, if possible, I would REALLY want the clef positions to be normal. There is an image showing what I am talking about in the Musescore 2 application. If someone could help me, that would be great.The clefs being switched up, this is all the way through the song too
Comment: it looks as these musescore midis and pdf are suboptimal, I think there are still other problems than the clefs: rhythm, notelength and key signs! compare this pdf version of the song:https://musescore.com/user/46224/scores/287776
Answer: In MuseScore, click 'Show MIDI import'.

You'll see that the Left Hand piano stave is above the Right Hand one.
Select it, click the down arrow, click Apply.

The RH and LH staves will now be the right way round.

Or do it in the Instruments page.
Answer: In the Musescore edit view just press "i" to open the "Instruments" dialog. Then you can rearrange the staves.
Comment: More detail in my answer.  But you got a vote!
Answer: The exchange of clefs is the smaller problem. Worse is the wrong representation of the rhythm in your version! the best way to correct bad midifiles is to play it in yourself by taking some useful information you got by this bad notation. this version is in dm but there are wrong enharmonics e.g.  Bb is enharmonic A# (as a result of the wrong key assignment), triplets are notated here as 6 eighth notes but the measure sign is given in as 3/4, while 6/8 would be correct.
You will learn much more if you correct this notation by playing it a new and better.
https://musescore.com/user/46224/scores/287776
Answer: The clefs and left hand right hand switches throughout, that's how it appears in your example.
You could try this editing fix in Musescore. Add two new staffs below the existing staves. Add a new treble and bass. Cut and paste bars from the existing jumbled staves into the appropriate new staves. After all the music is copied into the right place in the new staves delete the original staves.
Save a backup file of the original before you start. Save as you work in the edit file frequently. Might be a good idea to save an additional back up of the edit file before deleting the staves. Sometimes big edits to the whole score don't do what you want and are hard to undo, so make backup files.
Answer: Oh whow - that IS annoying.
First thing comes to mind is to save as a bmp or jpg file. Open in a paint or graphic program and just copy and paste the keys into the right position. I know it sounds kind of stupid, but it might be the quickest solution. (I use paint.net for doing similar things.)
Comment: If it's in musescore, edit with that not a 'photo-editing' program.

Switching the Clef Positions


Please explain confusing situation in 2009 UK Championship O'Sullivan vs. Higgins

Question: The situation in question is recorded in this video:

UK Championship 2009 Day 8. OSullivan — Higgins. Frame 13, weird situation

My questions are:

Starting at 1:40 in the video, what is the referee doing? They are placing a red ball on the table and the commentators suggest that he is determining whether that red can be hit from where the cue ball is — but why does he need to know that, about a ball that isn't on the table?
What happens at 5:24? The referee calls a foul, but for what? And whatever it is, did Ronnie do it intentionally to escape the situation, or was it a genuine mistake?
At 6:05, Higgins is told that he cannot request a replace because of the foul. Why is he confused about this? What do the commentators mean when they say "it's still a miss" and "if you play a foul shot, you can call a miss"? What are the players and the referee discussing?
Answer: There's a link at the bottom of this post to an online version of the rules of Snooker. These are the rules I'm working off of to answer your questions. If you're watching this, I'm guessing you understand the rules of snooker, but I'll explain some of the basics in detail for others reading this. Most terms in quotes can be found in the rules link.

At 1:40 the referee is attempting to see if the cue ball is "snookered". (Snookered means that the cue ball does not have a straight shot at any part of any "ball on" - the ball(s) the shooter can legally hit.) If the cue ball is snookered, then the incoming shooter has a "Free Ball" which basically means he can nominate any ball to aim for (not just a red ball, which is what he would normally have to target as the incoming shooter). The referee is using an already potted red ball as a visual aid to see if the shooter has a line on either of the two reds down at the bottom (that's why the added red ball is then removed after - it's just there for visuals). Because it's not a free ball (and a foul was committed b/c Ronnie didn't hit any balls), Higgins chooses to have Ronnie retake the shot.
At 5:24, Ronnie's cue touched one of the red balls on the table, which is a foul. The cue can only touch the cue ball. Whether he did it intentionally or made a mistake is hard to say, though the announcers at first seem to think he just lost concentration for a second. Later it seems he may have done it on purpose, because of your third question.
This appears to be a tricky one, but here's how I interpret it. If the referee believes that the shooter is not "to the best of his ability [endeavoring] to hit the ball on", then he calls a "miss". The incoming player may play the balls as they lie, or request they be reset and the offending shooter shoot again. However, if the shooter commits a penalty before nominating a color (which Ronnie did at 5:24), it is a "foul" and not a "miss" (also incurs 7 point penalty). So since Ronnie didn't call a ball, it's a foul. In this case, if Higgins wants him to reshoot, the red ball would NOT be replaced back where it was. The announcers say this at about 7:00 in, but also seem to say that the referee could call a miss in a situation like that. So since the referee has determined that it's a "foul" and not a "miss", the balls would not be replaced if Higgins wanted Ronnie to reshoot. I'm guessing that Higgins chooses to shoot because the moved balls would have given Ronnie a shot on the black ball. Now, the cue ball was also touching the red ball (See "Touching Ball"), which means that the incoming shooter can nominate another ball and shoot it and incur no penalty, even if that ball wouldn't normally be on. Higgins didn't have a good shot at potting any red balls, so that's why Higgins chooses to shoot for the blue ball instead. I'm assuming Ronnie hadn't shot for the blue before because he didn't want to give Higgins an open shot at the reds.

That's my best guess.
http://www.billiardworld.com/snooker.html
Comment: +1. The relevant section of the laws for the third part is in section 3: 14d (foul and a miss) http://www.worldsnooker.com/staticFiles/40/8d/0,,13165~167232,00.pdf
.As the commentator guesses, the referee knew the rules better than his color commentator.

Please explain confusing situation in 2009 UK Championship O’Sullivan vs. Higgins


If $X$ is uniformly distributed over $(a,b)$ find a random variable which is uniformly distributed over $(0,1).$

Question:
If $X$ is uniformly distributed over $(a,b)$ find a random variable which is some function of $X$ that is distributed as $U(0,1)$.

How can I find this??
Answer: Let's do it in two steps. Firstly, the random variable $$Y:=X-a$$ is uniformly distributed on $(0,b-a)$, i.e. $Y\sim U(0,b-a)$. Secondly, to get the upper bound equal to $1$ we need to divide $Y$ with $b-a$ (these are all calculations with constants, so they live the distribution unchanged). Hence, let $$U:=\frac{Y}{b-a}$$ then $U\sim U(0,1)$. To get $U$ in terms of $X$ write $$U=\frac1{b-a}Y=\frac{X-a}{b-a}$$
Comment: Yes, I am sure.
Comment: Are u sure this is the correct answer??


UNREACHABLE! => {"changed": false, "msg": "Data could not be sent to remote host

Question: I have SSH access for a particular server, but when I am trying to run the playbook for that server. I am trying to do the deployment for that server but I'm facing an issue.
fatal: [lapp999.corp.com]]: UNREACHABLE! => {"changed": false, "msg": "Data could not be sent to remote host \"lapp999.corp.com\". Make sure this host can be reached over ssh: ********************************************************************************\n
!!!WARNING!!!\n********************************************************************************\nThis system is a restricted access system. All activity on this system is\nsubject to monitoring. Information collected that is malicious, unauthorized or\nunlawful, may be provided to the relevant authorities for further action. By\ncontinuing past this point, you expressly consent to this monitoring.\n********************************************************************************\
firstname.lastname@example.com: Permission denied (publickey).\r\n", "unreachable": true}

Can someone please assist to fix this one?
Comment: The issue is `Permission denied (publickey)`.
Comment: Then check the verbose output of the connection attempt along with the logs on the server
Comment: But i have the access for that server , i am able to do ssh @GeraldSchneider
Answer: ansible-playbook -vvv  Verbosity 3 starts printing commands run, including the ssh command line. Compare this to the ssh command you claim is working interactively.
Check if IdentityFile  should be set for this host in ssh_config  and if so to which credential.
Ansible's default is to not use interactive ssh options. If you were to need a password, would need to provide that via  --ask-pass  on the  command line, or set variable ansible_password   And have the sshpass program installed, because OpenSSH really doesn't want you to automate passwords.