text:
Q: multiple definition of Сделал вроде все нормально, но вот ругается
В проекте 4е файла:
main.c
/*

Программу подготовил: Буренков Игорь (М8О-206Б-17)

Вариант: АВЛ-дерево

*/
/////////////////////////////////////////////////////////

/* Системные библиотеки */
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>

/* Пользовательские библиотеки */
#include "AVL_tree_slimrg.h"
#include "settings_slimrg.h"

/* Структуры */

/* Сигнатуры функций */
unsigned short int InputFiller();              // Ввод и исполнение комманд
void PrintError(unsigned short int ErrorCode); // Вывод ошибок

/* Основной цикл */
int main(){

    // Переменные
    unsigned short int log_error; // Код ошибки

    // Считываем и выполняем команды
    log_error = InputFiller();

    // Выввод ошибки
    PrintError(log_error);

    // Пауза при закрытии
    if (debug_pauseonclose) system("pause");

    // Все ОК
    return 0;
}

// Цикл ввода и выполнения
unsigned short int InputFiller(){

    // Переменные
    char tmpchar[StringLengthPS+1];                 // Временный контейнер для символа
    char tmpword[StringLengthPS+1];   // Временный контейнер для слова (массива символов)
    unsigned long long int tmpkey;    // Временный контейнер для ключа
    unsigned char errorcode;          // Код ошибки
    unsigned int i;                   // Тикер (для циклов и т.д.)

    // Создание пустого дерева
    struct avltree* AVLTree1 = AVL_Create();

    // Пока возможно - считываем первый символ строки
    while (scanf("%s", tmpchar) >= 1){
        // Перевод в нижний регистр
        tmpchar[0] = tolower(tmpchar[0]);
        // Определение комманды
        switch (tmpchar[0]) {

            // Добавить слово
            case '+':
                // Считываем слово
                scanf("%s", tmpword);
                // Преобразование в нижний регистр
                for (i = 0; i < StringLengthPS; i++) tmpword[i] = tolower(tmpword[i]);
                // Считывание ключа
                scanf("%llu", &tmpkey);
                // Довавляем лист (с включенным выводом)
                AVL_InsertLeaf(tmpword, tmpkey, AVLTree1, true);
                break;

            // Отладочные комманды
            case '!':
                // Считываем слово
                scanf("%s", tmpword);
                // Перевод в нижний регистр
                for (i = 0; i < StringLengthPS; i++) tmpword[i] = tolower(tmpword[i]);
                // Распознание слова
                if (strcmp(tmpword, "exit") == 0) {
                    return 0;
                } else
                if (strcmp(tmpword, "print") == 0) {
                    AVL_PrintMe(AVLTree1);
                } else
                if (strcmp(tmpword, "save") == 0) {
                    AVL_SaveTree(AVLTree1, true);
                } else
                if (strcmp(tmpword, "load") == 0) {
                    AVL_LoadTree(AVLTree1, true);
                }
                break;
            // Удаление слова
            case '-':
                // Считываем слово
                scanf("%s", tmpword);
                // Преобразование в нижний регистр
                for (i = 0; i < StringLengthPS; i++) tmpword[i] = tolower(tmpword[i]);
                // Удаляем лист
                AVL_RemoveLeaf(tmpword, AVLTree1, true);
                break;
            // Заглушка
            case '\n':
                break;
            // Осталось слово
            default:
                for (i = 0; i < StringLengthPS; i++) tmpchar[i] = tolower(tmpchar[i]);
                // Поиск
                tmpkey = AVL_FindMe_p(tmpchar, AVLTree1, true);
                break;

        }
    }
 return 0;
}

// Печать ошибок
void PrintError(unsigned short int ErrorCode){
}

AVL_tree_slimrg.h
#ifndef AVL_tree_slimrg_h
#define AVL_tree_slimrg_h

// Стандартные заголовки
#include <stdbool.h>
#include <string.h>

// Настройки
#include "settings_slimrg.h"

// Сама структура
struct avltree;

// Создание дерева
struct avltree* AVL_Create();

// Уничтожение дерева
void AVL_FreeAndNil(struct avltree* AVL_Tree);

// Проверка на пустоту
bool AVL_IsEmpty(struct avltree* AVL_Tree);

// Добавить лист
void AVL_InsertLeaf(char key[StringLengthPS+1], unsigned long long int llupar, struct avltree* AVL_Tree, bool PrintStatus);

// Удаление листа по значению
void AVL_RemoveLeaf(char key[StringLengthPS+1], struct avltree* AVL_Tree, bool PrintStatus);

// Поиск значения
bool AVL_FindMe(char key[StringLengthPS+1], struct avltree* AVL_Tree);
unsigned long long int AVL_FindMe_p(char key[StringLengthPS+1], struct avltree* AVL_Tree, bool PrintStatus);

// Печать дерева
void AVL_PrintMe(struct avltree* AVL_Tree);

// Сохранение дерева
void AVL_SaveTree(struct avltree* AVL_Tree,  bool PrintStatus);

// Загрузка дерева
void AVL_LoadTree(struct avltree* AVL_Tree,  bool PrintStatus);

#endif

AVL_tree_slimrg.c
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#include "AVL_tree_slimrg.h"

// Структура строки
struct String{
    char* Text;
    unsigned short int count;
};

// Структура листа
struct avlleaf {
  struct String key;              // Ключ
  unsigned long long int llupar;  // Значение
  long int height;                // Высота
  struct avlleaf* left;          // Левый ребенок
  struct avlleaf* right;         // Правый ребенок
};

// Структура дерева
struct avltree {
    struct avlleaf* root;
};

// Создание дерева
struct avltree* AVL_Create() {
  struct avltree* AVL_Tree = malloc(sizeof(struct avltree));
  AVL_Tree->root = NULL;
  return AVL_Tree;
}

// Уничтожение дерева
void AVL_FreeAndNil(struct avltree* AVL_Tree) {
  // Переменные
  char tmpword[StringLengthPS+1];
  unsigned short int i; // Тикер (для циклов и т.д.)

  // Запускаем балалайку ^_^
  while (AVL_IsEmpty(AVL_Tree) == false) {
    for (i = 0; i <= AVL_Tree->root->key.count; i++) {
        tmpword[i] = AVL_Tree->root->key.Text[i];
    }
    AVL_RemoveLeaf(tmpword, AVL_Tree, false);
  }
}

// Проверка на пустоту
bool AVL_IsEmpty(struct avltree* AVL_Tree) {
  return (AVL_Tree->root == NULL);
}

// Инициализация листа
struct avlleaf* AVLLeaf_Create(char inputkey[StringLengthPS+1], unsigned long long int llupar) {

  // Переменные
  struct avlleaf* keim; // Лист
  unsigned short int i; // Тикер (для циклов и т.д.)

  // Начальная инициализация
  keim = malloc(sizeof(struct avlleaf));
  keim->right = keim->left = NULL;
  keim->llupar = llupar;

  // Сложная инициализация
  i = 0;
  while (inputkey[i] != 0) i++;
  keim->key.count = i;
  keim->key.Text = malloc(keim->key.count * sizeof(char));
  for (i = 0; i <= keim->key.count; i++) {
      keim->key.Text[i] =  inputkey[i];
  }

  keim->height = 0;
  return keim;
}

// Получение высоты листа
long int AVLLeaf_GetHeight(struct avlleaf* Leaf) {
  if (Leaf == NULL) return (-1); else return Leaf->height;
}

// Получение коэффицента балансировки
char AVLLeaf_GetBalance(struct avlleaf* Leaf) {
  return (AVLLeaf_GetHeight(Leaf->right) - AVLLeaf_GetHeight(Leaf->left));
}

// Проверка высоты
void AVLLeaf_CheckHeight(struct avlleaf* Leaf) {

  // Переменные
  long int left, right; // Дети листа Leaf

  left  = AVLLeaf_GetHeight(Leaf->left);
  right = AVLLeaf_GetHeight(Leaf->right);

  // Высота получается увеличением максимальной детской высоты на единицу
  if (left <= right)  Leaf->height = right + 1; else Leaf->height = left + 1;
}

// Малое леве вращение (Small Left)
struct avlleaf* AVL_rotation_SL(struct avlleaf* Leaf) {

  // Переменные
  struct avlleaf* aor; // Ось вращения (Axis Of Rotation)

  aor = Leaf->right;

  // Магия вращения... (Вжух...)
  Leaf->right = aor->left;
  aor->left   = Leaf;

  // Выправляем высоту
  AVLLeaf_CheckHeight(Leaf);
  AVLLeaf_CheckHeight(aor);

  return aor;
}

// Малое правое вращение (Small Right)
struct avlleaf* AVL_rotation_SR(struct avlleaf* Leaf) {

  // Переменные
  struct avlleaf* aor; // Ось вращения (Axis Of Rotation)

  aor = Leaf->left;

  // Магия вращения... (Вжух...)
  Leaf->left = aor->right;
  aor->right = Leaf;

  // Выправляем высоту
  AVLLeaf_CheckHeight(Leaf);
  AVLLeaf_CheckHeight(aor);

  return aor;
}

// Ребалансировка дерева
struct avlleaf* AVL_BalanceMe(struct avlleaf* Leaf) {

  // Переменные
  char balfac; // Коэффицент баласировки (от -2 до +2)

  balfac = AVLLeaf_GetBalance(Leaf);

  // Оцениваем баланс и выправляем его
  if (balfac < -1) {

    // Смотрим, требуется ли большое вращение
    if (AVLLeaf_GetBalance(Leaf->left) > 0) {
      Leaf->left = AVL_rotation_SL(Leaf->left);
    }

    return (AVL_rotation_SR(Leaf));

  } else if (balfac > 1) {

    // Смотрим, требуется ли большое вращение
    if (AVLLeaf_GetBalance(Leaf->right) < 0) {
      Leaf->right = AVL_rotation_SR(Leaf->right);
    }

    return (AVL_rotation_SL(Leaf));

  } else {  // Если нуль

    // Вращение НЕ требуется
    AVLLeaf_CheckHeight(Leaf);

    return Leaf;

  }
}

// Поиск места вставки и вставка
struct avlleaf* AVL_FindAndInsert(char key[StringLengthPS+1], unsigned long long int llupar, struct avlleaf* Leaf, bool PrintStatus) {
  // Если поддерево пустое
  if (Leaf == NULL) {

    if (PrintStatus) printf("OK\n");
    return AVLLeaf_Create(key, llupar);

  } else if (strcmp(key, Leaf->key.Text) < 0) {

    Leaf->left  = AVL_FindAndInsert(key, llupar, Leaf->left, PrintStatus);

  } else if (strcmp(key, Leaf->key.Text) > 0){

    Leaf->right = AVL_FindAndInsert(key, llupar, Leaf->right, PrintStatus);

  } else {

    if (PrintStatus) printf("Exist\n");

  }

  return AVL_BalanceMe(Leaf);

}

// Добавление листа (обертка над функцией выше)
void AVL_InsertLeaf(char key[StringLengthPS+1], unsigned long long int llupar, struct avltree* AVLTree, bool PrintStatus) {
  AVLTree->root = AVL_FindAndInsert(key, llupar, AVLTree->root, PrintStatus);
}

// Получение минимального значения
struct String AVL_GetMinKey(struct avlleaf* Leaf) {
  while (Leaf->left != NULL) Leaf = Leaf->left;
  return Leaf->key;
}

// Получение параметра у листа с минимальным значением
unsigned long long int AVL_GetMinVal(struct avlleaf* Leaf) {
  while (Leaf->left != NULL) Leaf = Leaf->left;
  return Leaf->llupar;
}

