Unable to resolve module `../../../../src/redux` from `node_modules\react-redux\lib\connect\mapDispatchToProps.js`

Question: I am trying to add redux in my react native app but, when I start the app I got this error. I have followed this steps (Unable to resolve module `../../../../src/redux` from `node_modules/react-redux/lib/connect/mapDispatchToProps.js) but still got this error
Error
error: Error: Unable to resolve module `../../../../src/redux` from `node_modules\react-redux\lib\connect\mapDispatchToProps.js`:

None of these files exist:
  * src\redux(.native|.android.js|.native.js|.js|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx|.android.svg|.native.svg|.svg)
  * src\redux\index(.native|.android.js|.native.js|.js|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx|.android.svg|.native.svg|.svg)
    at ModuleResolver.resolveDependency (M:\Cimon\Files\Chaoh\chaohApp\node_modules\metro\src\node-haste\DependencyGraph\ModuleResolution.js:163:15)
    at ResolutionRequest.resolveDependency (M:\Cimon\Files\Chaoh\chaohApp\node_modules\metro\src\node-haste\DependencyGraph\ResolutionRequest.js:52:18)
    at DependencyGraph.resolveDependency (M:\Cimon\Files\Chaoh\chaohApp\node_modules\metro\src\node-haste\DependencyGraph.js:287:16)
    at Object.resolve (M:\Cimon\Files\Chaoh\chaohApp\node_modules\metro\src\lib\transformHelpers.js:267:42)
    at M:\Cimon\Files\Chaoh\chaohApp\node_modules\metro\src\DeltaBundler\traverseDependencies.js:434:31
    at Array.map (<anonymous>)
    at resolveDependencies (M:\Cimon\Files\Chaoh\chaohApp\node_modules\metro\src\DeltaBundler\traverseDependencies.js:431:18)
    at M:\Cimon\Files\Chaoh\chaohApp\node_modules\metro\src\DeltaBundler\traverseDependencies.js:275:33
    at Generator.next (<anonymous>)
    at asyncGeneratorStep (M:\Cimon\Files\Chaoh\chaohApp\node_modules\metro\src\DeltaBundler\traverseDependencies.js:87:24)

index.js
import {AppRegistry} from 'react-native';
import { Provider } from 'react-redux';
import { store } from "reduxCore";
import App from './src/App';
import {name as appName} from './app.json';

const ReduxApp = () => {
    <Provider store={store}>
        <App />
    </Provider>
}

AppRegistry.registerComponent(appName, () => ReduxApp);

src/App.js
import React, { Component } from 'react';
import EStyleSheet from 'react-native-extended-stylesheet';
import {PersistGate} from 'redux-persist/integration/react';

import createNavigator from './screens';
import {setStateAsynchronous} from 'utils/utils';
import {setNavigator} from 'utils/navigator';
import {COLOR_PALLETES} from 'utils/constants';

import {store, persistor} from 'reduxCore';

class App extends Component {
  constructor() {
    super();
    EStyleSheet.build({...COLOR_PALLETES});
    this.state = {
      appNavigator: null,
      isLoginSessionValid: false,
    }
  }

  checkUserAuth() {
    const {isLoginSessionValid} = this.state;
    setTimeout(async () => {
      await setStateAsynchronous(this, {
        appNavigator: createNavigator({
          initialRouteName: isLoginSessionValid
            ? 'Home'
            : 'Onboarding'
        })
      });
    }, 1);
  }

  componentDidMount() {
    this.unsubscribeStore = store.subscribe();
  }
  componentWillUnmount() {
    this.unsubscribeStore && this.unsubscribeStore();
  }

  render(){
    const AppNavigator = this.state.appNavigator;

    return (
      <PersistGate onBeforeLift={() => this.checkUserAuth()} loading={null} persistor={persistor}>
      {AppNavigator ? (
        <AppNavigator ref={navigatorRef => setNavigator('appNavigator', navigatorRef)}/>
      ) : <React.Fragment />}
      </PersistGate>
    );
  }

};

export default App;

src/appRedux/index.js
import {persistStore, persistReducer, createMigrate} from 'redux-persist';
import AsyncStorage from '@react-native-community/async-storage';
import {createStore, applyMiddleware, compose} from 'redux';
import Thunk from 'redux-thunk';

import reducers from './reducers';
import migration from './migrations';
import {packageJson} from 'utils/utils';

const persistConfig = {
  key: 'root',
  storage: AsyncStorage,
  version: packageJson().reduxPersistVersion,
  migrate: createMigrate(migration, {debug: __DEV__})
};

const persistedReducer = persistReducer(persistConfig, reducers);

const composeEnhancers = process.env.NODE_ENV !== 'production' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : compose;

export const store = createStore(persistedReducer, composeEnhancers(applyMiddleware(Thunk)));
export const persistor = persistStore(store);

package.json
{
  "name": "APPNAME",
  "version": "APPVERSION",
  "private": true,
  "reduxPersistVersion": 8,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "@fortawesome/fontawesome-svg-core": "^1.2.30",
    "@fortawesome/free-solid-svg-icons": "^5.14.0",
    "@fortawesome/react-fontawesome": "^0.1.11",
    "@fortawesome/react-native-fontawesome": "^0.2.5",
    "@react-native-community/async-storage": "^1.11.0",
    "@react-native-community/masked-view": "^0.1.10",
    "prop-types": "^15.7.2",
    "react": "16.13.1",
    "react-native": "0.63.2",
    "react-native-dash": "0.0.11",
    "react-native-divider": "^1.0.3",
    "react-native-dotenv": "^0.2.0",
    "react-native-extended-stylesheet": "^0.12.0",
    "react-native-gesture-handler": "^1.7.0",
    "react-native-localization": "^2.1.6",
    "react-native-reanimated": "^1.10.1",
    "react-native-safe-area-context": "^3.1.1",
    "react-native-screens": "^2.9.0",
    "react-native-size-matters": "^0.3.0",
    "react-native-spinkit": "^1.5.0",
    "react-native-svg": "^12.1.0",
    "react-native-svg-transformer": "^0.14.3",
    "react-navigation": "^4.4.0",
    "react-navigation-stack": "^2.8.2",
    "react-redux": "^7.2.1",
    "redux": "^4.0.5",
    "redux-persist": "^6.0.0",
    "redux-thunk": "^2.3.0"
  },
  "devDependencies": {
    "@babel/core": "^7.10.5",
    "@babel/runtime": "^7.10.5",
    "@react-native-community/eslint-config": "^2.0.0",
    "babel-jest": "^26.1.0",
    "babel-plugin-module-resolver": "^4.0.0",
    "eslint": "^7.5.0",
    "jest": "^26.1.0",
    "metro-react-native-babel-preset": "^0.61.0",
    "react-test-renderer": "16.13.1"
  },
  "jest": {
    "preset": "react-native"
  }
}

babel.config.js
module.exports = {
  presets: ['module:metro-react-native-babel-preset', 'module:react-native-dotenv'],
  plugins: [
    [
      'module-resolver',
      {
        root: ['./src'],
        alias: {
          localization: "./src/localization",
          utils: "./src/utils",
          views: "./src/views",
          components: "./src/components",
          assets: "./src/assets",
          reduxCore: './src/appRedux'
        },
      },
    ],
  ],
}

Comment: I had the same issue and after searching for about 5 hours, I found out it was my babel aliases that were interpreted inside react-redux somehow.
Others have suggested to install redux as a way to fix the issue but it didn't work out for me.
Hope it can help you find the root of this issue.
Answer: remove 'redux' from babel alias and run 'react-native start --reset-cache'
Comment: This worked for me


Splitting out my data when the length of each varies

Question: I have a string which I want to split into a dataframe. As you can see from my example and data below I want to split my current data out from a single cell into a position for each number, just using NAs where we have no value. I've tried splitting this out using a gsub but as the length varies from one to three '-' in each cell I don't get the result I am looking for. I thought using unlist(strsplit()) would be good for this but wasnt able to split the original data up correctly, again due to the differing lengths.
mydat
c("1-2 1-1", "1-2 1-1 3-3", "1-1 2-1 4-1", "1-1")

newdat
one   two   three     four    five    six
1     2      1        1       NA       NA
1     2      1        1       3        3
1     1      2        1       4        1
1     1      NA       NA      NA       NA

Comment: Does this answer your question? [rbind vectors of different length: pad with zero (or NA) instead of recycling](https://stackoverflow.com/questions/16556479/rbind-vectors-of-different-length-pad-with-zero-or-na-instead-of-recycling)
Answer: Using strsplit and adapting the `length<-`s.
> fn <- \(x) {
+   s <- strsplit(x, '-|\\s')
+   t(sapply(s, `length<-`, max(lengths(s))) )|>
+     as.data.frame() |> type.convert(as.is=TRUE)
+ }
> fn(x) |> setNames(c('one', 'two', 'three', 'four', 'five', 'six'))
  one two three four five six
1   1   2     1    1   NA  NA
2   1   2     1    1    3   3
3   1   1     2    1    4   1
4   1   1    NA   NA   NA  NA

Data:
> dput(x)
c("1-2 1-1", "1-2 1-1 3-3", "1-1 2-1 4-1", "1-1")

Answer: With tidyr::separate_wider_delim, you can set too_few = "align_start" to deal with varying lengths:
library(tidyr)
library(stringr)

mydat <- data.frame(col1 = c("1-2 1-1", "1-2 1-1 3-3", "1-1 2-1 4-1", "1-1"))
mydat |>
  separate_wider_delim(col1, delim = regex(" |-"), names = as.character(english::english(1:6)),
                       too_few = "align_start")

#   one two three four five  six
# 1   1   2     1    1 <NA> <NA>
# 2   1   2     1    1    3    3
# 3   1   1     2    1    4    1
# 4   1   1  <NA> <NA> <NA> <NA>

Answer: So, In order to do this you have to do the following steps:

Split each each string by space and then by '-'
then you have to find maximum length to the size of array
Prepare a matrix of the required size
Fill the matrix
Display the matrix by making it a dataframe.

If you follow all of the above steps your code should look something like below:
mydat <- c("1-2 1-1", "1-2 1-1 3-3", "1-1 2-1 4-1", "1-1")

# step 1
split_data <- lapply(strsplit(mydat, " "), function(x) {
  sapply(strsplit(x, "-"), function(y) y)
})

# step 2
max_length <- max(sapply(split_data, function(x) length(unlist(x))))

# step 3
aligned_data <- matrix(NA, nrow = length(mydat), ncol = max_length)

# step 4
for (i in seq_along(split_data)) {
  row_data <- unlist(split_data[[i]])
  aligned_data[i, seq_along(row_data)] <- row_data
}

# step 5
data <- as.data.frame(aligned_data)
colnames(data) <- c("one", "two", "three", "four", "five", "six")

print(data)


How to fix invoke uiautomator from command Prompt

Question: I want to run uiautomatorviewer from command Prompt.
But it gives an error:

-Djava.ext.dirs=..\lib\x86_64;..\lib is not supported.  Use
  -classpath instead.
      Error: Could not create the Java Virtual Machine.
      Error: A fatal exception has occurred. Program will exit.

Please guide.
Comment: have you set the environment variables for android home or not ?
Comment: Can you share the command you are running?
Comment: I have the same problem. Typing cmd from C:\Users\ME\AppData\Local\Android\Sdk\tools\bin , then uiautomatorviewer.bat in the command line window. My JAVA_HOME = C:\Program Files\Java\jdk-13.0.1 and JRE_HOME = C:\Program Files\Java\jre1.8.0_231 .
Answer:
Download JDK 8 version & install it
Set Environment variable as [JAVA_HOME : C:\Program Files\Java\jdk1.8.0_65]
Path = %JAVA_HOME%\bin & %JAVA_HOME%\lib
and provide uiautomatorviewer.bat command in cmd

The above scenario  will work.


JLabel scrolling text

Question: I need to make a piece of text that scrolls along the page by taking each letter and moving it from one jlabel to the next. This is my code so far. It needs a delay because its too fast but it seem to crash when the string has finished. Any help would be appreciated?.
package Lab4;

import java.awt.GridLayout;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

public class Scroll extends JFrame implements ActionListener {
final int scrollNumber = 10;
JTextField inputTextField = new JTextField(10);
JLabel[] output = new JLabel[scrollNumber];
JLabel text = new JLabel("Enter text and press Return",
        SwingConstants.CENTER);

public Scroll() {

    setLayout(new GridLayout(2, 1));
    JPanel row1 = new JPanel(new GridLayout(1, 10));

    output[0] = new JLabel();
    output[1] = new JLabel();
    output[2] = new JLabel();
    output[3] = new JLabel();
    output[4] = new JLabel();
    output[5] = new JLabel();
    output[6] = new JLabel();
    output[7] = new JLabel();
    output[8] = new JLabel();
    output[9] = new JLabel();

    row1.add(output[9]);
    row1.add(output[8]);
    row1.add(output[7]);
    row1.add(output[6]);
    row1.add(output[5]);
    row1.add(output[4]);
    row1.add(output[3]);
    row1.add(output[2]);
    row1.add(output[1]);
    row1.add(output[0]);

    add(row1);
    JPanel row2 = new JPanel(new GridLayout(1, 2));
    row2.add(text);
    row2.add(inputTextField);
    add(row2);

    inputTextField.addActionListener(this);

}

public void shift() {

    output[9].setText(output[8].getText());
    output[8].setText(output[7].getText());
    output[7].setText(output[6].getText());
    output[6].setText(output[5].getText());
    output[5].setText(output[4].getText());
    output[4].setText(output[3].getText());
    output[3].setText(output[2].getText());
    output[2].setText(output[1].getText());
    output[1].setText(output[0].getText());

}

public void run(String input) {
    int length = input.length();
    int i = 0;

    while (true) {

        if (output[0] != null) {
            output[0].setText(input.substring(i, i + 1));

        } else {
            output[0].setText("");
        }
        i = i + 1;
        System.out.println("0" + output[0].getText());
        System.out.println("1" + output[1].getText());
        System.out.println("2" + output[2].getText());
        System.out.println("3" + output[3].getText());
        System.out.println("4" + output[4].getText());
        System.out.println("5" + output[5].getText());
        System.out.println("6" + output[6].getText());
        System.out.println("7" + output[7].getText());
        System.out.println("8" + output[8].getText());
        System.out.println("9" + output[9].getText());
        shift();

    }
}

@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == inputTextField) {

        String j = inputTextField.getText();
        run("abcdef");
        System.out.println(j);
    }

}

}

Answer: So first of all. Yes your application crashes. Technically its an IndexOutOfBoundsException that you get when invoking input.substring(i, i + 1) in your run method. You increment i in an infinite loop without resitriction. And so it gets higher than your string length with the result that substring then throws that exception.
So first fix is a restriction when incrementing your index.
[...]
i = i + 1;
if(i > length - 1)
    i = 0;

Next fix should be a delay. But thats not as easy as it sounds. You should start learning how Threads work in Java because you will need to start one. Thats because you should never send your main Thread to sleep or your GUI will get unresponsible. So I will give you one simple solution and remind you to learn how Threads work.
So remove your run method and change your actionPerformed method like this:
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == inputTextField) {

        String j = inputTextField.getText();
        // run("abcdef");
        new Thread(new Runnable(){
            @Override
            public void run() {
                int length = j.length();
                int i = 0;
                while (true) {
                    if (output[0] != null) {
                        output[0].setText(j.substring(i, i + 1));
                    } else {
                        output[0].setText("");
                    }
                    i = i + 1;
                    if(i > length - 1)
                        i = 0;
                    try {
                        Thread.sleep(500); // your delay in ms
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    shift();
                }
            }
        }).start();
    }
}

Comment: Thanks for the help, but last question, how do i make it only run by once?
Comment: You will need a condition for your `while` loop so it could end when finish. Something like: `int runs = 0; while (runs++ < ((length - 1) + output.length)) { [...] }`.

JLabel scrolling text


Why does `R` `glmnet` need to run with $\lambda$ in decreasing order?

Question: In ?glmnet::glmnet documentation, it says

Do not supply a single value for lambda (for predictions after CV use predict() instead). Supply instead a decreasing sequence of lambda values. glmnet relies on its warms starts for speed, and its often faster to fit a whole path than compute a single fit.

Why? What is the "warms starts" process? and why "fit a whole path than compute a single fit"? Does it have something to do with projected gradient descent?
Comment: The lasso estimate has a closed form (in particular, is zero) when $\lambda$ is large enough. Hence, it's the best place to start this warm start procedure. The convention--even when the first estimate isn't zero--follows from this.
Answer: "Warm starts" is merely starting an optimization problem with values you suspect to be fairly close to the optimal solution. In the case of glmnet, it's pretty clear how to get warm starts; if ${\beta_{0.1}}$ is the solution you just solved for with $\lambda = 0.1$, and you want to find the solution when $\lambda = 0.09$...well $\beta_{0.1}$ seems like pretty good place to start.
It can also help to provide in descending order because $\beta_{0.1}$ should be closer to the zero vector than $\beta_{0.01}$, although I suspect the difference would be very minor to supply in ascending order.


Como tratar o retorno de arquivos(PDF) em uma AJAX call?

Question: Fiz um código que seleciona os documentos que estão em um banco FTP e ao clicar em baixar ele executa uma AJAX call para o DJANGO onde eu chamo o FTP novamente, baixo o arquivo e envio de volta para o AJAX. Porem não consigo achar como tratar o arquivo .PDF.

Ainda não descobri o por que o AJAX está tratando como error e não como sucess. Eu deveria estar definindo o dataType de forma diferente? Ou tratando a reponse no Django?
O que quero fazer é, selecionar o arquivo que o usuário deseja baixar, puxa-lo no ftp e baixar na máquina do usuário.
Segue os códigos:
AJAX:
    $.ajax({
        url:"{% url 'action_documents' %}",
        async: false,
        dataType: 'json',
        type: 'GET',
        data: {
            'documentos[]': documentos,
            'action': action,
    },
        success: function (data) {
            console.log('Sucess', data);
            result = 'S U C E S S O';
            // Tentando inserir o pdf em algum lugar para confimar que ele está -
            // chegando no Front End
            let html = ajax.decode(data.responseText).html;
            $('#main1').append(html);
            //ajax.get('pageContent').update(html);
        },
        error: function (response) {
            # o Ajax está saindo aqui
            console.log('Erro nos Documentos --> ', response);
            result = 'E R R O';
        }
    });

DJANGO:
if request.is_ajax:
    documentos = request.GET.get('documentos[]')
    # name é meramente ilustrativo
    name = documentos[1]
    ftp = logar_ftp()
    try:
        buffer = io.BytesIO()
        ftp.retrbinary('RETR ' + name, buffer.write)
        buffer.seek(0)
        # sending response
        response = HttpResponse(buffer, content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="' + name + '"'
    except IOError:
        # handle file not exist case here
        response = HttpResponseNotFound('
File not exist
')
else:
    response = HttpResponseNotFound('
Request Ajax Error
')
return response

Como eu devo efetuar a request de download na máquina do usuário?!
Answer: O Ajax, é uma maneira de obter dados de um servidor sem a necessidade de recarregar a página, porém ele espera receber do servidor um JSON com dados.
Você pode salvar o arquivo no seu servidor e mandar como resposta para o Ajax um objeto JSON com o link para fazer o download, e no success voce USA window.location = data.url.
No entanto seu servidor pode ficar muito lotado com arquivos, você pode agendar uma tarefa no seu servidor para limpar a determinada pasta e apagar os arquivos do dia anterior.
Comment: Ou então cogite a opção de fazer a request sem ser com Ajax, usando um get padrão.
Comment: Sim, mas no caso os dados estão em um FTP e não há possibilidade de colocá-los no banco pois precisaria mudar toda a estrutura do mesmo. Li em vários lugares que não se coloca regras de negócios no front end(e me deram dicas sobre isso também), então sempre uso Ajax para levar ao Django e tratar as regras lá.
Por isso estou tentando enviar o arquivo via ajax visto que sempre serão arquivos não pesados de PDF. E o que seria esse ''get padrão'' que você comentou?!
Outro detalhe, tentei utilizar via link porem iria precisar de login e senha entre outros detalhes que quero evitar...


How to add additional tabs to user profiles

Question: I'm trying to find a way to add another tab to the tabbed menu under each user's username on the user/* page.
I want to have View, Edit, and an additional link. I'm not sure where I need to be looking in the code to edit this menu and I can't find any documentation thus far. Any help would be great.
Thanks
Answer: I believe you can implement hook_menu in a custom module and use MENU_LOCAL_TASK as the type, and the path needs to start with user/
function HOOK_menu() {
  $items['user/mypage'] = array(
    'title' => t('My Tab'),
    'type' => MENU_LOCAL_TASK,
    //'page callback' => 'mymodule_mypage', //mymodule_mypage should be a function that returns HTML for the content area
    //'page arguments' => array(0, 1, 2), // 0 is arg(0), 1 is arg(1) etc...
  );
  return $items;
}

For all the array elements see this page
Comment: where would this code go?
Comment: This code goes in a custom module. Check [this page](http://drupal.org/node/361112) for a guide on how to write custom modules. In this case however you'll need the most basic module, you need only 2 files a .info and a .module file. The .module file will contain the above code, but the `HOOK_` needs to be replaced by the module's name. For example: If `mycustommodule` was your custom module name the function name would be `mycustommodule_menu()`
Comment: When you say "//mymodule_mypage should be a function that returns HTML for the content area" what do you mean?
Comment: Any function name that you put in `page callback` will be called when the path `user/mypage` is requested. You can create a new function which returns markup, or use a drupal function such as `drupal_get_form` etc.


One-sample z-test (?) and multiple comparison correction

Question: I have a basic stats question. So I am comparing a patient with a condition to the population of healthy. Due to only have 1 observation/patient, I am looking into the z-score, i.e. calculating that patient z-score based on healthy stats, to check how much it deviates to healthy central tendency and how significant it is (by converting it to p-value).
My questions:

Can this approach be called a 'one-sample z-test'? I have been reading around and most of the example I found, the 'one-sample' refers to another sample population, not 1 observation.
My follow-up question would be, is it valid to do multiple comparison correction, such as Bonferroni-Holm on top of this analysis?

I have been browsing about this but could not find any information for this specific question. Any help would be greatly appreciated!
Answer: It depends on whether you want to identify unhealthy by scores that are too large, or too small, or on either side, relative to healthy.  Assuming "too large" indicates unhealthy, and assuming you have a large database of healthy, I would suggest using the empirical upper quantile (say 0.95) of the distribution of scores for healthy people. You can then make an "unhealthy" determination if the the score exceeds this quantile. I would not suggest using $t$ or $z$ test because the distribution of scores for healthy is not normal, and because with only one observation, there is no help coming from the Central Limit Theorem.
On the other hand, if you only have the summary statistics from the healthy group, you could use, e.g., $\bar x + 1.65 s$, where $\bar x$ and $s$ are the mean and sdev from the healthy group, as an estimate of the 0.95 quantile, but just realize that it might not be a very accurate estimate, depending on the sample size and on the degree of nonnormality.
This test does not have a "name" per se as far as I know, but a similar procedure is used in financial "event study" analysis.
As far as multiple comparisons goes, I would not suggest using them at all here. Instead simply acknowledge that there will be a 5% rate (or, say 1%, if you use the 0.99 quantile) of determinations of "unhealthy" among people who are actually healthy, and proceed with the appropriate caveats. Otherwise, you run the risk of missing too many unhealthy people, because the quantile thresholds automatically increase when you use multiple comparisons.
Even without multiple comparisons, you should also acknowledge that this procedure has a risk of not flagging an unhealthy person.  If you have data on unhealthy people, you can easily estimate the probability of this outcome by using the proportion of people in the unhealthy group whose score is below the chosen quantile threshold.
Taking this further, you can determine an optimal threshold by using Bayesian decision theory.


Verify that salt.txt was located and being used by Drupal?

Question: In my settings file in Drupal 8, I am specifying a location for hash-salt to a file outside of the docroot.
Example:
$settings['hash_salt'] = file_get_contents('/salt.txt');

I don't see anything in the status report or way to verify that Drupal was able to locate this file on the webserver and it is using it. I tried setting it to a broken path and/or file that doesn't exist, I even removed the line. However I don't see any noticeable change, so, how can you tell that this setting is being respected?
Comment: You could check this with `Drupal\Core\Site\Settings::get('hash_salt')`, somewhere in code or command line `drush ev "var_dump()"`
Comment: I tried `drush ev "var_dump()" | grep "hash-salt"` and got `var_dump() expects at least 1 parameter, 0 given core.drush.inc(1168)`
Comment: I put it in an answer, there is more space.
Comment: Pretty sure that drupal dies hard and early if there is no hash salt, so that hot happening is kind of proof that it works. Try setting it to an empty string to see that "in action".
Comment: Hmm, I set it to all sorts of values that should not work. Drupal did not seem to notice.
Answer: You can check this with drush by using Settings::get('hash_salt'):
drush ev "var_dump(\Drupal\Core\Site\Settings::get('hash_salt'))"

Comment: Oh, gotcha, let me try that.
Comment: Result was `NULL`
Comment: OK, that might be because the $settings line didn't work. If you use the default settings, you see the hash?
Comment: No, if I comment the line out, I still get `NULL`. If I use 'install_profile', I get the right value. So the command works, just not this override.
Comment: put `echo file_get_contents('/salt.txt');` in settings.php and run `drush ev` without command, just to bootstrap drupal, then you should see the file content.
Comment: D'oh! Two things - I was using hash-salt vs hash_salt, and I was not ssh'd into the VM when executing. I get the right value when I am in the VM, but `NULL` when executing it from my host machine.
Comment: Note: forgot to use my alias for my local site. It works now.


Update column values with result from group values (MIN) of linked table

Question: I have two tables Table 1 (main) and Table 2,connected with T1.

I need to delete double entries in Table 1. TO do that before any
delete in T1 I must delete or update the data in T2.
The option chosen is to update T2 data to point with entries not to be
deleted in T1.

SQL Problem :
I have the following group by expresion :
SELECT min(t1.id) minid
                ,max(t1.id) maxid
                ,t1.t1_value t1valor
                ,t1.group_id grupo
                ,t1.date_begin
                ,t1.date_end
                ,count(*)
            FROM rs2qtt1 t1
            WHERE t1.t1_value LIKE '%B0%'
            GROUP BY t1.t1_value
                ,t1.group_id
                ,t1.date_begin
                ,t1.date_end
            HAVING count(*) > 1
            ORDER BY count(*) DESC
                ,t1.t1_value
                ,t1.group_id
                ,t1.date_begin

I want to do something like that avoiding PL/SQL if it's possible.
UPDATE rs2qtt2 t2
SET t2.rg_id = minid
WHERE t2.rg_id IN (
        SELECT maxid max2
        FROM (
            SELECT min(t1.id) minid
                ,max(t1.id) maxid
                ,t1.t1_value t1valor
                ,t1.group_id grupo
                ,t1.date_begin
                ,t1.date_end
                ,count(*)
            FROM rs2qtt1 t1
            WHERE t1.t1_value LIKE '%B0%'
            GROUP BY t1.t1_value
                ,t1.group_id
                ,t1.date_begin
                ,t1.date_end
            HAVING count(*) > 1
            ORDER BY count(*) DESC
                ,t1.t1_value
                ,t1.group_id
                ,t1.date_begin
            )
        );

But obviously the  minid in the set statement is not visible.
Answer: You can prepare the required values in a query with saved rowid from rs2qtt2 and then use it as source data for merge query like
merge into rs2qtt2 dst using (
    select t2.rowid row_id, t1.minid new_id
    from (
        SELECT min(t1.id) minid, max(t1.id) maxid
        FROM rs2qtt1 t1
        WHERE t1.t1_value LIKE '%B0%'
        GROUP BY t1.t1_value, t1.group_id, t1.date_begin, t1.date_end
        HAVING count(*) > 1
    ) t1 inner join rs2qtt2 t2 on (t2.rg_id = t1.maxid)
) src
on (dst.rowid = src.row_id)
when matched then update set dst.rg_id = src.new_id;

This should help to avoid ORA-38104 and should access rows for merging directly by rowid
Answer: I think this might be done using merge:
MERGE INTO rs2qtt2 t2
USING (SELECT min(t1.id) minid
                ,max(t1.id) maxid
                ,t1.t1_value t1valor
                ,t1.group_id grupo
                ,t1.date_begin
                ,t1.date_end
                ,count(*)
            FROM rs2qtt1 t1
            WHERE t1.t1_value LIKE '%B0%'
            GROUP BY t1.t1_value
                ,t1.group_id
                ,t1.date_begin
                ,t1.date_end
            HAVING count(*) > 1
            ORDER BY count(*) DESC
                ,t1.t1_value
                ,t1.group_id
                ,t1.date_begin) t1
ON (t1.maxid = t2.rg_id)
WHEN MATCHED THEN UPDATE SET t2.rg_id = t1.minid;

Comment: Are you sure that updating of the column used in `on` will work? It will likely cause `ORA-38104`
Comment: You might be right, I have no sample data to check. Would this make any difference? [how to work around ora-38104](https://blog.jooq.org/2019/01/02/how-to-work-around-ora-38104-columns-referenced-in-the-on-clause-cannot-be-updated/)


javascript parse parenthesis

Question: I need parse a string inside a parenthesis, which looks like (A, B, C), where A, B, and C are string that can contain any legal JavaScript code. For example, B might be a very long string with nested structures similar to (A, B, C). What would be the best way to parse such a string?
An example of the string to parser is invoking a function:
func( parameter 1, parameter 2, parameter 3)
where all the three parameters could be other function definitions.
Comment: Can you provide a real example?
Comment: Too bad you can't get that string delivered to you as JSON! But yes, if we could see a sample string, that would help.
Answer: One of the simplest ways to create such a parser is to write a recursive descent parser. This type of parser is relatively easy to create and is certainly easier to understand than more complex parser generators (such as "yacc" and the like).
Comment: @Paul: If you need to parse actual JavaScript source code, then building a parser that handles all cases can be quite a project in itself. If you can restrict your input to a subset of JavaScript, you may have a considerably easier time. Also, with regard to regular expressions: Regular expressions can parse [regular languages](http://en.wikipedia.org/wiki/Regular_language), which is a specific term in formal language theory. Any language (such as JavaScript) with arbitrarily deeply nested structures is *not* a regular language.
Comment: Is there any such a parser implemented in JavaScript?
Comment: @Paul: I found a few with a Google search for "javascript recursive descent". However, usually a recursive descent parser is something you just write for your particular grammar. The structure of the grammar closely mirrors the structure of the parser itself (as you can see from the examples on Wikipedia).

javascript parse parenthesis


How to execute shell script with sudo from java backend?

Question: I can't figure out how to execute a command like sudo some.sh from a java backend. The sudo is pwdless.
I tried with  exec() and with builder without any luck (see below). If i try passing exec("sudo touch text.txt"); it works.
 String[] cmdScript = new String[]{"/bin/bash", "/var/backup/dump/replication.sh"};
        Process procScript = Runtime.getRuntime().exec(cmdScript);

Any ideas what i may be doing wrong?
Thanks
Comment: I would try becoming the user your Java application runs as, then execute `sudo touch text.txt`. Wrong `sudoers` entries and different working directories (try absolute paths) are the most common pitfalls here I can think of.
Comment: Add `set -x; exec > /tmp/logfile 2>&1` as the second line in the script and then check out the trace logs and error messages in `/tmp/logfile`
Comment: tried all options. I'm passing absolute paths and also my sudo user doesn't require password. also tried to put the script in /tmp and execute from there, nothing works. logfile gets nothing filled in as well.
Answer: My guess would be:
String[] cmdScript = new String[]{"/bin/bash", "sudo /var/backup/dump/replication.sh"};

or
String[] cmdScript = new String[]{"/bin/bash", "sudo", "/var/backup/dump/replication.sh"};

Since sudo usually requires a password, you might need to pipe a password into it.
String[] cmdScript = new String[]{"/bin/bash -c", "echo 'password' | sudo -S /var/backup/dump/replication.sh"};

This is not tested, but should get you on the right track.  If not, it looks like it was solved here.
Comment: I added a reference for you to check out


Does the sign matter for proportionality?

Question: This question arose from Physics, where the force on an object attached on a spring is proportional to the displacement to the equilibrium (that is, the rest position). Also, if the displacement to the equilibrium is positive, the force will be negative, as it tries to pull the object back (i.e. if you pull a string, the force is opposite to your direction of pull).
Therefore, it can be said that:
$$F \propto -x$$
Where $F$ is the force and $x$ is the displacement from equilibrium
Is this the same as:
$$F \propto x$$
According to the relation of proportionality, it should be, but my friend says that putting the second one is not correct.
Both are equivalent right?
Comment: It depends on definitions/context. Using the definition on wikipedia, yes they are equivalent.
Answer: Mathematically they are equivalent, but physycist may want to differentiate between a force in the same direction as the displacement, and a force opposite to the displacement, as they lead to physically different behavior of the system. Thus the minus sign matters.
Answer: Yes, proportionality does not tell anything about the sign of the proportionality constant. This is probably done in physics so that the proportionality constant $k$ can be considered to be always positive. This has a physical interpretation , so it is convenient for it to be positive.


Removing Object in NSMutable Array using NSMutable Dictionary

Question: i want to remove object in Mutable array using mutable dictionary, How?
My code :
Employees *Emp7 = [[Employees alloc] init];
Emp7.Number = 7;
Emp7.Name = @"Safa'";
[EmployeesArray addObject:Emp1];
[Dictionary setValue:Emp1 forKey:Emp1.Name];

in the Deleting button (IBAction)
Employees *objEmp2 = [Dic1 objectForKey:objEmp1.Name ];
[Dic1 removeObjectForKey:@"Safa'"];

Comment: What actually you want to do?
Comment: i create NSMutableArray, which contain objects, each object has "name","Number"...etc, then i create NSMutable Dictionary, which i add all objects of MutableArray to MutableDictionary ...
then i want delete the object in the mutableArray by query object.name or obj.number , How ?
Comment: Please put the code in your question (not in a comment) and use the code formatting.
Comment: Please. edit. your question. Not. a comment. Thanks
Answer: Please be a little more clear with your question, is this what you are looking for ?
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjects:values forKeys:keys];
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"1",@"2",@"3", nil];
[array removeObject:[dict objectForKey:someKey]];

where 'values' and 'keys' are both arrays and 'somekey' is an object in the 'keys' array.
Please let me know if this helps.
Comment: i want to remove object by his " name " in the mutable array using NSDictionary < How ?
Answer: TESTED CODE : 100 % WORKS
NSMutableArray *EmployeesArray = [[NSMutableArray alloc]init];
NSMutableArray *EmployeesArrayToDelete = [[NSMutableArray alloc]init];

Employees *Emp7 = [[Employees alloc] init];
Emp7.number = @"7"; Emp7.Name = @"Safa'";
[EmployeesArray addObject:Emp7];

Employees *Emp3 = [[Employees alloc] init];
Emp3.number = @"7"; Emp3.Name = @"firstname.lastname@example.com";
[EmployeesArray addObject:Emp3];

Employees *EmployeToDelete = [[Employees alloc] init];
EmployeToDelete.number = @"7";
EmployeToDelete.Name = @"Safa'";

NSLog(@"before delete : %@",EmployeesArray);

for (Employees *eachEmployee in EmployeesArray) {
    if ([eachEmployee.Name isEqual:EmployeToDelete.Name] && [eachEmployee.number isEqual: EmployeToDelete.number]) {
        [EmployeesArrayToDelete addObject:eachEmployee];
    }
}

if ([EmployeesArrayToDelete count]>0) {
    [EmployeesArray removeObjectsInArray:EmployeesArrayToDelete];
}

NSLog(@" After delete Employeesarray : %@",EmployeesArray);


Oracle: Converting Varchar Column into Float

Question: I'm attempting to clean up a poorly designed table with approximately 12,000 rows.  The table is saving user inputted data as a varchar.  I was wondering if there was a way to convert the entire column into a float and strip an extraneous text.  The column has null values, text values, and numbers all stored as text.
| Score   |
|---------|
| 1       |
| 2       |
| 2       |
| 3       |
| 300 EOW |
| 5.5     |
| (null)  |
| N/A     |
| 200     |

I attempted to use the following command but eventually receive a ORA-01722 error.
TO_NUMBER(NVL(score,'0'),'9999D99','nls_numeric_characters=,.')

Any suggestions on how we can clean up the data?
Comment: https://www.techonthenet.com/oracle/questions/isnumeric.php
Comment: What version of Oracle?  if 12.2 the `to_number` function has a new clause on what to return if it cannot parse the value.
Answer: If you install this function listed:
    http://techonthenet.com/oracle/questions/isnumeric.php
Then, you can call is_number
CASE WHEN is_number(<EXPRESSION>) = 1 THEN TO_NUMBER(<SAME EXPRESSION>) ELSE 0 END

Referenced Function:
CREATE FUNCTION is_number (p_string IN VARCHAR2)
   RETURN INT
IS
   v_new_num NUMBER;
BEGIN
   v_new_num := TO_NUMBER(p_string);
   RETURN 1;
EXCEPTION
WHEN VALUE_ERROR THEN
   RETURN 0;
END is_number;

Comment: I think you would want to have the `ELSE 0` be `ELSE NULL`  since zero could be a valid data element, in general, but the OP's code appears to use `0` as a magic value of not a valid number.
Answer: A simple solution, without using a function, would be to use a regex to strip non-numeric characters before converting, like :
TO_NUMBER(
    NVL(REGEXP_REPLACE(score, '[^1-9.]', ''), 0),
    '9999D99',
    'nls_numeric_characters='.'
)

Explanation of the regex :
[        # any character
  ^      # other than
  1-9    # 1, 2, 3,  ..., 9
  .      # and character . (dot)
]

NB : if you have numbers on serveral places in the string, they end up concatenated together, and then converted to a number. There are other possible options, for your use case, for example to use something like REGEXP_SUBSTR(score, '[1-9.]') to capture the first number in the string.


I am using pandas for reading an excel image file which is attached below

Question: import pandas as pd

records = pd.read_excel('TerraData USERS.xlsx')

df1 = records.loc[records['PWD LAST MODIFIED DT'] == '20180528', ['USER ', 'PWD LAST MODIFIED DT', 'PROFILE', 'LAST_LOGIN DATE', 'LOGIN TIME']]

print (df1)

I am using the code above to search the entries in 2nd column of Excel file that are dates on which password was changes.

I want to search passwords changed in 2018. I have tried doing it with the script above but I got no result and no error simply says empty.
If some could help wold be very grateful.
Comment: please include your code as a part of the question. also, please provide some sample input and output.
Comment: import pandas as pd

records = pd.read_excel('TerraData USERS.xlsx')
df1 = records.loc[records['PWD LAST MODIFIED DT'] == '20180528', ['USER ', 'PWD LAST MODIFIED DT', 'PROFILE', 'LAST_LOGIN DATE', 'LOGIN TIME']]
print (df1)
Comment: I want to print all the entries of year 2018
Comment: If you got an error message you should include the message with its full traceback.
Comment: I tried your code but it did not work on the provided image. Please make sure to include everything for a [mcve].
Comment: It worked as Pawan kumar has sited it below. Thank you everyone for your support and help. :)
Comment: And sir I was not getting any error. I was getting the result "Empty Index" and no  error it was running successfully. I have cited it above if you have read my post. I have written that i got no error.
Answer: I would suggest a greater than date instead of a equals date to search passwords changed in 2018 like so..
df1 = records.loc[records['PWD LAST MODIFIED DT'] > '01/01/2018', ['USER', 'PWD LAST MODIFIED DT', 'PROFILE', 'LAST_LOGIN DATE', 'LOGIN TIME']]


How to change login validity in mysql wamp 3.1.7

Question: I recently updated my wamp to 3.1.7 version and now the GUI settings where you can change the login cookie validity in the browser is gone. Please see the image below for the screenshot.
Any idea for this?
Answer: Add this line to /config.inc.php:
$cfg['LoginCookieValidity'] = 36000;

In /setup/lib/index.lib.php
$cf->getValue('LoginCookieValidity') > 36000;

If you don't already have a .htaccess file for your phpMyAdmin site, create one, and add the following line to override the default PHP session timeout:
php_value session.gc_maxlifetime 36000

I would not recommend altering this value in your main php.ini file, as it will allow a ridiculously long session timeout for all your PHP sites.
source: http://www.sitekickr.com/blog/increase-phpmyadmin-timeout/
Also try changing the cookie time session feature at:
Goto phpMyAdmin from web browser and goto
Server >> Settings >> Features >> "Login Cookie Validity" a

https://community.webfaction.com/questions/11343/no-activity-within-1440-seconds-please-log-in-again
Comment: May I ask the complete path for these? `/config.inc.php` and `/setup/lib/index.lib.php`
Comment: Hey, The main configuration file is /etc/phpmyadmin/config.inc.php
Comment: Is that the complete path? I don't have it on my machine. I'm using windows by the way.
Comment: If for some reason the ./config.inc.php file doesn't exist, you will need to create one as per the Installation documentation.
https://docs.phpmyadmin.net/en/latest/setup.html#manually-creating-the-file
Comment: Do you know the exact path for wamp?
Comment: Hey Jonjie, Please check the installation path. Might be c:\wamp or search in local drive for wamp folder
Comment: Do you have easier way to do this? Unless it is from the official documentation.


JavaScript pop-up window with an error message in Rails

Question: I am working on my first Rails App and now I came so far, that I need to integrate JS into my Rails App - in the view. Basically I wish to show a pop-up window, if the user doesn't fill out all the fields in the registration form. As I created my app with devise, I already have my _error_messages.html.erb as follows.
<% if resource.errors.any? %>

      <%= I18n.t("errors.messages.not_saved",
                 count: resource.errors.count,
                 resource: resource.class.model_name.human.downcase)
       %>

      <% resource.errors.full_messages.each do |message| %>

<%= message %>

      <% end %>

<% end %>

Basically in the form it just lists all the errors, meaning the fileds, which were not filled out. I tried to integrate the script directly in the document, but this didnt work.

How do I do this? Thanks
Answer:
Add to your form remote: true attribute;

<%= form_for @model, remote: true do |f| %>
    your fields here
<% end %>

In your controller's action do something like this:

  def create
    @model = ::Model.new(model_params)
    if @model.save
      *your default successful code here*
    else
      respond_to do |format|
        format.js do
          render template: 'model/failed_modal.js.erb',
                 layout: false,
                 locals: { error_messages: @modal.errors } // *or your way to send error messages to view template
        end
      end
    end

Create file named failed_modal.js.erb under the views/model directory (near other your views new, create etc.)
In your new view (or where your create form is located) place modal (popup or whatever you want to display to user). Something like this:

    ×

      // errors will display here with javascript code

Add some styling to your modal (I found it here):

/* The Modal (background) */
.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  padding-top: 100px; /* Location of the box */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0, 0, 0); /* Fallback color */
  background-color: rgba(0, 0, 0, 0.4); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
  background-color: #fefefe;
  margin: auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
}

/* The Close Button */
.close {
  color: #aaaaaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: #000;
  text-decoration: none;
  cursor: pointer;
}

Add ability to hide modal (and erase current errors) by clicking on the close icon or to the area around modal:

document.addEventListener("DOMContentLoaded", function() {
  var span = document.getElementsByClassName("close")[0];
  var modal = document.getElementById("myModal");
  var modalBody = document.querySelector(".modal-body");

  span.onclick = function() {
    modal.style.display = "none";
    modalBody.innerHTML = "";
  };

  window.onclick = function(event) {
    if (event.target == modal) {
      modal.style.display = "none";
      modalBody.innerHTML = "";
    }
  };
});

And last but not least add js code you your empty failed_modal.js.erb to push errors to your modal (popup) window:

var errors = <%= error_messages.to_json.html_safe %>; //pass errors from controller action and read them in js

var errorForm = document.querySelector('#myModal'); //select our modal node;

Object.keys(errors).forEach(function(prop) {
  var modalBody = error_form.querySelector('.modal-body');
  var errElement = document.createElement('div');
  errElement.classList.add('alert');
  errElement.classList.add('alert-danger');
  errElement.innerText = prop + ':' + errors[prop][0];
  modalBody.appendChild(errElement)
}) // iterate through errors hash keys (object in js) to add them into modal body.

errorForm.style.display = "block";  // change display: none to display: block to show our modal with errors

By this time your errors will look ugly, like this:
But I am sure you will handle this and customise it as you like.
Hope this will help you.
P.S. For point 6 you can put this code into new file, name it whatever you want and place in the assets/javascripts directory. By default your application.js should have //= require_tree . line which loads all your js files in this directory. Cheers!
Comment: Thank you so much. What I did, added a function to application.js which is like this:                  function myFunction() {
  alert("Please fill out all the required fields");
}                     and then just called this function in _error_messages.html.erb. like this             <% if resource.errors.any? %>
  <%= javascript_tag "myFunction()" %>
<% end %>.             It works, but I guess, it's a very-very bad way to do this. Right?
Comment: Well the main goal is to make it work, if it works - then you are doing it fine. Later, you will improve your coding style anyway. Good luck
Comment: Last question: in which file / where do I add the code, which you described in number 6 (Add ability to hide modal (and erase current errors) by clicking on the close icon or to the area around modal: )
Comment: I added p.s section to my answer, hope it will help you


Angular/Boostrap - Navbar doesn't display properly

Question: Recently I added Bootstrap 4, jQuery and Popper to my project, but the problem is when I render my webpage it shows the navbar like this (which it goes in a component called header):

Also I added in my angular-cli.json:
"styles": [
    "../node_modules/bootstrap/dist/css/bootstrap.min.css",
    "styles.css"
],
"scripts": [
    "../node_modules/jquery/dist/jquery.min.js",
    "../node_modules/popper.js/dist/umd/popper.min.js",
    "../node_modules/bootstrap/dist/js/bootstrap.min.js"
],

HTML Code

  <button class="navbar-toggler d-lg-none" type="button" data-toggle="collapse"
          data-target="#collapsibleNavId" aria-controls="collapsibleNavId"
          aria-expanded="false" aria-label="Toggle navigation"></button>

    My App/Logo with Text

        Nav 1 (current)

        Nav 2

        Nav 3 dropdown

          Action 1
          Action 2

    <form class="form-inline float-xs-right">
      <input class="form-control" type="text" placeholder="Search">
      <button class="btn btn-outline-success" type="submit">Search</button>
    </form>

Comment: This code is nowhere near sufficient for troubleshooting. Post the entire HTML output for that page.
Comment: Same code extracted from Bootstrap docs
Comment: Are you saying you are using the code copied from Bootstrap docs and getting that result?
Comment: Yes, i think it's something related to the angular-cli.json file than the HTML itself, but i don't what.
Answer: You are missing some classes in your navbar. Take a look at the following code and the classes and components used there. If you still have questions, feel free to ask. But that code example should help you to sort out this problem.
Also, the d-lg-none class says: "hide this from the breakpoint large and above. Is that what you want? It's NOT how the toggler is designed to work. Bootstrap is designed to be mobile-first! Meaning the toggler is the default. You then use the navbar-expand-lg class which basically says: "hide the toggler and expand the navbar into horizontal from the 'lg' (=large) breakpoint onwards."
Here's my code example:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

  Navbar
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

  </button>

        Home (current)

        Link

          Dropdown

          Action
          Another action

          Something else here

        Disabled

    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
    </form>

Comment: The bootstrap snipplets for webstorm were the issue(they're all incomplete)
Comment: You were trying to hide the toggler in your code whereas the right way to do it is the other way around i.e. using the `navbar-expand-lg` class which basically says: "hide the toggler and expand the navbar from the "lg" (=large) breakpoint onwards". That's how it works.


Send array from php to js with fetch()

Question:
I have pscript.php file they have array $timeslots(). Array need a send to script.js used fetch(). How this do it? The files are in the same folder.
php:
$timeslots = array();
while ($cells = mysqli_fetch_assoc($result))
{
  array_push($timeslots, $cells['rectime']);
}

js:
async function getResponse() {
  let respons = fetch('pscript.php', {
    method: 'get',
    headers: { 'Content-Type': 'application/json' },
    //body: JSON.stringify($timeslots)
})
  let content = await respons.json();
  console.log(content);
};

getResponse();

I tried send it with this code on php file

and with it
echo json_encode($timeslots);

but html show me it
jsscript.js:7
   Uncaught (in promise) TypeError: respons.json is not a function
at getResponse (jsscript.js:7:31)
at jsscript.js:11:1

Answer:
you need to echo the $timeslots array from PHP in an appropriate format (e.g. echo json_encode($timeslots);) after your while loop finishes (so that there's some JSON content for the JS to receive), and

you forgot to await the fetch, e.g. let respons = await fetch('pscript.php', { - see examples in many places e.g. https://dmitripavlutin.com/javascript-fetch-async-await/#2-fetching-json
Comment: Presumably then your PHP script is either erroring (and showing a HTML-formatted error message), or returning more than just JSON alone. Check the raw response via the browser's Network tool
Comment: i try echo, but it same thing. I add await and html send me new err: jsscript.js:5

       Uncaught (in promise) ReferenceError: $timeslots is not defined
    at getResponse (jsscript.js:5:26)
    at jsscript.js:11:1
getResponse @ jsscript.js:5
(анонимный) @ jsscript.js:11
Comment: i think my err in body: JSON.stringify($timeslots) but idk what i should do
Comment: You don't need `body: JSON.stringify($timeslots)`..."body" is for _sending_ data to the server, not for receiving it. Clearly, `$timeslots` isn't a variable which exists in your browser/JS, it's a PHP variable on the server. You had commented that out in the code in your question, so I assumed you weren't using it. Look again at the examples in the link in my answer to see how to read the JSON data you receive from the server, and look at https://developer.mozilla.org/en-US/docs/Web/API/fetch to ensure you understand what all the options in the fetch() function are used for.
Comment: i comment that, but now html say i have syntax error Uncaught (in promise) SyntaxError: Unexpected token '<', "
"... is not valid JSON
Comment: let me show you the code again just in case
php:

$timeslots = array();
while ($cells = mysqli_fetch_assoc($result))
{
  array_push($timeslots, $cells['rectime']);
}

echo json_encode($timeslots);

js: async function getResponse() {
  let respons = await fetch('pscript.php', {
    method: 'get',
    headers: { 'Content-Type': 'application/json' },
    //body: JSON.stringify(data)
})
  let content = await respons.json();
  console.log(content);
};

getResponse();
Comment: I also attached a screenshot of the latest errors to the question
Comment: Ok. Well if that's the entire script then you _should_ be fine, but like I said there might be some kind of error or extra output. Did you do what I said and check the raw response?
Comment: P.S. You also really don't need `headers: { 'Content-Type': 'application/json' }` in your fetch, because you're not sending any data (especially not JSON data)
Comment: I don't understand what you're talking about, Idk how to check the raw response. I looked somewhere that the request was executed, but the variable is not output to the console
Comment: everything is fine, I did it! thank you very much
Comment: It's in your browser's Developer Tools. Instead of Console, look at the Network tool while you are running your code, you'll see the fetch request to pscript.php appear there. Click on it, and you can then click on the "Response" tab within it to see what PHP returned

Send array from php to js with fetch()


Find the equation of the plane that contains

Question: Find the equation of the plane that contains,
the lines: $$
\frac{x-2}{2} = \frac{y+4}{3} = \frac{2 - z}{5}
$$
and
$$\begin{align}
x &= 3 + 4t \\
y &= -4 +6t \\
z &= 5 -10t.
\end{align}
$$
I'm not exactly sure on how to tackle this problem.
Answer: The line $\frac{x-2}{2} = \frac{y+4}{3} = \frac{2-z}{5}\,$ can be written as
$$x=2+2t\,,\quad y=-4+3t \,,\quad z=2-5t \,, $$
and the line
$$x = 3 + 4t \,,y = -4 + 6t \,,z = 5 - 10t \,.$$
The two lines have the same direction, since $ v_1=(2,3,-5) $ and $ v_2 = (4, 6,-10)\,, $ where $v_1$ and $v_2$ are the direction vectors of the two lines.
One can get two points lie in the plane. Putting $t=0$ in the equations of the lines gives $p_1=(2,-4,2)$ and $p_2=(3,-4,5)\,,$ which lie in the plane.
Constructing the vector $ v_3=p_2-p_1$ gives $v_3=(1,0,3)\,.$ Now, we can find the normal to the plane by taking the cross product of $v_3$ and $v_1$ or $v_2$.
$$ n = v_3 \times v_2 \,. $$
Once that done, the equation of the plane is given by
$$ n.(X-p_1)=0 \Rightarrow n.( x-2,y-4,z-2 )=0 \,.$$
Comment: @Mike:I did not carry on the calculations, but basically this is the techniques.
Comment: So this should give me, 31 x-11 y-19 z+20 = 0?
Comment: The reason I ask is because the posted solution to this problem is 9x-11y-3z=56
Comment: @Mike: I made some corrections to the names of the vectors, make sure you have a look at that.
Comment: In doing that I get <31,11,19>
Comment: @Mike: Is this $n$?
Comment: That's what I calculated for n, however, the equation in the posted answers is 9x-11y-3z=56
Comment: @Mike: There was a small correction for the point $p_1=(2,-4,2)$.
Comment: @Mike:I made a correction $p_1=(2,-4,2)$ and based on it $v_3=(1,0,3).$ In this case you will get $n=(9,-11,-3)$.
Answer: Hints: To find a plane all you need is a point and a normal vector. You can get one point from one line.
The normal vector $n$ needs to be perpendicular on both lines, thus perpendicular on both their directions. How do you find a vector perpendicular on two given directions?
Answer: Hint: Note that the two lines are are parallel - both with direction vector $v = (2, 3, -5)$. Now for an equation of a plane you need a point and normal vector. The point should be easy to find.
For the normal vector, pick two point on each of the two lines given, say points $A$ and $B$. Then (try to draw a picture) a normal vector will be $v\times \vec{AB}$.


How does outlier impact logistic regression?

Question: I understand the outlier impact for linear regression with squared loss. @gung had a beautiful answer in this post to explain the concept of leverage and residual.
My question is How does outlier impact logistic regression? Does the same concept apply? (that we want to have a closer look at high leverage/residual points?)
For example, R, plot(glm(am~wt,mtcars,family="binomial")) is telling me Toyota Corona has high leverage and residual, should I take a closer look?

I found this post that says logistic regression is robust to outliers but did not discuss leverage and residual. Is it correct?
Comment: The second illustration is extremely confusing--in some instructive ways.  First, it does not exhibit any outlying responses.  We might understand the rightmost point to be a (somewhat) high-leverage one, but that's all.  Second, the fit is obviously wrong: this is a case of *complete separation.*  As such (a) there is no unique fit and (b) no matter what solution is chosen (among the correct ones), the regressor value for that rightmost point has *no influence on the solution whatsoever*!
Answer: Outliers may have the same essential impact on a logistic regression as they have in linear regression: The deletion-diagnostic model, fit by deleting the outlying observation, may have DF-betas greater than the full-model coefficient; this means that the sigmoid-slope of association may be of opposite direction. Separately, the inference may not agree in the two models, suggesting one commits a type II error, or the other commits a type I error.
This point underscores the problem of suggesting that, when outliers are encountered, they should summarily be deleted.
The implication for logistic regression data analysis is the same as well: if there is a single observation (or a small cluster of observations) which entirely drives the estimates and inference, they should be identified and discussed in the data analysis. DF-beta residual diagnostics is an effective numerical and graphical tool for either type of model which is easy to interpret by statisticians and non-statisticians alike.
There are some differences to discuss. In linear regression, it is very easy to visualize outliers using a scatter plot. The scaled vertical displacement from the line of best fit as well as the scaled horizontal distance from the centroid of predictor-scale X together determine the influence and leverage (outlier-ness) of an observation. For a logistic model, the mean-variance relationship means that the scaling factor for vertical displacement is a continuous function of the fitted sigmoid slope. Farther out in the tails, the mean is closer to either 0 or 1, leading to smaller variance so that seemingly small perturbations can have more substantial impacts on estimates and inference. However, whereas a Y value in linear regression may be arbitrarily large, the maximum fitted distance between a fitted and observed logistic value is bounded. Does that mean that a logistic regression is robust to outliers? Absolutely not.
Answer: Logistic regression is robust to concordant outliers, (with an extreme X value but an outcome that accords with the X value), in a way that the linear probability model is not. See http://teaching.sociology.ul.ie:3838/logitinfl for a simple illustration.
It might be better to say that such observations are outliers for the linear probability model, but not for logistic.


Modeling web traffic distribution

Question: I have to test some functionalities of a software. I need to simulate the web traffic to a server in terms of the numbers of access. What it is the most suitable function distribution for this task?
Comment: I assume "medias" means files of some sort. Can you not use real data for privacy reasons or because you have no way of getting it? If you really can't even _look_ at past real data, then you're pretty much screwed, because you won't even have something to fit a statistical model to. Something to keep in mind no matter what you do: The distribution of file sizes and of # of accesses will be very lop-sided (may look sort of like a log-normal or power-law), so make sure that your traffic-generator has _at least_ those properties (it will certainly be different from real traffic in other ways).
Comment: What do requests to your server actually look like? One somewhat easy thing to do is to just record a bunch of traffic and then replay it for a test. It often takes a lot of work to make simulated traffic that even sort-of resembles real traffic.
Comment: Are simple gets to medias. I can't use actual data.
Answer: It depends on your workload characterization as well as the system.
Take a loot at Long-lasting transient conditions in simulations with heavy-tailed workloads by Crovella and Lipsky publish at Winter Simulation Conference 1997. Specifically, read the paper, use its references, and also check who reference this paper.
A quick and dirty response would be modeling the interarrival request times as an Exponential distribution. But you should consider your system as well, which implies increase or decrease the number of workload generators (clients) in order to make them produce significant requests capable of impact on the system. You also can check Bench4Q: A QoS-Oriented E-Commerce Benchmark as a reference of how architect your testbed.
As more details of your problem you point, more accurate responses will appear. (my opinion)
Answer: Wiki Site Traffic_generation_model is a starter. It describes two models,

the more complicated 3GPP2 model, and
the easier 802.16 model

The latter is a combination of three processes:

Interrupted Poisson Process (IPP)
Interrupted Discreet Process (IDP)
Interrupted Renewal Process (IRP)

They are run in parallel to generate traffic. The main point for you is the IPP, which is used to simulate HTTP and FTP traffic. Short summary:
4 processes, each with different parameters. Each process has two states

ON state, where it sends traffic
OFF state, where it is idle

There is a switch probability given by a poisson distribution. You can model this by getting the time to the next switch from an exponential distribution.
In the ON state, messages are sent (one-directionally)

Modeling web traffic distribution


echoing timestamp appends annoying "^@"

Question: i run this command :echom system("date")<CR> in vim.
my expected output is something like this: Sat Jan 10 12:28:58 CET 2015
but it always appends an annoying ^@
so that the output is like this: Sat Jan 10 12:28:58 CET 2015^@
why?
and how can i easily avoid this?
when i run date in terminal it gives me the expected output. plus a newline of course (*1). so my guess is, that the ^@ comes from the newline, right?
i run vim 7.3 on debian (the version from the official repositories) in the terminal version, (not the gui version!) in a gnome-terminal with utf-8 encoding.

(*1): the prompt looks like this
user@host$ date
Sam Jän 10 12:28:58 CET 2015
user@host$

not like this:
user@host$ date
Sam Jän 10 12:28:58 CET 2015user@host$

Answer: The ^@ does come from the fact that date ends with a newline (\n).
You can either :

remove the trailing characters (this will only output the expected result if the command ends with a newline) :
:echom system("date")[:-2]
substitute the trailing \n (a bit more verbose) :
:echom substitute(system("date"), '\n$', '', '')

echoing timestamp appends annoying "^@"


Como determinar o último elemento de uma lista em um foreach?

Question: Dado uma lista qualquer, como saber se o foreach está no último elemento?
Existem algumas formas de se fazer isso, a que mais vejo é salvar o último elemento e verificar se o elemento atual é igual, mas dessa forma é necessário fazer a verificação em cada loop, como no exemplo abaixo:
var last = list.Last();

foreach(var element in list)
{
    if(element == last)
    {
       //is last
    }
}

Essa é a melhor forma em questão de performance?
Comment: Tem casos que o `Last()` vai acabar iterando por toda a coleção. Será que é uma boa ideia usar um `for`?
Answer: Tem alguns casos em que usar o método Last pode acabar causando uma iteração em toda a coleção, por exemplo, quando a coleção é resultado de uma consulta Linq. Isso iria fazer com que a coleção fosse iterada duas vezes. O que, com certeza, você vai querer evitar - principalmente se for trabalhar com coleções grandes.
Como você já deve saber, o foreach em si não tem nada que possa te ajudar nisso. A solução é achar alguma solução alternativa.
1. Usar um for
Essa é a primeira que eu cogitaria usar
for(int i; i < list.Count; i++)
{
    if(i == list.Count - 1)
    {
    }
}

2. Usando uma variável contadora dentro do loop
Também há a opção de "cachear" o tamanho da lista e usar uma variável contadora (não vejo vantagens nessa abordagem comparada ao uso de for)
var index = 0;
var count = list.Count; //ou Count() - você sabe
foreach (var item in list)
{
    if(++index == count)
    {
    }
}

3. Usando o método IndexOf
foreach (var item in list)
{
     if (list.IndexOf(item) == list.Count - 1)
     {
     }
}

Particularmente, eu te desencorajaria a usar esta abordagem porque o método IndexOf procura um elemento na coleção através de um loop, ou seja, a cada iteração do loop principal, outra iteração será feita no método IndexOf.
Você pode confirmar isto vendo o código fonte do método IndexOf de List<T> e o do método IndexOf da classe Array
Comment: Sim, é uma opção, mas queria saber se o `foreach()` possuía algo mais eficiente. Ahhh, tem como fazer o `Count - 1` com o `foreach()` também. xD
Comment: Pois é, eu percebi isso depois também. Acabei de editar a resposta =D
Answer: Eu não iria por este caminho.
Como disse o LINQ este é um caso onde o for pode ser uma ideia melhor, assim é só comparar o índice com o Count() ou Length da lista (possivelmente cacheado).
É possível usar a mesma técnica dentro de um foreach, mas teria que ter a variável índice para comparar com o total de itens (menos 1 para indicar o número do último). Se é para ter esta variável, porque não fazer um for? Algo asim:
var count = list.Length;

foreach(var element in list) {
    if (--count > 0) {
        //is last
    }
}

Em alguns casos é possível usar alguma opção com foreach. Poderia armazenar o valor do último item e comparar com o atual. Mas tem que garantir a unicidade dos valores na lista toda. Arriscado.
O foreach é adequado quando se quer iterar sobre a lista de forma mais uniforme, em casos assim ele não é tão adequado. Mas depende de cada caso.
Se puder usar outra forma (não faz tanto sentido), achei uma solução destrinchando o que o foreach faz:
using (var enumerator = .GetEnumerator()) {
    var last = !enumerator.MoveNext();
    T current;
    while (!last) {
        current = enumerator.Current;
        last = !enumerator.MoveNext();
        if (last) {
            //is last
        }
    }
}

Não gosto muito desta solução, e ela não pode ser usada em, todos casos, mas pode usar LINQ:
elements.ForEach((element, info) => {
    if (info.IsLast) {
        //is last
    }
});

Coloquei no GitHub para referência futura.
Dá para ter outras soluções criativas, variações destas, mas no fim muda pouco, tem que fazer o que for mais adequado para o caso. Não se pode prender a uma forma, use o que for melhor no caso concreto.


If $\mathbb{E}[X] = k$ and $\text{Var}[X] = 0$, is $\Pr\left(X = k\right) = 1$?

Question: This is not homework.
Let $X$ be a random variable. If $\mathbb{E}[X] = k \in \mathbb{R}$ and $\text{Var}[X] = 0$, does it follow that $\Pr\left(X = k\right) = 1$?
Intuitively, this seems obvious, but I'm not sure how I would prove it. I know for a fact that from the assumptions, it follows that $\mathbb{E}[X^2] = k^2$. So
$$\left(\int_{\mathbb{R}}x\text{ d}F(x)\right)^2 = \int_{\mathbb{R}}x^2\text{ d}F(x)\text{.}$$
This doesn't seem to lead me anywhere. I could try
$$\text{Var}[X] = \mathbb{E}\left[\left(X - k\right)^2\right]\text{.}$$
Now since $\left(X - k\right)^2 \geq 0$, it follows that $\mathbb{E}\left[\left(X - k\right)^2\right] \geq 0$ as well.
But if I were to use equality,
$$\mathbb{E}\left[\left(X - k\right)^2\right] = 0$$
then my gut instinct is that $\left(X - k\right)^2 \equiv 0$, so that $X \equiv k$.
How would I know this? I suppose a proof by contradiction.
If, to the contrary, $X \neq k$ for all $X$, then $(X-k)^2 > 0$, and $\mathbb{E}[(X-k)^2] > 0$ for all $X$. We have a contradiction, so $X \equiv k$.
Is my proof sound -- and if so, is there perhaps a better way to prove this claim?
Comment: I believe Chebyshev's Inequality answers this question immediately.
Comment: @Stephan You could easily mix in any nondegenerate distribution with range $(-\delta,\delta)$ and apply the inequality to show that $\Pr(|X - k| \gt \delta) \le \varepsilon$ for all $\varepsilon \gt 0$ and all $\delta \gt 0$.
Comment: @user777 I tried that method originally (as you can see in my $$\int_{\mathbb{R}}x\text{ d}F(x) = \int_{\mathbb{R}}x^2\text{ d}F(x)$$
equation), but wasn't sure how to proceed.
Comment: @whuber: at least [Wikipedia's statement of Chebyshev's inequality](https://en.wikipedia.org/wiki/Chebyshev's_inequality) explicitly requires *nonzero* variance. I don't really see whether we need some kind of elementary proof for the zero variance case...
Answer: Here is a measure theoretic proof to complement the others, using only definitions. We work on a probability space $(\Omega, \mathcal F, P)$. Notice that $Y:=(X - \mathbb EX)^2 \geq 0$ and consider the integral $\mathbb EY :=\int Y(\omega) P(d\omega)$. Suppose that for some $\epsilon>0$, there  exists $A\in \mathcal F$ such that $Y>\epsilon$ on $A$ and $P(A)>0$. Then $\epsilon I_A$ approximates $Y$ from below, so by the standard definition of $\mathbb E Y$ as the supremum of integrals of simple functions approximating from below,  $$\mathbb EY\geq \int\epsilon I_AP(d\omega) = \epsilon P(A)>0,$$ which is a contradiction. Thus, $\forall \epsilon>0$, $P\left(\{\omega : Y>\epsilon \}\right) = 0$. Done.
Answer: Prove this by contradiction. By the definition of the variance and your assumptions, you have
$$ 0 =\text{Var}X = \int_\mathbb{R} (x-k)^2\,f(x)\,dx, $$
where $f$ is the probability density of $X$. Note that both $(x-k)^2$ and $f(x)$ are nonnegative.
Now, if $P(X=k)<1$, then
$$U:=\big(\mathbb{R}\setminus\{k\}\big)\cap f^{-1}\big(]0,\infty[\big) $$
has measure greater than zero, and $k\notin U$. But then
$$ \int_U (x-k)^2\,f(x)\,dx > 0,$$
(some $\epsilon$-style argument could be included here) and therefore
$$ 0 =\text{Var}X = \int_\mathbb{R} (x-k)^2\,f(x)\,dx \geq \int_U (x-k)^2\,f(x)\,dx > 0,$$
and your contradiction.
Answer: What is $X \equiv k$? Is that the same as $X = k$ a.s.?
ETA: Iirc, $X \equiv k \iff X(\omega) = k \ \forall \ \omega \in \Omega \to X=k \ \text{a.s.}$
Anyway, it is obvious that
$$(X-E[X])^2 \ge 0$$
Suppose
$$E[X-E[X])^2] = 0$$
Then
$$(X-E[X])^2 = 0 \ \text{a.s.}$$
The last step I believe involves continuity of probability...or what you did (You are right).

Theres's also Chebyshev's Inequality:
$\forall \epsilon > 0$,
$$P(|X-k| \ge \epsilon) \le \frac{0}{\epsilon^2} = 0$$
$$P(|X-k| \ge \epsilon) = 0$$
$$\to P(|X-k| < \epsilon) = 1$$
Good talking again.

Btw why is it that
$$\int_{\mathbb{R}}x\text{ d}F(x) = \int_{\mathbb{R}}x^2\text{ d}F(x)$$
?
It seems to me that $LHS = k$ while $RHS = k^2$
Comment: Yep, you're right. I've edited the post
Comment: @Clarinetist Edited mine too :P


How to remove 'add to cart' button from one cms page only?

Question: I have created a web store with custom CMS page which has custom layout too. This page will show all the products of the store.
On that CMS page all the product is displaying but
I want to remove 'add to cart' button, 'add to wishlist' link and 'add to compare' link from products
I want to remove these links from that specific CMS page only.
I tried
<remove name="" />

in Layout Update XML of that CMS page but I can't get specific names to remove and while searching I tried every possible name but no success.
Any suggestions?
Answer: If you have used a custom layout and you are displaying all products on that page then you  must have used block type to display all products in content of that page.
Something like
{{block type="catalog/product_list_random" name="product" template="catalog/product/list.phtml"}}

Simply make a new file and save it on same loction where list.phtml is saved (obviously with different name say new.phtml
Put that new.phtml instead of list.phtml
And delete whatever you don't want to display on that page from new.phtml
Comment: It works. Thanks. Let see what comes next. I have lots of magento doubts.
Answer: You only can remove whole blocks with layout updates like that, but those links and buttons are not separate blocks but get rendered within the Mage_Catalog_Block_Product_List block. You will have to replace the template of this block with your own:

copy /app/design/frontend/base/default/template/catalog/product/list.phtml to /app/design/frontend/YOUR/THEME/template/WHATEVER/catalog/product/list.phtml (use your theme directory and a directory name under template that refers to your CMS page)
edit this copy and remove the links and buttons
in the layout update handle for your CMS page, add:

XML:
<reference name="product_list">
    <action method="setTemplate" template="WHATEVER/catalog/product/list.phtml" />
</reference>

(assuming that the product list block is called product_list)
Comment: Should have been "product" as I can see from the other answer. But I also see that you specified the template right there, so the layout XML is not necessary at all.
Comment: Thanks, I tried this first but nothing changes. My theme list.phtml is stored in app\design\frontend\default\mytheme\template\catalog\product. Can't get what to write in XML in place of WHATEVER. Tried every path :(
Comment: WHATEVER = whatever you like. It should just be the same both times.
Comment: Tried that path with no success. BTW in reference tag I put content.
Comment: Oh, my mistake. Certainly will try this too.
Answer: Then, depending on what you want to remove, you can put between the "default" tags the following lines:
<remove name="cart_sidebar" />  "

<remove name="catalog.compare.sidebar" />  "

http://www.hostknox.com/tutorials/magento/remove-default-blocks/manual-removal


How to add js file in only 1 node?

Question: I made a custom js script for a little calculator. I want to use this in only 1 node (article or page) so I do not want to load it via tpl files etc because I do not need it sitewide. And also: if every custom script (that I use only in 1 node) has to be loaded sitewide I would get an immense head section after some time. Does anyone have experience with how to do this in a simple and safe way?
Thanks.
Frank
Comment: It's the same as http://drupal.stackexchange.com/questions/126/any-way-to-add-css-for-a-single-page-node only you have to use [`drupal_add_js()`](https://api.drupal.org/api/function/drupal_add_js/7) instead.
Comment: Just use hook_node_view and with condition add js using drupal_add_js.
Comment: Is there a chance that the js will be use in other part of te site?
Answer: In the template.php you will write this small piece of code:
function MYTHEME_preprocess_node($vars) {
 if (drupal_get_path_alias("node/{$vars['#node']->nid}") == 'yournid') {
    drupal_add_js(drupal_get_path('theme', 'MYTHEME') . "/script/js");
 }
}

Replace foo with values related to your need.
Answer: code for adding JS to particular path:
if ($_SERVER['REQUEST_URI'] == '/path/to/node') {
  drupal_add_js('somefile.js');
}

to attach js to node:
function my_module_node_view($node, $viewmode, $langcode) {
  $node->content['#attached']['js'][] = array('type' => 'file','data' => drupal_get_path('module', 'my_module') . '/my_script.js',);
}

Thanks!
Answer: Another option is JS Injector. Though I haven't used this module. This requires no  programming as it provides user interface to administrators.
Answer: you need to use php filter or need to create tpl file for single node to accomplish this. With php filter or tpl you need to put only this code.
<?php
  drupal_add_js('jQuery(document).ready(function () {
    jQuery("p").hide();
    jQuery("p").fadeIn("slow");
  });', 'inline');
?>

Comment: PHP filter is highly discouraged.
Comment: I understand it creates a potential security risk especially in the hands of end users or people new to Drupal or PHP.

How to add js file in only 1 node?


Proof — Weierstrass Approximation Theory for derivatives

Question: I'm working through the second edition of Abbott's Understanding Analysis, and I'm stuck on the following (6.7.11):

Assume that f has a continuous derivative on $[a, b]$. Show that there exists a polynomial $p(x)$ such that $|f(x) − p(x)| < ε$ and $|f'(x)-p'(x)| < ε$ for all $x \in [a, b]$.

I know that $|f(x) − p(x)| < ε$ follows directly from the WAT, but I'm not sure about the second part. I believe the differential limit theorem may be useful, but I can't quite incorporate it in. Thanks!
Comment: Approximate $f'$ with the WAT, then integrate the approximation.
Comment: You should approximate first $f'$.
Answer: This can be done without using integration, in a more basic way. Actually, that's probably what Abbott meant since this problem is given before even introdusing the concept of integration in his book.
Since $f'$ is continuous, $\exists$ a polynomial $q'(x)$ (which is the derivative of some other family of polynomials $q(x) + C$, where $q(x)$ represents some polynomial and $C$ is a constant) such that:
$$\vert f'(x)-q'(x)\vert \le \epsilon \iff -\epsilon\le f'(x)-q'(x)\le\epsilon $$
($\le$ sign will just make it easier later and these are equivalent anyway).
Consider $p(x)=q(x) - q(a)+ f(a)$. Notice that $p'(x)=q'(x)$.
Now let $g(x)=\epsilon (x-a)-(f(x)-p(x)).$
$$g(a)=0 \land g'(x)=\epsilon-(f'(x)-p'(x))=\epsilon-(f'(x)-q'(x))\ge0$$
$$g(a)=0\land g'(x)\ge0\implies g(x)\ge0\,\,\forall x\in [a,b]$$(since $g'(x)\ge 0\implies g $ is increasing).
$$g(x)= \epsilon (x-a)-(f(x)-p(x))\ge0\implies f(x)-p(x)\le\epsilon(x-a)\le\epsilon(m+\vert a \vert),$$
where $m=max(\vert a \vert,\vert b \vert).$
Using the same method we can show that $-\epsilon(m+\vert a \vert)\le f(x)-p(x)$.
Thus: $$-\epsilon(m+\vert a \vert)\le f(x)-p(x)\le \epsilon(m+\vert a \vert)\iff \vert f(x)-p(x) \vert \le \epsilon(m+\vert a \vert),$$ which proves our goal.
In case you're bothered with some constant multiple of $\epsilon$, we could heve let  $\vert f'(x)-q'(x)\vert \le \frac{\epsilon}{m+\vert a \vert}$, but this does not change anything since the very mathematical idea behind this all is still that we can make the difference between the function and the polynomial to be less than any given positive real number and we can thus approximate $f$ by $p$ uniformly.
Comment: @Sergio I didn't write $g'(x)=\epsilon$. You've got it right, $g'(x)=\epsilon-f'(x)+q'(x)$
Comment: @Sergio let $g(x)=-\epsilon (x-a)-(f(x)-p(x))$ . Then do everything I did(pretty much identical stuff but the the function will end up being decreasing and thus negative)
Comment: Can you please elaborate on why $g'(x)=\epsilon$? I am re writing your answer with full details and I am getting $g'(x)=\epsilon-f'(x)+q'(x)$ and I can't simplify further.
Comment: oof, apologies. I was looking at it on my phone and it was breaking the line just there.
Comment: Can you please elaborate on this inequality: $-\epsilon(m+\lvert a\rvert) \leq f(x)-p(x)$? I can only get here: $-\epsilon(m+\lvert a\rvert) \leq -(f(x)-p(x))$, and can't seem to find the reason as to why $-(f(x)-p(x)) \leq f(x)-p(x)$.
Comment: I see. Thanks a lot!
Answer: I was trying to solve this problem as well. This my attempt, which makes use of one of theorems from an earlier section in the chapter. It's more convoluted than the previous answer though.
Since $f$ is continuously differentiable on $[a,b]$, by the WAT,
$\forall \epsilon >0$ there exists a polynomial $p$ such that $\forall x \in [a, b], |f'(x) - p(x)| < \epsilon$. Thus there exists a sequence of polynomials $(p_n)$ that uniformly converges to $f'$. Since $(p_n)$ is countable, we can find a sequence of polynomials $(q_n)$ such that $q_n(a) = f(a)$ and $q_n' = p_n$ for all $n$. Thus the sequence $(q_n(a))$ trivially converges to $f(a)$.
There is an extension of the Differentiable Limit Theorem in Abbott's book (Theorem 6.3.3) that states:

Let $(f_n)$ be a sequence of differentiable functions defined on the closed interval $[a,b]$, and assume $(f'_n)$ converges uniformly to a function $g$ on $[a,b]$. If there exists a point $x_0 \in [a,b]$ for which $f_n(x_0)$ is convergent, then $(f_n)$ converges uniformly. Moreover, the limit function $f= \lim f_n$ is differentiable and satisfies $f' = g$.

The sequence $(q_n)$ satisfies the hypothesis of this theorem because $(q_n)$ converges for at least one point in $[a,b]$, and the sequence of derivatives $(q'_n)$, where $\forall n, q'_n = p_n$, is uniformly convergent. By construction $\lim p_n = f'$, and so the theorem implies $(q_n)$ uniformly converges to some $h$, where $h' = f'$. Thus $h$ and $f$ have the same derivative. Since properties of the integral can't be used (this is before the integration section in the book) , let's use  the extended/generalized Mean Value Theorem (MVT). Since $f'=h'$ and by construction $f(a)=h(a)$, the generalized MVT implies $f = h$.
Thus on $[a,b]$ , $(q_n)$ is a sequence of polynomials uniformly converging to $f$, and $(q'_n)$ uniformly converges to $f'$. So by definition of uniform convergence, $\forall \epsilon >0$, we can find some $m$ such that $\forall x\in [a,b], |q_m(x) - f(x)| < \epsilon$ and $|q'_m(x) - f(x)| < \epsilon$.


Best Development Framework for a Google-Maps-ish Web Application?

Question: I am starting a project in which I hope to create a web application with similar elements to Google Maps, such as zooming, panning, displaying tiles, etc.  The idea would be for it to have a very fluid and dynamic feel.
Some possibilities that I have encountered are:
-Flash
-Silverlight
-HTML5
-Google Web Toolkit
-Javascript/jQuery
Being proficient in C# and .net, I feel that Silverlight may be the easiest for me to work with.  I am worried however with regards to the penetration of Silverlight (this is a consumer-facing application).
Please note that I am not asking to implement Google Maps into my web application.  Rather I am attempting to create a new similar website (not mapping, but similar concepts).
Thank you very much.
Answer: There's a virtually ready-to-go solution as OpenLayers Mobile:
http://openlayers.org/dev/examples/mobile.html
Another example here, with jQuery mobile for added mobile goodness:
http://openlayers.org/dev/examples/mobile-jq.html#mappage
Displays tiles, vectors, map layers (if you need them) and so on. The tiles don't even need to be geographic, you can use it to display large images.
Its the mobile branch of OpenLayers. Oh, and it's open source. Whatever you do, don't go for Flash or Silverlight. Massive deadends.
Answer: Seeing how Google Maps itself is an HTML/JavaScript/CSS application I'd suggest going the HTML5 route. The main advantage is penetration into the mobile market, especially on Android/iPhone/iDevices which support HTML5 out of the box.
Answer: If you want to use Silverlight and C#, then you should have a look at the bing maps silverlight control. I know you said that you were not making a maps application, but depending how similar the application is, you could still use the same control. You can specify your own tile source with the map control, which means the tiles don't have to be map tiles at all.


button_click upon pressing Return in TextBox - ASP.NET

Question: I've got an ASP WebForm with 2 Textboxes and 3 Buttons and I want a specific button_click event to be fired whenever I press return whilst in a TextBox - how would I achieve this?
I tried using the TabIndex-Property, unfortunately that actually only seems to work for tabbing, not for pressing return in a TextBox.
Thanks!
Answer: Hey everyone, thanks for your answers - I just found the solution, for an aspx-page within a MasterPage I need to set
Form.DefaultButton = myButton.UniqueID;

instead of
Form.DefaultButton = myButton.ID;

which throws an error.
Thanks everyone!
Answer: Set the form's AcceptButton to the button you want pressed:
form1.AcceptButton = btnOK;

Comment: Thanks for your answer, unfortunately my ASP-Form is within a MasterPage and setting the DefaultButton on the MasterPages Form will result in getting an error on every other page.
Answer: You can set which button is to be used as the default directly in mark-up of controls, by settings the defaultbutton property value to the ID of the desired button control, try this:
<form id="form1" runat="server" defaultbutton="DefaultButtonId">

</form>

Comment: Thanks, but my aspx-file is within a MasterPage-File, setting the defaultbutton there results in an error on any other page, and programmatically setting it on my aspx-forms page_load also results in one.


Two circles covering the sides of a triangle

Question: I would like to prove or find a counterexample for the following theorem:
For any $\triangle ABC, \odot P_1, \odot P_2$ such that the three lines $AB, AC, BC$ are each contained in the union of the two circles  $P_1 \cup P_2$, the entire interior of $\triangle ABC$ is contained in $P_1 \cup P_2$.
If the theorem holds in Euclidiean geometry, does it also hold in spherical geometry and/or in isotropic Lobachevski geometry (constant negative curvature)?
Answer: Euclidean case: Let $X$ be an interior point of $\Delta ABC$ not covered by $P_1\cup P_2$. Then the line $\ell$ through $X$ orthogonal to the connection of the centers intersects $P_1\cup P_2$ in a (convex) line segment. Hence this line segment cannot contain both points where $\ell$ leaves the triangle.
Comment: Tranferring the convexity argument to the other geometries works - almost
Comment: Yes, your argument works.  And you can in fact let $\ell$ be the line defined by connecting $X$ to any point on any line of the triangle. I guess this proof also works of the spherical geometry case, but I don't see that it works for hyperbolic geometry.
Comment: In the spherical case, consider a (small) triangle with its boundary covered by two disks. Now swap the meaning of interior and exterior for the triangle ... I assume one at least to agree "interior" of circle/triangle always means "smaller part of complement", but I'm still not sure for extreme cases


Complete stripping of URL with jquery

Question: This might be pretty straight forward. But i can't figure out a stable solution.
For example:
http://site1.com/promotion
I want to strip my url so i only get the "site1"-part of the URL.
I tried with:
var url = window.location.href.split('http://')[1];
var stripOne = url.split('/')[0];
var stripTwo = stripOne.split('.')[0];

But that comes out inconsistent depending on whether or not the url contains www. or not.
UPDATED WITH CORRECT ANSWER
var url = window.location.href;
url = url.replace(/http:\/\/(www.)?/,'');
var stripOne = url.split('.')[0];

Answer: You could use a replace that will strip out 'http://' and 'www.' (if it exists). You could still fall foul of https URLs with this though -
url = url.replace(/http:\/\/(www.)?/,'');
var stripTwo = url.split('.')[0];

Demo - http://jsfiddle.net/Ux9jx/
Comment: Works like a charm!
Thank you mr. :)
Answer: I think
location.host.replace('www.','').split('.')[0]

would work?
Answer: Consider using Regular Expressions . Check this out.
Answer: window.location.host.split("\.")[0]

Complete stripping of URL with jquery


More than one D.S.?

Question: Is it possible to have more than one D.S. when charting a song? if so, how would you know which segno?
This would be a great tool for saving space in a chart.
Answer: D.S.  and D.SS. are sometimes used.  Same for codas.  Possibly useful for saving paper when a score won't have to be sight-read!  But, in these days of computer score preparation, it's little extra work to play safe and write it out if there's any chance of confusion.
I have seen parts almost as silly as this!
Comment: Awesome example! One good reason for saving space though is to get the entire song on a single sheet of paper and avoid a page turn.

More than one D.S.?


Ring structure of Hecke algebra

Question: For any locally profinite group $G$ and its open compact subgroup $K$,one can define the hecke algebra $H(G,K)$ as the space of compact supported bi $K$-invariant functions on $G$ with convolution as product operation.
Hecke algebra is very important in the representation theory of $G$, and there are several results about commutativity of such algebra. While we can always write a basis for such algebra using characteristic function for double coset, I know little about it's ring structure. For example, $H(GL_n(\Bbb Q_p),GL_n(\Bbb Z_p))$ is commutative, but I wonder what it is as a ring.
Therefore, are there some results about the ring structure? Are there some nice examples and applications of the explicit ring structure?
Comment: Do you mean like Satake's isomorphism, for p-adic reductive groups?
Comment: @aulgarrett Thank you, I haven't heard this before. The wikipedia says it is isomorphic to the grothendieck ring of complex representations of the Langlands dual group. Are there some explicit examples? I do not know how to compute the grothendieck ring of representations of Langlands dual group even for the $GL_n$ case.
Comment: What about other open compact subgroups? In general they may not be commutative, are there some classifications?
Comment: @ZhiyuZhang In general, commutativity of the Hecke algebra is equivalent to the restriction rule being multiplicity free. The affine Iwahori-Hecke algebras (which are non-commutative) arise, for instance, by taking an Iwahori subgroup instead.
Answer: As is typical in Lie theory, if you want to find an explicit calculation, it's best to start by checking if Macdonald wrote something about it. In this case, you should start by having a look at Spherical functions on a $\mathfrak{p}$-adic Chevalley group, available free here
https://projecteuclid.org/download/pdf_1/euclid.bams/1183529627
This short paper gives an explicit isomorphism (Theorem 1') from the spherical Hecke algebra $L(G,U)$ of compactly supported, continuous, $U$-bi-invariant functions from $G$ to $\mathbf{C}$ to $\mathbf{C}[P^\vee]^W$, where $G$ is a Chevalley group, $U$ is a maximal compact subgroup, $P^\vee$ is the coweight lattice, $W$ is the Weyl group, so by Bourbaki (Chapter 6 of Lie groups and Lie algebras), $\mathbf{C}[P^\vee]^W$ is a polynomial ring on $r=\mathrm{rk}(G)$ generators.
So even though it doesn't directly address your question (only since $\mathrm{GL}_n$ is reductive but not quite semisimple), you will find it easier to read than his book Symmetric functions and Hall polynomials, which contains the relevant material for the general linear group (in which case the spherical Hecke algebra is the algebra of symmetric polynomials).

Ring structure of Hecke algebra


TFS 2010: How to deploy a windows service as a part of a build?

Question: We need to be able to deploy a couple of windows services to the remote machine as a part of a build.
This is a nightly build which deploys the whole application to the TEST environment so it has to be automated somehow.
For the Web project MSDeploy can be used, as well as for the DB servers.
But what about windows services? They have to be stopped (if already installed) on the target machine, then binaries need to be copied, the service has to be registered (if not previously installed), etc, etc...
Comment: Did you ever find an answer for this?  I'm trying to do the same thing and my google-fu is failing me.
Answer: Our way to accomplish this is a litte web service running on our servers which monitors a certain directory for new files.
Our build deploys the windows services to that folder with a temp name and then renames them to a monitored name pattern ("servicename.deployservice.zip")
the deployment service will take such a file, unzip it to a temp location and performs the neccesary steps for deployment (e.g. stop old service, uninstall old service, install new service, start new service).
If you need to transport special actions, you could add a deployment code DLL or "build script" in the deployment ZIP file.
The easiest way to accomplish such deployment code with most generic is a service that simply expects an (msi or whatever) setup in the zip file and executes that. This way, you can simply add an deployment setup to your project and have very less to do in your Teambuild...
Answer: Assuming you are using VS 2010 and TFS 2010 then you could modify the build workflow to add a ExecuteProcess activity (inside an AgentScope actiivty for the target server) to run svcutil.exe specifying the name of your service.
Answer: You can use MSDeploy to do this. There is a runCommand Provider that runs the specified command on the destination computer.
<code>msdeploy.exe -verb:sync -source:runCommand="net start MyService" -dest:auto
</code>
You can read more here:
http://technet.microsoft.com/en-us/library/ee619740(WS.10).aspx
Comment: There's a lot more involved to get this working with TFS