// Поиск и удаление
struct avlleaf* AVL_FindAndRemove(char key[StringLengthPS+1], struct avlleaf* Leaf, bool PrintStatus) {

  // Переменные
  struct avlleaf* child; // Служебная (для случаев с одним ребенком)
  char tmpkey[StringLengthPS+1];      // Временный контейнер для ключа
  unsigned short int i;  // Тикер (для циклов и т.д.)

  if (Leaf == NULL) {
    // Нет значения для удаления
    if (PrintStatus) printf("NoSuchWord\n");
    return NULL;

  } else if (strcmp(key, Leaf->key.Text) < 0) {

    Leaf->left = AVL_FindAndRemove(key, Leaf->left, PrintStatus);
    return AVL_BalanceMe(Leaf);

  } else if (strcmp(key, Leaf->key.Text) > 0) {

    Leaf->right = AVL_FindAndRemove(key, Leaf->right, PrintStatus);
    return AVL_BalanceMe(Leaf);

  } else { // Найдена позиция

    if (PrintStatus) printf("OK\n");
    // Анализ детей и перемещение
    if (Leaf->left != NULL && Leaf->right != NULL) {

      Leaf->key    =  AVL_GetMinKey(Leaf->right);
      Leaf->llupar =  AVL_GetMinVal(Leaf->right);

      for (i = 0; i <= Leaf->key.count; i++) {
          tmpkey[i] = Leaf->key.Text[i];
      }

      Leaf->right =   AVL_FindAndRemove(tmpkey, Leaf->right, PrintStatus);

      return AVL_BalanceMe(Leaf);

    } else if (Leaf->left != NULL) {

      // Есть только один ребенок (правый)

      child = Leaf->left;
      Leaf->key.count = 0;
      free(Leaf->key.Text);
      free(Leaf);
      return child;

    } else if (Leaf->right != NULL) {

       // Есть только один ребенок (левый)

      child = Leaf->right;
      Leaf->key.count = 0;
      free(Leaf->key.Text);
      free(Leaf);
      return child;

    } else {

      // Нет дитей - просто выкидываем
      Leaf->key.count = 0;
      free(Leaf->key.Text);
      free(Leaf);
      return NULL;

    }

  }

}

// Удаление из дерева (обертка над функцией выше)
void AVL_RemoveLeaf(char key[StringLengthPS+1], struct avltree* AVL_Tree, bool PrintStatus) {
  AVL_Tree->root = AVL_FindAndRemove(key, AVL_Tree->root, PrintStatus);
}

// Поиск элемента в дереве
bool AVL_FindMe(char key[StringLengthPS+1], struct avltree* AVL_Tree) {

  // Переменные
  struct avlleaf* CuP;

  CuP = AVL_Tree->root;
  while (CuP != NULL) {

    if (strcmp (key, CuP->key.Text) == 0) {

      return true;

    } else if (strcmp(key, CuP->key.Text) < 0) {

      CuP  = CuP->left;

    } else {

       CuP = CuP->right;

    }

  }

  return false;

}

// Еще один алгоритм поиска (удобнее для пользователя)
unsigned long long int AVL_FindMe_p(char key[StringLengthPS+1], struct avltree* AVL_Tree, bool PrintStatus){

  // Переменные
  struct avlleaf* CuP;

  CuP = AVL_Tree->root;
  while (CuP != NULL) {

    if (strcmp (key, CuP->key.Text) == 0) {

      if (PrintStatus){
          printf("OK: ");
          printf("%llu", (CuP->llupar));
          printf("\n");
      }
      return CuP->llupar;

    } else if (strcmp(key, CuP->key.Text) < 0) {

      CuP  = CuP->left;

    } else {

       CuP = CuP->right;

    }

  }

  if (PrintStatus) printf("NoSuchWord\n");
  return 0;

}

// Печать дерева
void AVL_print_rec(struct avlleaf* Leaf, long int lvl) {

  // Переменные
  int i;

  if (Leaf == NULL) {
    return;
  }

  AVL_print_rec(Leaf->left, lvl + 1);

  for (i = 0; i < lvl; i++) printf("\t");

  printf("%s", Leaf->key.Text);
  printf("%c", '|');
  printf("%llu", Leaf->llupar);
  printf("\n");

  AVL_print_rec(Leaf->right, lvl + 1);
}

// Печать дерева (обертка над функцией выше)
void AVL_PrintMe(struct avltree* AVL_Tree){
  if (AVL_Tree->root == NULL) {
    printf("EMPTY\n");
  } else {
    AVL_print_rec(AVL_Tree->root, 0);
  }
}

// Запись лист в файл
void AVL_LeafToFile(struct avlleaf* Leaf, FILE * file){
    if (Leaf == NULL) return;

    fwrite(&(Leaf->key.count), sizeof(unsigned short int), 1, file);
    fwrite(Leaf->key.Text, sizeof(char), Leaf->key.count+1, file);
    fwrite(&(Leaf->llupar), sizeof(unsigned long long int), 1, file);

    AVL_LeafToFile(Leaf->right, file);
    AVL_LeafToFile(Leaf->left, file);
}

// Сохранение дерева
void AVL_SaveTree(struct avltree* AVL_Tree, bool PrintStatus){

    // Переменные
    char adress[1024];
    FILE *file = NULL;

    // Открытие файла
    scanf("%s", adress);
    file = fopen(adress, "wb+");
    if ((file == NULL)&&(PrintStatus)) printf("ERROR: Couldn't create file\n");
    if (file == NULL) return;

    // Запись дерева
    fwrite(&(UnCo), sizeof(unsigned long long int), 1, file);
    AVL_LeafToFile(AVL_Tree->root, file);

    // Закрытие
    if (PrintStatus) printf("OK\n");
    fclose(file);
}

// Поиск места вставки и вставка
struct avlleaf* AVL_FindAndInsert_clean(char key[StringLengthPS+1], unsigned long long int llupar, struct avlleaf* Leaf, bool PrintStatus) {
  // Если поддерево пустое
  if (Leaf == NULL) {

    return AVLLeaf_Create(key, llupar);

  } else if (strcmp(key, Leaf->key.Text) < 0) {

    Leaf->left  = AVL_FindAndInsert_clean(key, llupar, Leaf->left, PrintStatus);

  } else if (strcmp(key, Leaf->key.Text) > 0){

    Leaf->right = AVL_FindAndInsert_clean(key, llupar, Leaf->right, PrintStatus);

  } else {

    if (PrintStatus) printf("ERROR: Broken File\n");

  }

  return Leaf;

}

// Добавление листа (обертка над функцией выше)
void AVL_InsertLeaf_clean(char key[StringLengthPS+1], unsigned long long int llupar, struct avltree* AVLTree, bool PrintStatus) {
  AVLTree->root = AVL_FindAndInsert_clean(key, llupar, AVLTree->root, PrintStatus);
}

// Загрузка листа из файла
void AVL_LeafFromFile(struct avltree* AVL_Tree, FILE * file){

    // Переменные
    char tmpkey[StringLengthPS+1];
    unsigned long long int tmpllupar;
    unsigned short int charcount;

    while (feof(file) == 0){
        fread(&charcount, sizeof(unsigned short int), 1, file);
        fread(tmpkey, sizeof(char), charcount+1, file);
        fread(&tmpllupar, sizeof(unsigned long long int), 1, file);

        AVL_InsertLeaf_clean(tmpkey, tmpllupar, AVL_Tree, false);
    }
}

// Загрузка дерева
void AVL_LoadTree(struct avltree* AVL_Tree,  bool PrintStatus){

    // Переменные
    char adress[1024];
    FILE *file = NULL;
    unsigned long long int FileUnCo;

    // Открытие файла
    scanf("%s", adress);
    file = fopen(adress, "rb");
    if ((file == NULL)&&(PrintStatus)) printf("ERROR: Couldn't read file\n");
    if (file == NULL) return;

    // Тест совместимости
    fread(&FileUnCo, sizeof(unsigned long long int), 1, file);
    if (UnCo != FileUnCo){
        printf("ERROR: Unsupported file\n");
        return;
    }

    // Уничтожаем ранее созданное дерево
    AVL_FreeAndNil(AVL_Tree);

    // Загружаем новое дерево
    AVL_LeafFromFile(AVL_Tree, file);

    // Закрытие
    if (PrintStatus) printf("OK\n");
    fclose(file);
}

settings_slimrg.h
#ifndef settings_h
#define settings_h
/* Settings */

//  Настройка ввода
const unsigned int StringLengthPS = 256; // Длина строки (в символах)

// Настройка отладки
const bool debug_pauseonclose = true; // Следует ли делать паузу перед выходом

// Номер сборки
const unsigned long long int UnCo = 115700744534137162;

#endif

MakeFile
all:
    gcc -pedantic -Wall -std=c99 -Werror -Wno-sign-compare main.c AVL_tree_slimrg.c -lm -o lb2

Лог (здесь main.c заменен на lb2.c)
gcc -pedantic -Wall -std=c99 -Werror -Wno-sign-compare lb2.c AVL_tree_slimrg.c -lm -o lb2
/tmp/cc4upHwG.o:(.rodata+0x0): multiple definition of `StringLengthPS'
/tmp/ccORqDAb.o:(.rodata+0x0): first defined here
/tmp/cc4upHwG.o:(.rodata+0x4): multiple definition of `debug_pauseonclose'
/tmp/ccORqDAb.o:(.rodata+0x4): first defined here
/tmp/cc4upHwG.o:(.rodata+0x8): multiple definition of `UnCo'
/tmp/ccORqDAb.o:(.rodata+0x8): first defined here
collect2: error: ld returned 1 exit status
Makefile:2: recipe for target 'all' failed
make: *** [all] Error 1

A: В отличие от С++, в языке С const объекты имеют внешнее связывание по умолчанию. Их нельзя определять в заголовочных файлах.
Либо явно придайте им внутреннее связывание, т.е. определяйте их как static const, либо идите по традиционному пути: в заголовочный файл кладите, extern const без инициализатора, а в один из .c файлов кладите ваши определения.
В вашем случае можно также просто заменить ваши константы на макросы или enum.

A: const unsigned int StringLengthPS = 256; // Длина строки (в символах)
const bool debug_pauseonclose = true; // Следует ли делать паузу перед выходом
const unsigned long long int UnCo = 115700744534137162;

Раз у вас константы в хедере, то они копируются в каждый .c файл, который этот хедер инклудит - отсюда multiple definition.
Решение:
Либо сделать переменные static - тогда каждый файл получит свою копию каждой переменной,
либо заменить переменные на #define.


text:
Q: Self-duality of the subgroup lattice of finite abelian groups For each abelian finite group $G$ let $\mathcal L(G)$ be the lattice of all subgroups of $G$.
For which abelian finite groups $G$, is $(\mathcal L(G),\subseteq)$ order-isomorphic to $(\mathcal L(G),\subseteq^{-1})$?
($\subseteq^{-1}$ is the same as $\supseteq$)

A: Any finite abelian group $G$ is (noncanonically) isomorphic to its dual $\hat{G}=\operatorname{Hom}(G,\mathbb{Q}/\mathbb{Z})$.  By duality, the lattice of subgroups of $G$ is anti-isomorphic to the lattice of subgroups of $\hat{G}\cong G$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to configure idleWaitTime Environment Variable in QuartzScheduler for Spring Framework I currently am using a third party application that uses the spring framework and am trying to troubleshoot an issue where something in the spring framework keeps recreating a connection every 30 seconds to a serverless postgres database in AWS. I am using a Hikari datasource that has been configured with the following environment variables:
DATASOURCE_MINIMUMIDLE=0
DATASOURCE_IDLETIMEOUT=30000
DATASOURCE_MAXLIFETIME=60000

I have confirmed these settings are modifying the hikari pool as expected.
Investigating the issue, I found that Quartz is scheduling a query every 30 seconds or so. I've tried setting the env var to control the idle timeout for the main scheduler loop:
https://github.com/quartz-scheduler/quartz/blob/9f9e400733f51f7cb658e3319fc2c140ab8af938/quartz-core/src/main/java/org/quartz/core/QuartzSchedulerThread.java#L244
Either the env var I'm trying to set to control the idleWaitTime is incorrect or something else is going on.
Does anyone have experience controlling the quartz idleWaitTime with the environment variables?
I've tried SPRING_QUARTZ_PROPERTIES_ORG_QUARTZ_SCHEDULER_IDLEWAITTIME, but that does not seem to have any effect.

A: I solved this by setting the SPRING_APPLICATION_JSON environment variable with the following:
"{\"spring\":{\"application\":{\"quartz\":{\"org.quartz.scheduler.idleWaitTime\":\"600000\"}}}}"


text:
Q: How to include JavaScript file into JSP? I have the following script tag in my JSP file:
<script src="/js/CCTUtil.js"></script>

with the following function in it:
function disableButton(buttonID) {
     document.getElementById(buttonID).setAttribute("disabled", "true");
    return true;
}

and in my jsp I call it with:
onchange="disableButton('datasourceForm:cancel');

datasourceForm:cancel is just the ID, so don't worry about that.
This works if I hardcode the JS function in my JSP, but when exporting it to a file, it doesn't work. It recognizes the valid filepath (otherwise the server throws an exception) so it can see the file just fine, but when testing it in Internet Explorer the error is "Object expected", and points to the end of the JSP file, which of course isn't telling of anything.
Help please?

A: The SRC must not be correct then. Are you sure you have set the path correctly? It's not supposed to be "../js/CCTUtil.js" is it?

A: Instead of including script file, directly add javascript function in the jsp file.
Then try, if you are getting the same issue, might be some issue with javascript or ur id datasourceForm:cancel


text:
Q: Recently started using socket.io - what security measures should I take before releasing the site to the public? The socket server doesn't handle any logins or any inputs from the user, it just delivers information TO the user from a mysql database when it becomes available. Having not worked with socket.io before I don't know what things I should look out for when developing with it. For example can someone access the contents of the .js "server"? Because mine contains some sensitive data like sql credentials.

A: socket.io has pretty much the same security issues as any web server and web requests.  Providing you haven't done anything silly to expose your server side files, they would not generally be accessible.  We'd have to see your actual server-side code to know if you've accidentally exposed anything there.  The main thing to protect your server and your SQL database is that you have to validate all incoming parameters to make sure nothing you aren't expecting is sent to you that could cause your code to accidentally do something that is not intended.
And, one big thing to make sure you're avoiding with SQL queries it to make sure that nothing that is sent to you is directly put into a SQL query as this exposes you to SQL injection attacks where an attacker sends you parameters you aren't expecting which you put into a SQL query which ends up allowing them to run their own SQL on your SQL server.  There is much written about SQL Injection in other articles if you want to learn more about it.
Since you say that you don't handle any logins, you presumably know that you could get any arbitrary number of socket.io connections and pretty much anyone could be connecting (whether from a browser or from some other custom written agent).


text:
Q: C# compiled .exe System.IO.FileNotFOundException (Environment = Windows 10 1803, program type is .exe)
I have written a program to be used across different computers at work, however, When i try to run the compile program from anyone elses machine other than my own (and my fellow IT coworkers), I end up with this error:
(From event viewer)

Event 1026, .NET Runtime Application: program123.exe Framework Version
  v4.0.30.319 Description: The process was terminated due to an
  unhandled exception. Exception Info: System.IO.FileNotFoundException
  at
  System.Reflection.RuntimeAssembly._nLoad(System.Reflection.AssemblyName,
  System.String, System.Security.Policy.Evidence,
  System.Reflection.RuntimeAssembly, ........

I have extensive logging in the application and pretty much log immediately upon program entry. However, my log never gets hit - (to me, this means that this application is being blocked, or dying before running any code).
This is different because my application does not even start. In the example that you recommended, the application begins and then fails on an event. My .exe will not work at all.
Any help would be appreciated. Thanks in advance.


text:
Q: Problem with updating object property in array of objects in React I'm making an ecommrece project, in search bar I'm displaying checkboxes with categories from the API, all of those have value active == true by default. This is how I'm mapping them:
{categories.map((category) => {
       return (
              <>
             <input type="checkbox" onClick={() => handleCheckbox(category)}
             defaultChecked={category.active} key={category.name} />
             {category.name}

             </>
)
})}

Then I run this function to change category.active property from true to false, when the exact checkbox is clicked, then I want to update this object using useState
const handleCheckbox = (category) => {
    let tempCategory = category
    if (tempCategory.active == true) {
        tempCategory.active = false;
    } else {
        tempCategory.active = true;
    }
    setCategories({...categories, [tempCategory.id]: tempCategory})
    console.log(category.active)
}

Unfortunetly when I click on the checkbox I'm getting an error from React:
TypeError: categories.map is not a function

And it points to categories.map, I have no idea how to fix it. All I want is to update specific object in the categories array.

A: I believe your categories start life as an array of category objects, and you meant to setCategories to an array - but instead you're setting it to an object.
You also need to make sure you dont double up tempCategory. something like this:
setCategories([
 ...categories.filter(x => x.id != tempCategory.id),
 tempCategory
]);

However, this will reorder your categories, putting tempCategory at the end, so another option is to slice the array correctly
const tmpIdx = categories.findIndex(x => x.id == tempCategory.id);
setCategories([
     ...categories.slice(0,tmpIdx),
     tempCategory,
     ...categories.slice(tmpIdx+1),
]);

Another option is make your categories an object and use Object.values(categories).map(...) but this makes ordering your categories harder, as there is no fixed ordering of object keys/values like there is with an array.


text:
Q: How does the surfaceview retain the color after glClear is called? I am just beginning to learn openGL and am working on android and am getting stuck in places. Please look at the code below:-
    public void onDrawFrame(GL10 arg0) {

    glClear(GL_COLOR_BUFFER_BIT);
}

@Override
public void onSurfaceChanged(GL10 glUnused, int width, int height) {

    glViewport(0,0,width,height);
}

@Override
public void onSurfaceCreated(GL10 glUnused, EGLConfig config) {

    glClearColor(1.0f,0.0f,0.0f,0.0f);
}

Here in onSurfaceCreated the color is set  and in onDrawFrame the color buffer is cleared. Now once the color buffer is cleared , why is the color of the surface still the same what was set in onSurfaceCreated?

A: glClearColor specifies the color that will be used to clear the buffer. When you call glClear this color will be applied to the buffer.
If you want a dark surface change it to:
 glClearColor(0.0f,0.0f,0.0f,0.0f);


text:
Q: Why are the underscores not all being removed from the list? Python
Possible Duplicate:
Remove all occurences of a value from a Python list

For a list:
char = ['a', '_', '_', 'b' ]

How does one remove all instances of '_' from the list, so it ends up looking like:
char = ['a', 'b' ]

I've tried:
char.remove('_')

which gives me:
char = ['a', '_', 'b']

Why is this, and how can I get it to remove all underscores in the list?

A: list.remove only removes the first instance of a match - you can use a list-comprehension:
char = [el for el in char if el != '_']

A: There are several options considered in this post that is a close duplicate perhaps of this one. One of them is :
>>> x = [1,2,3,2,2,2,3,4]
>>> filter (lambda a: a != 2, x)
[1, 3, 3, 4]


text:
Q: How to find the inner SP's taking time I have 1 main procedure and inside 5 procedure calls and my Main SP taking too much time. I want to find out which is the procedure call taking time to execute amongst inside 5 procedures.

A: you can use the query plan functionality for this. I wrote a blog post for this on http://plixa.nl/how-to-read-query-execution-plans/ where you can find out how to get the plan and how to read it

A: You can log the strat time and end time of each proc in a separate table and then you can check which is taking long time.


text: Q: Record voice and audio file Mixing issue Here, I am using the following Click here attached code for mixing the audio files. But when i am using this for mixing recorded voice and audio file, it's not working for me.So how can i resolve this issue. you Can see my code via this link Code Link


text:
Q: Redirigir segun el dominio Hola amigos estoy buscando la manera correcta de redirigir según de donde viene la visita .
Tengo este código:
 <script>
var result = document.referrer.split( '/' ).indexOf("https://ged-botxtrem.rhcloud.com/");;
if (result >= 0){
    alert("Correcto");
} else {
    alert("Incorrecto");
    location.href = "https://www.google.com/";
}
</script>

El funciona bien pero resulta que cuando la url es :
https://ged-botxtrem.rhcloud.com/index.php

O otra variante. Que no sea solo el dominio.
Redirecciona igual como que no es el dominio correcto .
Espero alguna ayuda Gracias.

A: indexOf
El método indexOf()devuelve el índice, dentro del objeto String que realiza la llamada, de la primera ocurrencia del valor especificado, comenzando la búsqueda desde indiceBusqueda; o -1 si no se encuentra dicho valor.
Es decir, que si https://ged-botxtrem.rhcloud.com/index.php contiene https://ged-botxtrem.rhcloud.com/  y en tu ejemplo siempre será verdadero, retornará un valor distinto a -1.
Si lo que quieres es verificar que las cadenas coincidan o sean iguales, debes comparar los string con localeCompare
 <script>
var result = document.referrer.split( '/' ).localeCompare("https://ged-botxtrem.rhcloud.com/");;
if (result >= 0){
    alert("Correcto");
} else {
    alert("Incorrecto");
    location.href = "https://www.google.com/";
}
</script>

A: ¿Por qué no usas regex?

var url = document.referrer;
var rgx;

rgx = new RegExp("https?\:\/\/es\.stackoverflow\.com\/");

//En tu caso
//rgx = new RegExp("https?:\/\/ged\-botxtrem\.rhcloud\.com\/");

if(rgx.test(url))
  console.log("Correcto");
else
  console.log("Incorrecto");


text:
Q: Uniform initialization allows passing an object to class' constructor. Why? This title might be a little confusing, but I am hurrying with the explanation.
I wanted to ask you guys why having a class like that:
class scoped_thread2
{
    std::thread t;
public:
    explicit scoped_thread2(std::thread t_) : t(std::move(t_))
    {
    }

    ~scoped_thread2() {
        t.join();
    }
};

I was calling constructor of scoped_thread2 like this:
scoped_thread2 thread_test{ std::thread(do_something) };

Where do_something was a simple void function that actually did nothing.
void do_something()
{
    return;
}

So I'm asking, why the first initialization works, and I clearly see in Visual Studio's debugger that we are going into scoped_thread2's constructor, but in this case:
scoped_thread2 thread_test2(std::thread(do_something));

It does not work. I found that it's somehow related to uniform initialization that was introduced in C++11, but I couldn't find a good explanation that would explain this difference to me clearly. Anyone?


text:
Q: Jmeter || Error generating the report: java.lang.NullPointerException while running test from CMD I am trying to execute a test from CMD but getting following error :

Command : jmeter -n -t D:\Users\load.test\Desktop\Performance\apache-jmeter-5.5\bin\UserServices.jmx -l D:\Users\load.test\Desktop\Performance\apache-jmeter-5.5\PerformanceData\MICR_Project\MICR_TestResults\DebugOOM\DebugOOM_1.csv -e -o  D:\Users\load.test\Desktop\Performance\apache-jmeter-5.5\PerformanceData\MICR_Project\MICR_TestResults\DebugOOM\DebugOOM_1 -JURL=localhost -JPort=7058 -JUser=5 -JRampUp=1 -JDuration=900 -JRampUpSteps=1 -JOutputFileName=OutputOOM.jtl -JErrorFileName=ErrorOOM.jtl -JFlow1=100
What could be the possible reasons for this error as its not very informative.emphasized text

A: The NullPointerException is related to generating the HTML Reporting Dashboard, the dashboard generation fails because your test failed to execute at all - no Samplers were run.
The reason why no Samplers were run can be found in jmeter.log file, the most "popular" reasons are:

*

*The number of threads in the Thread Group is 0

*The test uses CSV Data Set Config for parameterization and the CSV file is not present.

*The test uses a JMeter Plugin and the plugin is not installed


text:
Q: How to make rsync skip existing files on destination I have one Raspberry NAS and one backup server (192.168.25.25).
I would like to regularly backup the Raspebery NAS into the backup server where until now I have copied the files manually.
I drafted the following command to be run from the Raspberry NAS:
rsync -vv --ignore-existing -a --progress --stats -e ssh '/home/daniele/nas/Multimedia/' 'pippo@192.168.25.25:/share/Multimedia/'

but the files already existing on the destination server 192.168.25.25 are not skipped but are transferred from source to destination despite the use of the --ignore-existing flag.
What am I doing wrong?
Please help,
Daniele


text:
Q: Jump into Chrome debugger from Angular When I place the command
    debugger;
within my Angular code, it is not jumping into the Chrome debugger when it hits this line.  I just passes over it.
How do you jump into the Chrome debugger from within your Angular code?
Thank you for any insight you can provide.


text:
Q: How to find sources of connections to Mongodb? In the Mongodb, I can see there are 54 connections from different applications in my local server. Is there anyway to see which one of my applications are using Mongodb more than the others?
Imagine I have 10 application using mongo db with different names and ports.
This is full MongoDB log:
2017-09-05T11:04:34.772+0430 I CONTROL  [initandlisten] MongoDB starting : pid=10554 port=27017 dbpath=/var/lib/mongodb 64-bit host=s19497827.onlinehome-server.com
2017-09-05T11:04:34.772+0430 I CONTROL  [initandlisten] db version v3.0.14
2017-09-05T11:04:34.772+0430 I CONTROL  [initandlisten] git version: 08352afcca24bfc145240a0fac9d28b978ab77f3
2017-09-05T11:04:34.772+0430 I CONTROL  [initandlisten] build info: Linux ip-10-30-223-232 3.2.0-4-amd64 #1 SMP Debian 3.2.46-1 x86_64 BOOST_LIB_VERSION=1_49
2017-09-05T11:04:34.772+0430 I CONTROL  [initandlisten] allocator: tcmalloc
2017-09-05T11:04:34.772+0430 I CONTROL  [initandlisten] options: { config: "/etc/mongod.conf", net: { bindIp: "127.0.0.1", port: 27017 }, storage: { dbPath: "/var/lib/mongodb", journal: { enabled: true } }, systemLog: { destination: "file", logAppend: true, path: "/var/log/mongodb/mongod.log" } }
2017-09-05T11:04:34.805+0430 W -        [initandlisten] Detected unclean shutdown - /var/lib/mongodb/mongod.lock is not empty.
2017-09-05T11:04:34.819+0430 I JOURNAL  [initandlisten] journal dir=/var/lib/mongodb/journal
2017-09-05T11:04:34.819+0430 I JOURNAL  [initandlisten] recover begin
2017-09-05T11:04:34.819+0430 I JOURNAL  [initandlisten] recover lsn: 749244
2017-09-05T11:04:34.819+0430 I JOURNAL  [initandlisten] recover /var/lib/mongodb/journal/j._0
2017-09-05T11:04:34.819+0430 I JOURNAL  [initandlisten] recover skipping application of section seq:80 < lsn:749244
2017-09-05T11:04:34.819+0430 I JOURNAL  [initandlisten] recover skipping application of section seq:522054 < lsn:749244
2017-09-05T11:04:34.819+0430 I JOURNAL  [initandlisten] recover applying initial journal section with sequence number 749244
2017-09-05T11:04:34.821+0430 I JOURNAL  [initandlisten] recover cleaning up
2017-09-05T11:04:34.821+0430 I JOURNAL  [initandlisten] removeJournalFiles
2017-09-05T11:04:34.822+0430 I JOURNAL  [initandlisten] recover done
2017-09-05T11:04:34.847+0430 I JOURNAL  [durability] Durability thread started
2017-09-05T11:04:34.847+0430 I JOURNAL  [journal writer] Journal writer thread started
2017-09-05T11:04:34.847+0430 I CONTROL  [initandlisten]
2017-09-05T11:04:34.847+0430 I CONTROL  [initandlisten] ** WARNING: You are running in OpenVZ which can cause issues on versions of RHEL older than RHEL6.
2017-09-05T11:04:34.848+0430 I CONTROL  [initandlisten]
2017-09-05T11:04:34.952+0430 I NETWORK  [initandlisten] waiting for connections on port 27017
2017-09-05T11:04:37.040+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55262 #1 (1 connection now open)
2017-09-05T11:04:37.040+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55264 #2 (2 connections now open)
2017-09-05T11:04:37.041+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55266 #3 (3 connections now open)
2017-09-05T11:04:37.042+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55268 #4 (4 connections now open)
2017-09-05T11:04:37.043+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55270 #5 (5 connections now open)
2017-09-05T11:04:37.043+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55272 #6 (6 connections now open)
2017-09-05T11:04:37.043+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55274 #7 (7 connections now open)
2017-09-05T11:04:37.043+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55276 #8 (8 connections now open)
2017-09-05T11:04:37.043+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55278 #9 (9 connections now open)
2017-09-05T11:04:37.044+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55280 #10 (10 connections now open)
2017-09-05T11:04:37.044+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55282 #11 (11 connections now open)
2017-09-05T11:04:37.045+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55284 #12 (12 connections now open)
2017-09-05T11:04:37.046+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55286 #13 (13 connections now open)
2017-09-05T11:04:37.047+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55288 #14 (14 connections now open)
2017-09-05T11:04:37.047+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55290 #15 (15 connections now open)
2017-09-05T11:04:37.058+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55292 #16 (16 connections now open)
2017-09-05T11:04:37.525+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55324 #17 (17 connections now open)
2017-09-05T11:04:37.870+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55348 #18 (18 connections now open)
2017-09-05T11:04:38.030+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55360 #19 (19 connections now open)
2017-09-05T11:04:38.097+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55366 #20 (20 connections now open)
2017-09-05T11:04:38.527+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55396 #21 (21 connections now open)
2017-09-05T11:04:38.545+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55398 #22 (22 connections now open)
2017-09-05T11:04:38.958+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55430 #23 (23 connections now open)
2017-09-05T11:04:38.964+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55432 #24 (24 connections now open)
2017-09-05T11:04:38.966+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55434 #25 (25 connections now open)
2017-09-05T11:04:38.971+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55436 #26 (26 connections now open)
2017-09-05T11:04:38.993+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55440 #27 (27 connections now open)
2017-09-05T11:04:38.996+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55442 #28 (28 connections now open)
2017-09-05T11:04:38.998+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55444 #29 (29 connections now open)
2017-09-05T11:04:38.998+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55446 #30 (30 connections now open)
2017-09-05T11:04:39.001+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55448 #31 (31 connections now open)
2017-09-05T11:04:39.002+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55450 #32 (32 connections now open)
2017-09-05T11:04:39.002+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55452 #33 (33 connections now open)
2017-09-05T11:04:39.113+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55460 #34 (34 connections now open)
2017-09-05T11:04:39.132+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55464 #35 (35 connections now open)
2017-09-05T11:04:39.147+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55466 #36 (36 connections now open)
2017-09-05T11:04:39.148+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55470 #37 (37 connections now open)
2017-09-05T11:04:39.616+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55496 #38 (38 connections now open)
2017-09-05T11:04:39.622+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55498 #39 (39 connections now open)
2017-09-05T11:04:40.295+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55540 #40 (40 connections now open)
2017-09-05T11:04:40.351+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55546 #41 (41 connections now open)
2017-09-05T11:04:40.576+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55562 #42 (42 connections now open)
2017-09-05T11:04:41.106+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55594 #43 (43 connections now open)
2017-09-05T11:04:41.246+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55608 #44 (44 connections now open)
2017-09-05T11:04:41.615+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55630 #45 (45 connections now open)
2017-09-05T11:04:41.621+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55632 #46 (46 connections now open)
2017-09-05T11:04:41.625+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55634 #47 (47 connections now open)
2017-09-05T11:04:41.625+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55636 #48 (48 connections now open)
2017-09-05T11:04:41.652+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55638 #49 (49 connections now open)
2017-09-05T11:04:42.300+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55682 #50 (50 connections now open)
2017-09-05T11:04:42.609+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55698 #51 (51 connections now open)
2017-09-05T11:04:42.682+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55702 #52 (52 connections now open)
2017-09-05T11:04:42.979+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55722 #53 (53 connections now open)
2017-09-05T11:04:43.161+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55740 #54 (54 connections now open)
2017-09-05T11:04:43.711+0430 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:55780 #55 (55 connections now open)

When I run the command:
sudo lsof | grep mongod | grep TCP

The result is:
lsof: WARNING: can't stat() fuse.gvfsd-fuse file system /run/user/1000/gvfs
      Output information may be incomplete.
lsof: WARNING: can't stat() fuse.mongobooster-4.0.2-x86_64.AppImage file system /tmp/.mount_XnRJeB
      Output information may be incomplete.
mongod    10082             mongodb    7u     IPv4              74307        0t0        TCP localhost:27017 (LISTEN)
mongod    10082             mongodb   40u     IPv4             167764        0t0        TCP localhost:27017->localhost:52582 (ESTABLISHED)
mongod    10082             mongodb   41u     IPv4             167765        0t0        TCP localhost:27017->localhost:52584 (ESTABLISHED)
mongod    10082             mongodb   42u     IPv4             167766        0t0        TCP localhost:27017->localhost:52586 (ESTABLISHED)
signalP.g 10082 10083       mongodb    7u     IPv4              74307        0t0        TCP localhost:27017 (LISTEN)
signalP.g 10082 10083       mongodb   40u     IPv4             167764        0t0        TCP localhost:27017->localhost:52582 (ESTABLISHED)
signalP.g 10082 10083       mongodb   41u     IPv4             167765        0t0        TCP localhost:27017->localhost:52584 (ESTABLISHED)
signalP.g 10082 10083       mongodb   42u     IPv4             167766        0t0        TCP localhost:27017->localhost:52586 (ESTABLISHED)
Backgro.k 10082 10084       mongodb    7u     IPv4              74307        0t0        TCP localhost:27017 (LISTEN)
Backgro.k 10082 10084       mongodb   40u     IPv4             167764        0t0        TCP localhost:27017->localhost:52582 (ESTABLISHED)
Backgro.k 10082 10084       mongodb   41u     IPv4             167765        0t0        TCP localhost:27017->localhost:52584 (ESTABLISHED)
Backgro.k 10082 10084       mongodb   42u     IPv4             167766        0t0        TCP localhost:27017->localhost:52586 (ESTABLISHED)
mongod    10082 10089       mongodb    7u     IPv4              74307        0t0        TCP localhost:27017 (LISTEN)
mongod    10082 10089       mongodb   40u     IPv4             167764        0t0        TCP localhost:27017->localhost:52582 (ESTABLISHED)
mongod    10082 10089       mongodb   41u     IPv4             167765        0t0        TCP localhost:27017->localhost:52584 (ESTABLISHED)
mongod    10082 10089       mongodb   42u     IPv4             167766        0t0        TCP localhost:27017->localhost:52586 (ESTABLISHED)
mongod    10082 10090       mongodb    7u     IPv4              74307        0t0        TCP localhost:27017 (LISTEN)
mongod    10082 10090       mongodb   40u     IPv4             167764        0t0        TCP localhost:27017->localhost:52582 (ESTABLISHED)
mongod    10082 10090       mongodb   41u     IPv4             167765        0t0        TCP localhost:27017->localhost:52584 (ESTABLISHED)
mongod    10082 10090       mongodb   42u     IPv4             167766        0t0        TCP localhost:27017->localhost:52586 (ESTABLISHED)
mongod    10082 10091       mongodb    7u     IPv4              74307        0t0        TCP localhost:27017 (LISTEN)
mongod    10082 10091       mongodb   40u     IPv4             167764        0t0        TCP localhost:27017->localhost:52582 (ESTABLISHED)
mongod    10082 10091       mongodb   41u     IPv4             167765        0t0        TCP localhost:27017->localhost:52584 (ESTABLISHED)
mongod    10082 10091       mongodb   42u     IPv4             167766        0t0        TCP localhost:27017->localhost:52586 (ESTABLISHED)
mongod    10082 10092       mongodb    7u     IPv4              74307        0t0        TCP localhost:27017 (LISTEN)
mongod    10082 10092       mongodb   40u     IPv4             167764        0t0        TCP localhost:27017->localhost:52582 (ESTABLISHED)
mongod    10082 10092       mongodb   41u     IPv4             167765        0t0        TCP localhost:27017->localhost:52584 (ESTABLISHED)
mongod    10082 10092       mongodb   42u     IPv4             167766        0t0        TCP localhost:27017->localhost:52586 (ESTABLISHED)
mongod    10082 10093       mongodb    7u     IPv4              74307        0t0        TCP localhost:27017 (LISTEN)
mongod    10082 10093       mongodb   40u     IPv4             167764        0t0        TCP localhost:27017->localhost:52582 (ESTABLISHED)
mongod    10082 10093       mongodb   41u     IPv4             167765        0t0        TCP localhost:27017->localhost:52584 (ESTABLISHED)
mongod    10082 10093       mongodb   42u     IPv4             167766        0t0        TCP localhost:27017->localhost:52586 (ESTABLISHED)
mongod    10082 10094       mongodb    7u     IPv4              74307        0t0        TCP localhost:27017 (LISTEN)
mongod    10082 10094       mongodb   40u     IPv4             167764        0t0        TCP localhost:27017->localhost:52582 (ESTABLISHED)
mongod    10082 10094       mongodb   41u     IPv4             167765        0t0        TCP localhost:27017->localhost:52584 (ESTABLISHED)
mongod    10082 10094       mongodb   42u     IPv4             167766        0t0        TCP localhost:27017->localhost:52586 (ESTABLISHED)
mongod    10082 10095       mongodb    7u     IPv4              74307        0t0        TCP localhost:27017 (LISTEN)
mongod    10082 10095       mongodb   40u     IPv4             167764        0t0        TCP localhost:27017->localhost:52582 (ESTABLISHED)
mongod    10082 10095       mongodb   41u     IPv4             167765        0t0        TCP localhost:27017->localhost:52584 (ESTABLISHED)
mongod    10082 10095       mongodb   42u     IPv4             167766        0t0        TCP localhost:27017->localhost:52586 (ESTABLISHED)
mongod    10082 10096       mongodb    7u     IPv4              74307        0t0        TCP localhost:27017 (LISTEN)
mongod    10082 10096       mongodb   40u     IPv4             167764        0t0        TCP localhost:27017->localhost:52582 (ESTABLISHED)
mongod    10082 10096       mongodb   41u     IPv4             167765        0t0        TCP localhost:27017->localhost:52584 (ESTABLISHED)
mongod    10082 10096       mongodb   42u     IPv4             167766        0t0        TCP localhost:27017->localhost:52586 (ESTABLISHED)
mongod    10082 10097       mongodb    7u     IPv4              74307        0t0        TCP localhost:27017 (LISTEN)
mongod    10082 10097       mongodb   40u     IPv4             167764        0t0        TCP localhost:27017->localhost:52582 (ESTABLISHED)
mongod    10082 10097       mongodb   41u     IPv4             167765        0t0        TCP localhost:27017->localhost:52584 (ESTABLISHED)
mongod    10082 10097       mongodb   42u     IPv4             167766        0t0        TCP localhost:27017->localhost:52586 (ESTABLISHED)
WTJourn.F 10082 10098       mongodb    7u     IPv4              74307        0t0        TCP localhost:27017 (LISTEN)
WTJourn.F 10082 10098       mongodb   40u     IPv4             167764        0t0        TCP localhost:27017->localhost:52582 (ESTABLISHED)
WTJourn.F 10082 10098       mongodb   41u     IPv4             167765        0t0        TCP localhost:27017->localhost:52584 (ESTABLISHED)
WTJourn.F 10082 10098       mongodb   42u     IPv4             167766        0t0        TCP localhost:27017->localhost:52586 (ESTABLISHED)
DeadlineM 10082 10099       mongodb    7u     IPv4              74307        0t0        TCP localhost:27017 (LISTEN)
DeadlineM 10082 10099       mongodb   40u     IPv4             167764        0t0        TCP localhost:27017->localhost:52582 (ESTABLISHED)
DeadlineM 10082 10099       mongodb   41u     IPv4             167765        0t0        TCP localhost:27017->localhost:52584 (ESTABLISHED)
DeadlineM 10082 10099       mongodb   42u     IPv4             167766        0t0        TCP localhost:27017->localhost:52586 (ESTABLISHED)
ftdc      10082 10100       mongodb    7u     IPv4              74307        0t0        TCP localhost:27017 (LISTEN)
ftdc      10082 10100       mongodb   40u     IPv4             167764        0t0        TCP localhost:27017->localhost:52582 (ESTABLISHED)
ftdc      10082 10100       mongodb   41u     IPv4             167765        0t0        TCP localhost:27017->localhost:52584 (ESTABLISHED)
ftdc      10082 10100       mongodb   42u     IPv4             167766        0t0        TCP localhost:27017->localhost:52586 (ESTABLISHED)
RangeDele 10082 10101       mongodb    7u     IPv4              74307        0t0        TCP localhost:27017 (LISTEN)
RangeDele 10082 10101       mongodb   40u     IPv4             167764        0t0        TCP localhost:27017->localhost:52582 (ESTABLISHED)
RangeDele 10082 10101       mongodb   41u     IPv4             167765        0t0        TCP localhost:27017->localhost:52584 (ESTABLISHED)
RangeDele 10082 10101       mongodb   42u     IPv4             167766        0t0        TCP localhost:27017->localhost:52586 (ESTABLISHED)
TTLMonito 10082 10102       mongodb    7u     IPv4              74307        0t0        TCP localhost:27017 (LISTEN)
TTLMonito 10082 10102       mongodb   40u     IPv4             167764        0t0        TCP localhost:27017->localhost:52582 (ESTABLISHED)
TTLMonito 10082 10102       mongodb   41u     IPv4             167765        0t0        TCP localhost:27017->localhost:52584 (ESTABLISHED)
TTLMonito 10082 10102       mongodb   42u     IPv4             167766        0t0        TCP localhost:27017->localhost:52586 (ESTABLISHED)
clientcur 10082 10103       mongodb    7u     IPv4              74307        0t0        TCP localhost:27017 (LISTEN)
clientcur 10082 10103       mongodb   40u     IPv4             167764        0t0        TCP localhost:27017->localhost:52582 (ESTABLISHED)
clientcur 10082 10103       mongodb   41u     IPv4             167765        0t0        TCP localhost:27017->localhost:52584 (ESTABLISHED)
clientcur 10082 10103       mongodb   42u     IPv4             167766        0t0        TCP localhost:27017->localhost:52586 (ESTABLISHED)
Periodi.k 10082 10104       mongodb    7u     IPv4              74307        0t0        TCP localhost:27017 (LISTEN)
Periodi.k 10082 10104       mongodb   40u     IPv4             167764        0t0        TCP localhost:27017->localhost:52582 (ESTABLISHED)
Periodi.k 10082 10104       mongodb   41u     IPv4             167765        0t0        TCP localhost:27017->localhost:52584 (ESTABLISHED)
Periodi.k 10082 10104       mongodb   42u     IPv4             167766        0t0        TCP localhost:27017->localhost:52586 (ESTABLISHED)
thread1   10082 10105       mongodb    7u     IPv4              74307        0t0        TCP localhost:27017 (LISTEN)
thread1   10082 10105       mongodb   40u     IPv4             167764        0t0        TCP localhost:27017->localhost:52582 (ESTABLISHED)
thread1   10082 10105       mongodb   41u     IPv4             167765        0t0        TCP localhost:27017->localhost:52584 (ESTABLISHED)
thread1   10082 10105       mongodb   42u     IPv4             167766        0t0        TCP localhost:27017->localhost:52586 (ESTABLISHED)
conn2     10082 10122       mongodb    7u     IPv4              74307        0t0        TCP localhost:27017 (LISTEN)
conn2     10082 10122       mongodb   40u     IPv4             167764        0t0        TCP localhost:27017->localhost:52582 (ESTABLISHED)
conn2     10082 10122       mongodb   41u     IPv4             167765        0t0        TCP localhost:27017->localhost:52584 (ESTABLISHED)
conn2     10082 10122       mongodb   42u     IPv4             167766        0t0        TCP localhost:27017->localhost:52586 (ESTABLISHED)
conn3     10082 10123       mongodb    7u     IPv4              74307        0t0        TCP localhost:27017 (LISTEN)
conn3     10082 10123       mongodb   40u     IPv4             167764        0t0        TCP localhost:27017->localhost:52582 (ESTABLISHED)
conn3     10082 10123       mongodb   41u     IPv4             167765        0t0        TCP localhost:27017->localhost:52584 (ESTABLISHED)
conn3     10082 10123       mongodb   42u     IPv4             167766        0t0        TCP localhost:27017->localhost:52586 (ESTABLISHED)
conn4     10082 10124       mongodb    7u     IPv4              74307        0t0        TCP localhost:27017 (LISTEN)
conn4     10082 10124       mongodb   40u     IPv4             167764        0t0        TCP localhost:27017->localhost:52582 (ESTABLISHED)
conn4     10082 10124       mongodb   41u     IPv4             167765        0t0        TCP localhost:27017->localhost:52584 (ESTABLISHED)
conn4     10082 10124       mongodb   42u     IPv4             167766        0t0        TCP localhost:27017->localhost:52586 (ESTABLISHED)

A: As per your log i am able to see you are using linux O.S.  So, the below grep command you are able to see how connections open to the MongoDB port (27017) on my computer.
$ sudo lsof | grep mongod | grep TCP

As per you log statement, After execution the above query . which you have already said in your question statement.
I am able to see your log statement like
TCP localhost:27017 (LISTEN)
TCP localhost:27017->localhost:52582 (ESTABLISHED)
TCP localhost:27017->localhost:52584 (ESTABLISHED)
TCP localhost:27017->localhost:52586 (ESTABLISHED)

I would like to say that here in your case three connections open for the mongodb by default port 27017.
And for the number of connection
db.serverStatus()

It gives no of connections opend and avail but not shows the connections from which client.
Even you can also get directly by querying
db.serverStatus().connections

for your ref Here


text:
Q: AS3 Verify Socket Host Connection - Resolve Host? I've ran into a bit of a problem where people are manipulating the connection of my game clients socket through the use of their local HOST file. That is to say, I have some method similar to
    private var _socket : Socket;
    public function init(host : String, port : uint = 0) : Boolean {
        _socket.connect(host, port);
        return true;
    }

I expect host to always be something along the lines of 'example.game.com', and for that to always resolve to some ip '255.255.255.255'. However through the use of HOST file it is possible that 'example.game.com' to resolve to '127.0.0.1', which is allowing for third party applications to intercept and modify game data.
The crooks of it are I cannot use DNSResolver as this requires AIR, the solution would have to be pure Actionscript. I also cannot trust a request to some external JS/PHP script that would resolve it for me, as the result of this could be modified with some HTTP Proxy (e.x. Fiddler)
Does anyone have any pure AS3 solution that would allow for me to ensure the host my socket has connected to is what I want?

A: I can think of two ways.
Firstly, from initial testing it looks like you can query remoteHost and remotePort. Even if you're using hosts, they return a value that is useful to you. This is shown below.
Secondly, you can set up your socket to ping Flash in order to get a response every ~5 minutes or so. Have the ping request localAddress, localPort, remoteAddress and remotePort. If they do not match what you expect when you receive the data, terminate the connection.
Most importantly, validate on the server side whenever you receive data. Make your server aware of what the player is doing, as well as what is within reason. Mos multiplayer games (which is what I assume this is), effectively 'run' themselves on the server. So, if user A did manage to bypass the security you had set up and said he wanted to hit a target 5000 yards away for 1.5 million damage, the server already knows that:

*

*A he's out of range

*B he can't do that much damage

This topic is one of the most difficult to manage when it comes to developing the end game. Whilst you can battle it, and mostly win, you'll never stop people 'emulating' servers and using your content there. But, you should be able to stop most injections into your game.
Edit: Your problems really start when people begin to decompile the SWF and manage to recompile it. Then, any client-side validation is out of the window as they'll remove the validation that you have in place and you're reliant 100% on the server side validation. This can also happen through memory editing as well, though... In general, client side validation will only stop the more basic "hacker's".
package kazo
{
    import flash.net.SharedObject;
    import flash.net.Socket;
    import flash.events.Event
    import flash.events.ProgressEvent
    import flash.events.SecurityErrorEvent
    import flash.events.IOErrorEvent
    /**
     * ...
     * @author KM
     */
    public class TestCases
    {

        private var socket:Socket;

        private const ADDRESS_LIST:Vector.<String> = {
            '255.255.255.255',
            '255.255.255.254'
        }
        private const PORT_LIST:Vector.<String> = {
            '111',
            '112'
        }

        public function TestCases() { }

        /**
         * Start the test case
         */
        public function start():void {
            trace('Starting test case');

            socket = new Socket();

            socket.addEventListener(Event.CONNECT, onConnect);
            socket.addEventListener(ProgressEvent.SOCKET_DATA, onData);

            socket.connect('example.domain.com', port);
        }

        /**
         *
         * @param   e
         */
        private function onConnect(e:Event):void {
            trace(socket.remoteAddress);
            trace(socket.remotePort);

            // validate before doing anything
            validateNow();
        }

        /**
         *
         * @param   e
         */
        private function onData(e:ProgressEvent):void {
            trace(e.target);

            // validate before processing data
            validateNow();
        }

        /**
         *
         */
        private function validateNow():void {
            var i:int = 0;
            // List of allowed ports (MUST be hardcoded)
            var portLen:int = PORT_LIST.length;
            // List of addresses (MUST be hardcoded)
            var addressLen:int = ADDRESS_LIST.length;

            var addressPass:Boolean;
            var portPass:Boolean;

            // Loop through, make sure we're valid
            for (i; i < portLen; i++) {
                PORT_LIST[i] === socket.remotePort ? portPass = true : continue;
            }

            // Loop through, make sure we're valid
            for (i = 0; i < addressLen; i++) {
                ADDRESS_LIST[i] === socket.remoteAddress ? addressPass = true : continue;
            }

            // If we're not, close off. If we are, run the course
            if (!addressPass || !portPass) {
                socket.close();
                // inform server
            }
        }

    }

}


text:
Q: Cannot read properties of undefined (reading 'indexOf') in firebase v9 {modular} I changed my code from firebase v8 to v9, I am able to write the data in db but couldn't get and map it.
My data is stored in db like this : users >> user.uid >> orders >> paymentIntent.id,
each doc saved has amount, basket data, created
Please check mentioned screenshot.
Previous code:
useEffect(() => {
    if (user) {
      db.collection("users")
        .doc(user?.uid)
        .collection("orders")
        .orderBy("created", "desc")
        .onSnapshot((snapshot) => {
          // console.log(snapshot);
          setOrders(
            snapshot.docs.map((doc, i) => ({
              key: { i },
              id: doc.id,
              data: doc.data(),
            }))
          );
        });
    } else {
      setOrders([]);
    }
  }, [user]);

My data is stored in db like this : users >> user.uid >> orders >> paymentIntent.id,
each doc saved has amount, basket data, created
Please check mentioned screenshot.
This is firestore inserted data
firestore added data in db, screenshot
This is my new code
import { collection, doc, getDoc, getDocs, onSnapshot, orderBy, query } from 'firebase/firestore';
import React, { useEffect, useState } from 'react'
import { db } from './firebase';
import './Orders.css'
import { useStateValue } from './StateProvider';
import Order from './Order';

function Orders() {
  const [{ basket, user}, dispatch] = useStateValue();
  const [orders, setOrders] = useState([]);

useEffect(() => {
  const getDocs = async () => {
    try {
      const collRef = await getDocs(collection(db, "users", user?.id, "orders"));
      // const collRef = doc(db, "users", user?.id, "orders"));
      // const collRef = collection(db, "users", user?.id, "orders"));

      const orderedRef = query(collRef, orderBy("created", "desc"));
      const docSnap = onSnapshot(orderedRef, (snapshot) => {
        snapshot.map((doc) => ({
          id: doc.id,
          data: doc.data(),
        }));
        setOrders(docSnap);
      });
    } catch (err) {
      console.log(err.message);
    }
  };
  getDocs();
}, [user]);

  return (

Your Orders

        {orders?.map((order, i) => (
          <Order key={i} order={order} />
        ))}

  );
}

export default Orders;

Console, screenshot

A: My guess it that user doesn't have a value, so user?.id becomes undefined. You'll want to still check whether user has a value inside the second snippet too.
For example:
useEffect(() => {
  const getDocs = async (user: User) => {
    try {
      const collRef = await getDocs(collection(db, "users", user.id, "orders"));

      ...
    } catch (err) {
      console.log(err.message);
    }
  };
  if (user) {
    getDocs(user!);
  }
}, [user]);

A: useEffect(() => {
  if (user) {
    try {
            const collRef = collection(db, "users", user?.uid, "orders");
            const orderedRef = query(collRef, orderBy("created", "desc"));
            const docSnap = onSnapshot(orderedRef, (querySnapshot) => {
              const orderArray = [];
              querySnapshot.forEach((doc) => {
                orderArray.push({
                  id: doc.id,
                  data: doc.data()
                })
              })
              setOrders(orderArray);
             });
          } catch (err) {
            console.log(err.message);
          }
  } else {
    console.log("not found");
    setOrders([]);
  }
}, [user]);


text:
Q: How Can I change Network UI Name in settings? I need to change network name in setting like bellow picture.
I want to change UI name (PCI Ethernet / USB Ethernet) in settin not eth0..eth2..enp2s0.
ex) PCI Ethernet -> Network 1
USB Ethernet -> Network 2


text:
Q: Assigning an array as a component of another array in Python I have a 3-d array G with a size that changes in a loop. In Matlab, I first create an empty array G = [];
then I create the first element of G from another existing array D with size 256x256, it is simple to do that in matlab as follows
  G(:,:,1) = D(:,:)

How can I do the same thing in Python?

A: Consider preallocating.
In python's numpy you can preallocate like this:
G = np.zeros([depth, height, width])

then you can slice G in a way similar to matlab, and substitue matrices in it. If you still want to have an array of changing size, you can create a list with your 2D arrays and then convert it to a np.array, like so:
G = list()
for i in range(N):
    G.append(D)
G = np.array(G)

A: an empty 3d array should look something like this
    n = 256
    threeD = [[[0 for k in xrange(n)] for j in xrange(n)] for i in xrange(n)]

or if you want just one 256x256 2d array in the larger 3d array (which is what i think you are trying in Matlab)
    threeD = [[[0 for k in xrange(n)] for j in xrange(n)]]

where n is the size of each "dimension".
it will give you an array full of 0, or you can replace 0 with None if that is more desirable as an empty array
also, it isn't really an "array" in python, it's a "list"

A: You can use
G[:,:,1]=D[:,:]

Example:
>>> G=np.zeros((2,2,2))
>>> D=np.ones((2,2))
>>> G[:,:,1]=D[:,:]
>>> G
array([[[ 0.,  1.],
        [ 0.,  1.]],

       [[ 0.,  1.],
        [ 0.,  1.]]])


text:
Q: I need an API to plot waypoints and give me a route through them, and to give me city population. Which API should I use? I'm making an iOS app that needs to be able to find the most populated cities within a radius from a certain point, and to calculate a route that passes through a certain number of those cities, that satisfy a certain time constraint. I'm planning to use Google to give me polylines that I can put directly on an Apple Map in the Mapkit for Xcode. I've looked into the Google Maps SDK for iOS, and Google Places. Google also has a Directions API, and a Distance Matrix API. With so many API's, I'm slightly confused about which one I should use, and for what.
Additionally, do Google API's provide city population, or should I find that via another database?

A: You can use Google Maps URL Scheme to get directions for Google Maps iOS.
If you are ever confused about which API to use for Google Maps, you can use API picker.
There is no Google API that give city population, so you would need to find it with a another database.


text:
Q: og:description not displaying on LinkedIn I'm trying to troubleshoot an issue regarding the description of our links not displaying on the LinkedIn site, and I've noticed that the og:description tag is not being used. This is also the same for other sites that share their content with LinkedIn .
Does LinkedIn no longer display the description of a site?
Thanks.


text:
Q: iOS 9: App Transport Security I am trying to display the www.usta.com website in my application.
I added the following keys to my .plist and the site loads some of the data. However, it will not load any of the images.
Does anyone know why the images won't load?

I am testing on an iPhone 6 device that has iOS 9.3 installed.

A: The website you're asking about uses Amazon S3 to serve images. This screenshot shows where the images are loading from:

Since App Transport Security checks for a matching domain name, you need to add the s3 domain (amazonaws.com) to your plist.

A: My first try would be to simply allow arbitrary loads, unless you are wanting ONLY usta.com to be able to load. This should be the most simple way of doing it unless you are wanting to restrict which kinds of websites (http vs https) will load other than usta.


text:
Q: What's wrong with the ?? operator used like this: So insteed of writing:
if (obj.Collection == null)
    obj.Collection = new Collection();
obj.Collection.Add(something);

I thought of writing:
obj.Collection = obj.Collection ?? new Collection;
obj.Collection.Add(something);

It kind of feels wrong, especially this part "obj.Collection = obj.Collection..."
What do you guys think ?
Regards,

A: Do you mean:
if (obj.Collection == null)
   {
      obj.Collection = new Collection();
   }
obj.Collection.Add(something);

If so, you can rewrite it as
(obj.Collection = (obj.Collection ?? new Collection())).Add(something);

A: If I had to choose between these two blocks of code, I would use the former. It's more readable and it's a common pattern. ?? is useful in scenarios where you need to default a value (e.g., DateTime date = nullableDateTimeInstance ?? defaultDate;).
But frankly, I'd try to not end up in situation where I want to add to collection and it's possible that the collection is null. Instead, I'd make sure that the collection is initialized in the constructor or whatever the case may be.

A: The code will emit an unnecessary assignment (of obj.Collection to itself) if obj.Collection is not null, but other than that it is equivalent to the original.
Looks fine to me provided you don't use it in time critical sections.  Anyway it's possible the compiler can optimise the assignment away, but I don't know if it would or not.
Perhaps it just feels wrong because the original code is such a common and simple pattern that it feels wrong to change it.

A: I'd say it also depends on what the setter of the Collection property does. Consider this:
public Collection Collection
{
    get { return _collection; }
    set
    {
        _collection = value;
        Thread.Sleep( 1000 ); // or some expensive real work
    }
}

In this case, the assignment obj.Collection = obj.Collection ?? new Collection() would be really costly.
However, if you need to create a collection "on demand", it's common to use a similar pattern in the property getter, like this:
public Collection Collection
{
    get { return _collection ?? ( _collection = new Collection() ); }
}


text:
Q: How to only remove one item from list with duplicates? I have a list: (x, y, y,z)
I have another list: (x, y)
You want to remove the items from the 1st list that belong also in the 2nd list.
Ex: I want the result to be (y,z)
How do I do this?
EDIT: If I use removeAll. The example list returns (z)

A: You can do this in many ways. Here is some examples.
List<String> one = new ArrayList<String>();
    one.add("x");
    one.add("y");
    one.add("y");
    one.add("z");
List<String> two = new ArrayList<String>();
    two.add("x");
    two.add("y");

1. Using Lambda
two.forEach((i)->one.remove(i));
System.out.println(one);

Output: [y, z]
2. Apache Commons
Collection<Integer> result = CollectionUtils.subtract(one, two);
System.out.println(one);

Output: [y, z]

A: This solution seems acceptable.
List<String> one = new ArrayList<>();
one.add("x");
one.add("y");
one.add("y");
one.add("z");
List<String> two = new ArrayList<>();
two.add("x");
two.add("y");

for (String s : two)
{
    one.remove(s);
}

System.out.println("one : " + one);

The output :

one : [y, z]

List.remove(Object o) documentation :

Removes the first occurrence of the specified element from this list, if it is present (optional operation). If this list does not contain the element, it is unchanged. More formally, removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))) (if such an element exists). Returns true if this list contained the specified element (or equivalently, if this list changed as a result of the call).

Note: The algorithm complexity is O(n*m), avoid to do it with 2 very big lists (where n and m are list size).

A: Check this:
    ArrayList<String> list1 = new ArrayList<String>();
    list1.add("Maria");
    list1.add("Nick");
    list1.add("Nick");
    list1.add("Joe");

    ArrayList<String> list2 = new ArrayList<String>();
    list2.add("Maria");
    list2.add("Nick");

    for (String x : list2) {
        int index = list1.indexOf(x);
        if (index >= 0) {
            list1.remove(index);
        }
    }


text:
Q: Error - could not start the command I have been getting the error of "could not start the command" whenever I run the texmaker.
I have worked on Latex before and it was working fine but now i can't get through it. I tried everything available online.
Also, now I can't make changes to my previous reports.
Can anyone help me with the same?


text:
Q: How to generate presigned S3 urls using django-storages? I have a Django form which saves a file to s3 through the django-storages library and works fine. How can I generate and return a pre-signed url so the user can access the file temporarily after it is uploaded ? Is this abstracted by django-storages or do I have to use the boto3 api?
I have spent hours going through the Django-storages documentation however it is not very clear how to do this ..
form.py
class DocumentForm(forms.Form):
    docfile = forms.FileField(
        label='Select a file',
        help_text='max. 42 megabytes'
    )
   name = models.CharField(max_length=20)
   uploaded_at = models.DateTimeField(auto_now_add=True)

views.py
def upload_file(request):
   if request.method == 'POST:
      form = DocumentForm(request.POST)
      if form.is_valid():
         form.save()
         url = #generate pre-signed url of uploaded file here
         return render(request, 'upload_response.html', url)

A: Turns out you do not need to use boto3 to generate a presigned url. Django-storages abstracts the entire process. You can simply generate it as follows docfile.url.
--- Edit ----
For reference, here is the S3 storage class method that generates the pre-signed url for you
https://github.com/jschneier/django-storages/blob/770332b598712da27ecdba75c9e202ad6a1a8722/storages/backends/s3boto3.py#L554

A: Here is sample code for generating pre-signed url for object in S3
import boto3

client = boto3.client('s3')
response = client.generate_presigned_url('get_object',Params={'Bucket': bucket_name,
                                                              'Key': objectpath},
                                         HttpMethod="GET", ExpiresIn=expires_in)


text:
Q: Hubot Basic Authentication REST Call With Hubot I am trying to access specific issues through JIRA REST api.
url = http://myserver.com/jira/rest/api/2/search?jql=status="open"+AND+assignee=null
robot.http(url).get() (err, res, body) ->
   # some code

Hubot fails to reach the server. Proxies are all set properly. The REST api works as expected through the browser once logged in.
Thus I need to specify authentication.
What I tried so far (plain basic authentication):
robot.http(url).auth('user', 'pass'). ...

robot.http(url).header('Authentication', 'user:password'). ...

robot.http('http://user:password@someurl'). ...

Hubot keeps telling me that the server was not found.
How do I properly pass authentication through http?

A: This is a snippet from hubot-confluence plugin It should be the same for authenticating with Jira. This is basic access authentication. You can look up the btoa method but what is does is convert binary to base64 encoded ascii. As far as I know there are already lots of scripts for connecting to Jira with hubot.
make_headers = ->
  user = nconf.get("HUBOT_CONFLUENCE_USER")
  password = nconf.get("HUBOT_CONFLUENCE_PASSWORD")
  auth = btoa("#{user}:#{password}")

  ret =
    Accept: "application/json"
    Authorization: "Basic #{auth}"

And you have it correct for making the robot.http call
headers = make_headers()
robot.http(url)
.headers(headers)
.get() (error, response, body) ->

A: you need to get the basic auth creds in the right format I think.
user = process.env.DNSIMPLE_USERNAME
pass = process.env.DNSIMPLE_PASSWORD
auth = 'Basic ' + new Buffer(user + ':' + pass).toString('base64')

then you need to pass the auth variable in
robot.http(url)
  .headers(Authorization: auth, Accept: 'application/json')
  .get() (err, res, body) ->
    #some code


text:
Q: Coldfusion dynamic query output Not sure if this is possible or not. What I am trying to do is build an output string via queries. I am concatenating the output "name" and appending the "value" to the end. Then outputting the string. I don't think this is possible. But I am looking for any alternatives.
So this is what I have:
qry1 is the main query. qry2 gets the value to append to the end of the string.
So the value of variable test would look like this: "variables.qry1.100"
Which would make sense to qry1 as this is part of the query object. So then this string would return a correct value from the database as there is a subquery called 100
<cfoutput>
<cfloop query="variables.qry2">
    <cfset test = variables.qry1. & variables.qry2.#valueID#>
#test#
</cfloop>
</cfoutput>

Many thanks.
JC

A: What your trying to do is possible, but you need to build a variable name first.
Instead of
<cfset test = variables.qry1. & variables.qry2.#valueID#>

Try
<cfset test = "variables.qry1.#variables.qry2.valueID#">

Test will then be variables.qry1.[valueID value]. Note that [valueID value] is what is getting returned from the query, so the actual value inside the variable.
Then to display the value of variables.qry1.[valueID value].
#evaluate(test)#

UPDATE As stated by Adam Cameron's answer. You should really try to avoid the evaluate() function, it's quite a performance hit and not considered good practice. Instead rather use the following code (This is copied from Adam Cameron's answer)
#variables.qry1[variables.qry2.valueID][1]#

NOTE: Go look at Adam Cameron's answer for a better description of whats going on.

A: So basically - given your example - you have a column in qry1 called 100 (etc, perhaps also 200, 300 etc), and the values 100, 200, 300 etc are row values in the valueID column of qry2? And qry1 is a single-row query? Is that right?
If you have the name of the column in a dynamic string, you use this syntax:
queryName[columnName][rowNumber]

Where queryName is the variable that is the query, columnName is the string holding the column name, and rowNumber is the row number (either an actual number, or a variable containing one).
So using your example variables, you code would be:
#variables.qry1[variables.qry2.valueID][1]#

There is no need to use evaluate() to do this, and it is not a good solution here. There is very seldom a need to use evaluate() in CFML, since the days of CF5.
I have no idea of the background of how your data structures came to be the way they are, but if you are needing to write the sort of code you are suggesting you need to... I'd be looking long and hard at how you're going about things.

A: Adam has the correct solution.  Here is a modified version of your original code that does what I think you are trying to do.
<cfoutput query="variables.qry1">

<cfloop query="variables.qry2">
    <cfset test = variables.qry1[variables.qry2.valueID][variables.qry1.currentrow]>
    #test#
</cfloop>

</cfoutput>


text:
Q: Two levels deep one-to-many relationship with contains() I have two tables like so
class Department(Model):
    id = Column(Integer, primary_key=True)
    employees = relationship('Employee', backref='department')

class Employee(Model):
    id = Column(Integer, primary_key=True)
    name = Column(String)
    department_id = Column(Integer, ForeignKey('department.id'))
    email_addresses = relationship('EmailAddress', backref='employee')

class EmailAddress(Model):
    id = Column(Integer, primary_key=True)
    value = Column(String)
    employee_id = Column(Integer, ForeignKey('employee.id'))

And now I need to find all departments that have an employee with an email address of X.
Back when each employee was allowed to have only one email address (so they had email_address = Column(String) I used this code, but I'm not sure how to extend it to work with multiple emails:
session.query(Department).filter(
    Employee.email_address==request.args['email']
).outerjoin((Employee, Department.employees))

A: You can use the any() method of relationship. This code should do it:
session.query(Department).filter(
    Employee.email_address.any(value=request.args['email'])
).outerjoin((Employee, Department.employees))

A: You could use any() like this :
department1 = Department()
department2 = Department()
DBSession.add(department1)
DBSession.add(department2)
employee = Employee()
employee.email_addresses.append(EmailAddress(employee.id, 'e@mail.com'))
DBSession.add(employee)
department1.employees.append(employee)
DBSession.flush()
print(DBSession.query(Department).filter(Department.employees.any(Employee.email_addresses.any(EmailAddress.value == 'e@mail.com'))).all())

see this gist for a full example.


text:
Q: Flutter firebase authentication login success no matter if the user is in the database If I try to fill TextFormFields responsible for email and password and submit, the login procedure gonna be success always.. no matter if user is in firebase authentication field. I've done login and register pages before with firebase working perfectly. Only diffrence was using pushNamed instead pushReplace. Should it do difference?
That's form inkwell onTap :
onTap: () {
                                      final formState = _formkey.currentState;
                                      if (formState.validate()) {
                                        formState.save();

                                        signIn(_email, _password).whenComplete(
                                            () => Navigator.of(context)
                                                    .pushReplacement(
                                                        MaterialPageRoute(
                                                  builder: (context) =>
                                                      HomePage(),
                                                )));
                                      }
                                    }

and authentication:
FirebaseAuth _auth = FirebaseAuth.instance;
Future<void> signIn(String _email, String _password) async {
  try {
    UserCredential user = await _auth.signInWithEmailAndPassword(
        email: _email, password: _password);
  } on FirebaseAuthException catch (e) {
    print('error');
  }
}

Email/password sign-in method is turn on.
How to fix this problem and allow to log in only users that exist in firebase?


text:
Q: Generators + Promises explanation I've been studying Promises and Generators but I got stuck in the script below:
function getFile(file) {
    return new Promise(function (resolve) {
        fakeAjax(file, resolve);
    });
}

function* getFiles() {
    var p1 = getFile('file1');
    var p2 = getFile('file2');
    var p3 = getFile('file3');

    output(yield p1);
    output(yield p2);
    output(yield p3);
}

function runner(gen) {
    var g = gen();
    function run(val) {
        val || undefined;
        var next = g.next(val);
        if(!next.done && !next.value !== undefined) {
            next.value
                .then(function(v) {
                    run(v);
                });
        }
    }
    run();
}

runner(getFiles);

What I'm trying to figure it out is what happens when I get to the first yield on getFiles? Why does this code work, I don't get it.
*EDIT: output is simply a console.log wrappend in a function. The fakeAjax function returns a text from an object based on the 'file' requested.

A:
What I'm trying to figure it out is what happens when I get to the first yield on getFiles? Why does this code work, I don't get it.

yield does three things:

*

*It pause the execution of the generator function

*It defines the value the caller of next() will receive in the value property. In this case, that's the promises you made.

*It optionally acts as an expression with the value passed into next(). That will be the file name you passed as a argument to next().

yield is like a two-way conduit, both accepting values and passing values.
In your code at the first yield it will return the object with the promise and pause, but it doesn't log anything to the console at this point — yield can pause mid-expression. When you call next() again it will finish the console.log and then move to the next yield. It can be a little confusing because there is usually one more call to next that there are yields. For example in this code `next is called four times and that's why you get the last console.log.
Here's an MCVE that I assume approximates the undefined functions in your example:

function getFile(file) {
    return new Promise(resolve => setTimeout(() => resolve(file), 1000))
}

function* getFiles() {
    var p1 = getFile('file1');
    var p2 = getFile('file2');
    var p3 = getFile('file3');

    console.log(yield p1); // return promise, then pause, then log value passed to next()
    console.log(yield p2);
    console.log(yield p3);
}

function runner(gen) {
    var g = gen();
    function run(val) {
        var next = g.next(val);
        if(!next.done && !next.value !== undefined) {
            next.value
                .then(function(v) {
                    run(v);
                });
        }
    }
    run();
}

runner(getFiles);


text:
Q: Oracle parameterized SQL using IN clause with multiple values not working I have an parameterized SQL statement that uses the IN clause in order to update multiple records with one query. It is an integer field, the RID (record ID), to do the update. If I pass only one RID it works but if I pass multiple values I get Error: ORA-01722: invalid number.
This is the code:
sbQuery.Append("update EXC_LOG set supv_emp_id=:userId, status=:exceptionStatus, supv_comments=:exceptionComment ");
sbQuery.Append("where RID in (:rid)");
ctx.Database.ExecuteSqlCommand(sbQuery.ToString(),
                                new OracleParameter("userId", UserId),
                                new OracleParameter("exceptionStatus", exceptionStatus),
                                new OracleParameter("exceptionComment", comment),
                                new OracleParameter("rid", rid));

If I pass in one value RID it works but if I pass in multiples comma separated (ex: 1234,5566,8899) I get the Invalid Number error.
How can I pass in multiple integer values when using parameters?

A: You are passing a single string argument in to IN(). If that happens to contain a single number then you're effectively doing:
where RID in ('12345')

which is processed with an implicit conversion, since your RID column is numeric, as:
where RID in (to_number('12345'))

which is fine. But with multiple values in a single string argument you're really trying to do:
where RID in (to_number('12345,5566,8899'))

and to_number('12345,5566,8899') will throw ORA-01722: invalid number.
There are various ways to unpack a delimited string into individual values but a simple one is by treating them as an XPath sequence and putting them through an XMLTable call:
sbQuery.Append("where RID in (select RID from XMLTable(:rid columns RID number path '.'))");

As a demo of that approach, first how the XMLTable call expands the string using a SQL*Plus bind variable:
var rid varchar2(30);

exec :rd := '12345,5566,8899';

select RID from XMLTable('12345,5566,8899' columns RID number path '.');

       RID
----------
     12345
      5566
      8899

and then in a dummy query against a dummy table:
with EXC_LOG (RID, SUPV_EMP_ID, STATUS, SUPV_COMMENT) as (
            select 12345, 123, 'OK', 'Blah blah' from dual
  union all select 8899, 234, 'Failed', 'Some comment' from dual
  union all select 99999, 456, 'Active', 'Workign on it' from dual
)
select *
from EXC_LOG
where RID in (select RID from XMLTable('12345,5566,8899' columns RID number path '.'));

       RID SUPV_EMP_ID STATUS SUPV_COMMENT
---------- ----------- ------ -------------
     12345         123 OK     Blah blah
      8899         234 Failed Some comment

Your code will just do an update instead of a select, using the same filter.


text:
Q: What are strings really in .NET? Is a string actually a character array (is-a), or does it have a character array as an internal store (has-a), or is it's own object which can expose itself as a with an array of characters?
I am more inclined to say it is it's own object, but then why are we so inclined to always say "A string is an array of characters..."?

A: It depends on your definition of the word "string".
System.String type in .NET has a character array as internal store (it also stores length (which is O(1)), among other things, for example).
But the word string means a consecutive occurrence of something in general, which might also mean a character array :))
By the way, when I said string type has a "character array," I didn't mean "a field of type char[]" specifically. I meant the general meaning of the term "array" as an ordered collection of something. :))

A: the .NET string is not just an array of characters. It contains an array of characters, so strictly speaking, it's has-a.
Moreover, there are a lot of Unicode-related subtleties where it doesn't behave anything like an array. Concatenating a character may do a lot more than just increase the string length by one, and insert the new character at the end. According to the Unicode normalization rules, it may actually change the entire string. So it is definitely nothing like an array of characters, but somewhere within the class, such an array exists.

A: The semantic meaning of string is the second.
The .Net String class maintains an internal store (has-a) and can expose that store in as many abstract ways as the designers choose.
The question is like "Is an Apple a red round thing? Because I always thought it was a fruit."

A: MSDN : The string type represents a string of Unicode characters.
This mean : it's an array of Unicode character.

A: In an abstract way (and I guess, when laid out in memory) - it is an array of characters.
Correct me, if I am wrong in thinking that.

A: String is a name of a class.  It has different meanings in different languages.  It could be unicode or ASCII internally meaning it's storage mechanism is a series of bytes.  This class provides functions for manipulating it's own internal storage and it is not meant to be directly accessed and modified due to the fact that it could contain characters in a variety of different encodings.  So for the purpose of your question, it has-a byte store.

A: It depends on the language and implementation.  On a most basic level (ascii char* string) it is a sequential series of memory addresses each of which contain a short int corresponding to a ascii code and terminated by null (char(0)).  Most higher level languages provide a string object which has a character array as well as convenience methods because working with char* strings is more or less a pain in the rear.

A: Depends on exactly how you look at it.  If you pin it with a GCHandle and then look at the memory where it resides, you're see it's actually a 32-bit length descriptor followed immediately by an array of unicode characters (be aware that AddrOfPinnedObject will give you the address of the first character, not the length.  If it gave the address of the length it would be far less useful for P/Invoking).

A: Functionally, a string is a list, or sequence, of characters.  Strings are often stored transparently as character arrays (e.g., in C), so we often refer to them that way.  Arrays allow convenient random access to the characters, which is important for some algorithms.
For other purposes, though, storing Unicode strings as UTF-8 might be the most appropriate form.  Note that, although it's stored in a byte array, there's no longer a one-to-one correspondence between bytes and characters:  your string algorithms generally need to access the characters sequentially from the beginning -- as a list.
The moral of this story is:  your string code should only demand random access if it actually needs it.  You might be surprised how seldom you really need an array of characters.


text:
Q: regex: matching same expression unknown number of times With the help of some of the guys here I have some regex to match strings in quotes that aren't in brackets:
"one" - matches
("two") - doesn't match

Is it possible to repeat the match so the input:
"one" ("two") "three"

would return one and three? The only thing I can think of doing is capturing whatever is left over and reprocessing with the same regex, i.e:
process > "one" ("two") "three" - returns one and "("two") "three""
process > ("two") "three"       - returns failed and "three", not sure how but hey
process > "three"

I'm learning regex at the moment so just wondering if this functionality is built in?
NB: this may be a repeat of refering to already existing group in regex, c# but not clearly enough for me to follow :(.

A: You need the Regex.Matches() function which returns all of the substrings that match the regex.


text:
Q: How to display limited number of tags post? I have a post with tags:b1,b2,b3. But in the category template, I want to show only 2 tags for the post:b1,b2. How can I do it ?
Now I use the following code to display tags of the post:
<?php
$posttags = get_the_tags();
if ($posttags) {
    foreach($posttags as $tag) {
        echo '
' .$tag->name. '
';
    }
}
?>

What I want to:

A: Updated: Going back to foreach() with a break in it.
<?php
$posttags = get_the_tags();
if($posttags){
    foreach($posttags as $index=>$tag){
        echo '
' .$tag->name. '
'; // echos while $index == 0 & 1
        if($index>0){break;}  // second iteration ($index==1) breaks the loop
    }
}
?>

Or if the $posttags array does not use numerical keys, you create your own iteration counter:
if($posttags){
    $x=0;
    foreach($posttags as $tag){
        echo '
' .$tag->name. '
';
        if(++$x==2){break;}  // increment and test $x (first $x=1, second $x=2 so break)
    }
}


text:
Q: Integral of $\sin (e^{x^2})e^{-x^2+ix\lambda}$ Trying to solve this problem :

Is $T$ invariant under Fourier transform ? Where : $T= \{f\in \mathcal{C}^{\infty} (\mathbb{R}), \forall n \in \mathbb{N}, |x|^nf(x) \to 0 \; \text{when}\; |x| \to \infty \}$

My answer is no, and here is what I've already done :
Let $f : x \mapsto e^{-x^2} \sin (e^{x^2})$. We can easily check that $f \in T$. Now : $$\hat{f}(\lambda)= \int_{- \infty}^{\infty} e^{-x^2}\sin (e^{x^2})e^{-ix\lambda}\mathrm{d}x$$
Thus by Riemann-Lebesgue's theorem we have $\hat{f}(\lambda) \to 0$ when we let $\lambda \to \infty$, but I am pretty sure that $\hat f \notin T$. To show that I tried to show that : $$\lambda \hat f (\lambda)$$ is not wanishing to $0$, but I remain not able to prove this.
Can anyone help ? Or if anyone has a better example (more simple) of $f \in T$ such that $\hat f \notin T$ I am taking it !