text:
Q: How can I avoid the Windows _exec* and _spawn* functions splitting arguments at spaces? While using the _execv() function in a C++ Windows console program, I found that the arguments are split at spaces, with each substring becoming a separate argument in the arguments list of the exec'd program. Presumably, this is not happening until after that program is found, as it is being found even when the program path argument contains spaces.
I have written a pair of programs that demonstrate the problem. The same thing happens with _spawnv(), and also if I modify the calling program to use wchar_t arrays and _wexecv().
I am building the examples as either x86 or x64 windows console application projects, using Visual Studio 2017 on Windows 10. How can I avoid this problem while using one of these functions?
// Calling program

#include "pch.h"
#include <iostream>
#include <process.h>

int main()
{
    const char program[] = "C:\\Users\\dummy\\Documents\\Visual Studio 2017\\Projects\\execTest\\x64\\Debug\\testCalled.exe";
    const char* arguments[] = { program, "Hello   World!", nullptr };   // Note the multiple spaces

    for (int a = 0; sizeof(arguments) / sizeof(*arguments) > a && arguments[a]; ++a) {
        std::cerr << "Caller: " << a << " = " << arguments[a] << '\n';
    }
    std::wcerr << '\n';

    auto rc = _execv(program, arguments);

    perror("Exec fail ");
    std::cerr << "return code " << rc <<'\n';
    return rc;
}

// Called program

#include "pch.h"
#include <iostream>

int main( int argc, char** argv)
{
    for (int a = 0; a < argc; ++a) {
        std::cerr << "Called: " << a << " = " << argv[a] << '\n';
    }
    return 0;
}

Output:
Caller: 0 = C:\Users\dummy\Documents\Visual Studio 2017\Projects\execTest\x64\Debug\testCalled.exe
Caller: 1 = Hello   World!

Called: 0 = C:\Users\dummy\Documents\Visual
Called: 1 = Studio
Called: 2 = 2017\Projects\execTest\x64\Debug\testCalled.exe
Called: 3 = Hello
Called: 4 = World!

A: On Unix-like systems, execve is the system call that allows a program to erase itself with a different one, which receives separately the arguments, and the exec family function directly call it.
On Windows, the system API define the CreateProcess function which uses the name or path of the new program (as execve does) and a single command line which is built by joining the parameters of exec.
That means that you have to enclose the parameters containing spaces in explicit double quotation marks. So the Windows way is indeed:
const char* arguments[] = { program, "\"Hello   World!\"", nullptr };

The C standard does not define an execv function, it is only defined in Posix and Windows, despite trying to be compatible is not a Posix system, so caveats are to be expected...

A: (edit: avoid using _execv in Windows as explained in comments)
To fix the usage for _execv, set the first argument to the exact path. Then modify the second parameter (arguments) so the path name is in double quotes (as well as other arguments which are broken with blank space):
char program[] = "c:\\foler name\\path name.exe";

char *arguments[] = {
        "\"c:\\foler name\\path name.exe\"",
        "\"(x 1)\"",
        "\"(x 2)\"",
        nullptr
};

_execv(program, arguments);

Now the recipient should see argv[0] as "c:\\foler name\\path name.exe", argv[1] as "(x 1)" ...
You can also use CreateProcess and put program name and arguments in one line.
#include <windows.h>
...

std::string cmd;
cmd += "\"c:\\folder name\\path name.exe\" "; //<- add extra space manually
cmd += "a "; //<- add extra space manually
cmd += "b c d ";
cmd += "\"Hello   World!\" "; //<- add extra space manually

STARTUPINFOA si = { sizeof(si) };
PROCESS_INFORMATION pi;
CreateProcessA(0, cmd.data(), 0, 0, 0, 0, 0, 0, &si, &pi);
//* if cmd.data() is not supported then copy to char buffer

//optional: wait until process is finished
//WaitForSingleObject(pi.hProcess, INFINITE);
//CloseHandle(pi.hProcess);
//CloseHandle(pi.hThread);

See also
Parsing C++ Command-Line Arguments


text:
Q: Annotation processors works incorrectly when target directory already presents. Is there any solution except remove target dir? I am using annotation processors for compile time validation and code generation (with help of Javapoet), Apache Maven, Intellij Idea.
When I am running my app for the "first time" (when target directory not generated yet after it's removal or mvn clean command execution) everything is works as it should.
But, if I'll change somemething in code, for example to trigger some validation case - it shows random validation errors. If I'll remove target directory - everything works fine.
Little bit of context. For example I have such code, with is annotated with my custom annotations:
@ActionSequenceConfiguration(
        name = CAT_WASH_SEQUENCE,
        actions = {
                WATER_SUPPLIER_ACTION,
                SOAP_SUPPLIER_ACTION,
                TOY_SUPPLIER_ACTION,
                WASH_CAT_ACTION
        }
)
ActionSequence getCatWashSequence(@InitialParam(CAT_PARAM) Cat cat);

One of annotation processors checks, if all actions with names provided into ActionSequenceConfiguration are exist. So if I will change any code, which is not related to actions and their presence - I'll get false error (it will not happen if target dir doesn't exists or removed).
UPD: as suggested in comments, it should be problem in compiled files and classes. Is this problem common for all annotation processors?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Armadillo and OpenMP and stack-use-after-scope I have an issue with a stack-use-after-scope with error with the C++ Armadillo library within an OpenMP blog in an R package and I cannot figure out what is wrong. The complete gcc log is here from the CRAN GCC ASAN check of the R-package. I have have kept the relevant part of the log below
==33791==ERROR: AddressSanitizer: stack-use-after-scope on address 0x7ffd03364940 at pc 0x7ff8127abc07 bp 0x7ffd03364680 sp 0x7ffd03364670
WRITE of size 4 at 0x7ffd03364940 thread T0
    #0 0x7ff8127abc06 in arma::Mat<double>::Mat(double*, unsigned int, unsigned int, bool, bool) /data/gannet/ripley/R/test-3.5/RcppArmadillo/include/armadillo_bits/Mat_meat.hpp:1215
    #1 0x7ff8129fb0c2 in GMA<logistic>::solve() [clone ._omp_fn.0] /data/gannet/ripley/R/test-3.5/RcppArmadillo/include/armadillo_bits/Col_meat.hpp:411
    #2 0x7ff825ae2cde in GOMP_parallel (/lib64/libgomp.so.1+0xdcde)
    #3 0x7ff812a0c9f8 in GMA<logistic>::solve() ddhazard/GMA_solver.cpp:83
    #4 0x7ff81276421d in ddhazard_fit_cpp(...

Address 0x7ffd03364940 is located in stack of thread T0 at offset 416 in frame
    #0 0x7ff8129fa82f in GMA<logistic>::solve() [clone ._omp_fn.0] ddhazard/GMA_solver.cpp:83

  This frame has 5 object(s):
    [32, 40) 'dest'
    [96, 104) 'src'
    [160, 176) 'ans'
    [224, 384) 'my_X_cross'
    [416, 576) '<unknown>' <== Memory access at offset 416 is inside this variable
HINT: this may be a false positive if your program uses some custom stack unwind mechanism or swapcontext
      (longjmp and C++ exceptions *are* supported)
SUMMARY: AddressSanitizer: stack-use-after-scope /data/gannet/ripley/R/test-3.5/RcppArmadillo/include/armadillo_bits/Mat_meat.hpp:1215 in arma::Mat<double>::Mat(double*, unsigned int, unsigned int, bool, bool)
Shadow bytes around the buggy address:
  0x1000206648d0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x1000206648e0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x1000206648f0: 00 00 00 00 f1 f1 f1 f1 00 f2 f2 f2 f2 f2 f2 f2
  0x100020664900: 00 f2 f2 f2 f2 f2 f2 f2 f8 f8 f2 f2 f2 f2 f2 f2
  0x100020664910: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>0x100020664920: 00 00 00 00 f2 f2 f2 f2[f8]f8 f8 f8 f8 f8 f8 f8
  0x100020664930: f8 f8 f8 f8 f8 f8 f8 f8 f8 f8 f8 f8 f3 f3 f3 f3
  0x100020664940: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x100020664950: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x100020664960: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x100020664970: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 f1 f1
Shadow byte legend (one shadow byte represents 8 application bytes):
  Addressable:           00
  Partially addressable: 01 02 03 04 05 06 07
  Heap left redzone:       fa
  Freed heap region:       fd
  Stack left redzone:      f1
  Stack mid redzone:       f2
  Stack right redzone:     f3
  Stack after return:      f5
  Stack use after scope:   f8
  Global redzone:          f9
  Global init order:       f6
  Poisoned by user:        f7
  Container overflow:      fc
  Array cookie:            ac
  Intra object redzone:    bb
  ASan internal:           fe
  Left alloca redzone:     ca
  Right alloca redzone:    cb
==33791==ABORTING

The WRITE that causes the error is in the dynamichazard/src/ddhazard/GMA_solver.cpp and particularly this OpenMP block
#ifdef _OPENMP
      int n_threads = std::max(1, std::min(omp_get_max_threads(),
                                           (int)r_set.n_elem / 1000 + 1));
#pragma omp parallel num_threads(n_threads) if(n_threads > 1)
{
#endif
      arma::mat my_X_cross(q, q, arma::fill::zeros);

#ifdef _OPENMP
#pragma omp for schedule(static)
#endif
      for(arma::uword i = 0; i < r_set.n_elem; i++){
        auto trunc_eta = T::truncate_eta(
          is_event[i], eta[i], exp(eta[i]), at_risk_length[i]);
        h_1d[i] =  w[i] * T::d_log_like(
          is_event[i], trunc_eta, at_risk_length[i]);
        double h_2d_neg = -  w[i] * T::dd_log_like(
          is_event[i], trunc_eta, at_risk_length[i]);
        sym_mat_rank_one_update(h_2d_neg, X_t.unsafe_col(i), my_X_cross);
      }

#ifdef _OPENMP
#pragma omp critical(gma_lock)
{
#endif
      X_cross += my_X_cross;

#ifdef _OPENMP
}
}
#endif

As far as I can tell, the error is at the X_t.unsafe_col(i) call in the call to sym_mat_rank_one_update. The declaration of the function is
void sym_mat_rank_one_update(const double, const arma::vec&, arma::mat&);

It should trigger a call to the arma::col<double> constructor in line 411 of include/armadillo_bits/Col_meat.hpp which inherit the arma::mat<double> constructor in line 1215 of include/armadillo_bits/Mat_meat.hpp. I gather this is where the 4 bit write occurs with one of the unsigned int since the arma::mat<double> constructor is
template<typename eT>
inline
Mat<eT>::Mat(eT* aux_mem, const uword aux_n_rows, const uword aux_n_cols, const bool copy_aux_mem, const bool strict)
  : n_rows   ( aux_n_rows                            )
  , n_cols   ( aux_n_cols                            )
  , n_elem   ( aux_n_rows*aux_n_cols                 )
  , vec_state( 0                                     )
  , mem_state( copy_aux_mem ? 0 : ( strict ? 2 : 1 ) )
  , mem      ( copy_aux_mem ? 0 : aux_mem            )
  {
  arma_extra_debug_sigprint_this(this);

  if(copy_aux_mem == true)
    {
    init_cold();

    arrayops::copy( memptr(), aux_mem, n_elem );
    }
  }

where
template<typename eT>
class Mat : public Base< eT, Mat<eT> >
  {
  public:

  typedef eT                                elem_type;  //!< the type of elements stored in the matrix
  typedef typename get_pod_type<eT>::result  pod_type;  //!< if eT is std::complex<T>, pod_type is T; otherwise pod_type is eT

  const uword  n_rows;    //!< number of rows     (read-only)
  const uword  n_cols;    //!< number of columns  (read-only)
  const uword  n_elem;    //!< number of elements (read-only)
  const uhword vec_state; //!< 0: matrix layout; 1: column vector layout; 2: row vector layout
  const uhword mem_state;
  ...

See include/armadillo_bits/Mat_bones.hpp and notice that arma::uword is unsigned int. However, I cannot figure out why this would cause a stack-use-after-scope.
A similar error is in the Morpho package. See the current CRAN log here and src/createL.cpp.
Setup
The above check is on CRAN. As far as I can tell, it is with gcc 7.2 on Fedora 26 with the following config.site used to build R
CXX="g++ -fsanitize=address,undefined,bounds-strict -fno-omit-frame-pointer"
CFLAGS="-g -O2 -Wall -pedantic -mtune=native -fsanitize=address"
FFLAGS="-g -O2 -mtune=native"
FCFLAGS="-g -O2 -mtune=native"
CXXFLAGS="-g -O2 -Wall -pedantic -mtune=native"
MAIN_LDFLAGS=-fsanitize=address,undefined

Further, the following ~/.R/Makevars is used
CC = gcc -std=gnu99 -fsanitize=address,undefined -fno-omit-frame-pointer
F77 = gfortran -fsanitize=address
FC = gfortran -fsanitize=address
FCFLAGS = -g -O2 -mtune=native -fbounds-check
FFLAGS = -g -O2 -mtune=native -fbounds-check

The error does not happen with clang 5.0.0 and valgrind on the same machine. Further, I cannot reproduce them on a local Ubuntu 17.04 with gcc version 6.3 and clang version 4.0.0.
Minimal, Complete, and Verifiable example
I will work on making one.


text:
Q: Testing EF data access with a Test DB data access I've done some of research today but I've not found any appropriate answer to my question.
I've inherited an ASP.NET MVC project where there's no sign of unit test. I've created all my repository using DI and I've separated the logic business from the data access (almost everywhere)
Now I was writing the unit tests that should be related to DB manipulation (before downvoting I don't want to test LINQ to Object since the behavior from Linq to SQL can be different, what approach do you use? Do you use a DB replicated from some test environment when I've to test or do you use an in-memory DB? (SQL Express for example?)
Consider the case I've to test an insert in a table where I've got a constraint in the name, testing in SQL to Object wouldn't fail. I was evaluating to have a SqlServer express filled with the data I need to perform the test, for example, if I need to test Customer and Orders with those 2 columns filled) but this would mean that I'll have to create a lot of SQL Server instances to handle all my tests.
What's the best approach?
Thanks
UPDATE 1
Example of an insert Method I've
 public bool InsertUteCliente(UteCliente uteCli)
    {

        UPC upc = new UPC();
        upc.IdUtente = uteCli.idUte;
        upc.CodiceCliente = GetCodCliente(uteCli.id);
        upc.AnagraficaVitaEnable = uteCli.AnagVita;
        upc.AnagraficaRSMEnable = uteCli.AnagRSM;
        upc.AnagraficaInfortuniEnable = uteCli.AnagInfo;
        upc.AnagraficaIPMEnable = uteCli.AnagIPM;
        upc.PolizzaVitaEnable = uteCli.PolVita;
        upc.PolizzaRSMEnable = uteCli.PolRSM;
        upc.PolizzaInfortuniEnable = uteCli.PolInfo;
        upc.PolizzaIPMEnable = uteCli.PolIPM;
        upc.ConsuntiviEnable = uteCli.IfConsuntivi;
        upc.RinnoviEnable = uteCli.IfRinnovi;
        upc.IncEscEnable = uteCli.IfIncEsc;
        upc.PremiVisible = false;
        upc.EstrazionePremiVisibile = uteCli.IfEstrazionePremi;

        dbContext.UPC.Add(upc);

        dbContext.SaveChanges();

        return true;
    }

How should I test it?


text:
Q: Running a multi-stage job using SLURM I am new to SLURM. My problem is that I have a multi-stage job, which needs to be run on a cluster, whose jobs are managed by SLURM. Specifically I want to schedule a job which:

*

*Grabs N nodes,

*Installs a software on all of them

*(once all nodes finish the installation successfully) it creates a
database instance on the nodes

*Loads the database

*(once loading is done successfully) Runs a set of queries, for benchmarking purpose

*Drops the database and returns the nodes

Each step could be run using a separate bash script; while the execution of the scripts and transitions between stages are coordinated by a master node.
My problem is that I know how to allocate nodes and call a single command or script on each (which runs as a stand-alone job on each node) using SLURM. But as soon as the command is done (or the called script is finished) on each node, the node returns to pool of free resources, leaving the allocated nodes queue for my job. But the above use case involves several stages/scripts; and needs coordination between them.
I am wondering what the correct way is to design/run a set of scripts for such a use case, using SLURM. Any suggestion or example would be extremely helpful, and highly appreciated.

A: You simply need to encapsulate all your scripts into a single one for submission:
#!/bin/bash
#SBATCH --nodes=4 --exclusive

# Setting Bash to exit whenever a command exits with a non-zero status.
set -e
set -o pipefail

echo "Installing software on each of $SLURM_NODELIST"
srun ./install.sh

echo "Creating database instance"
./createDBInstance.sh $SLURM_NODELIST

echo "Loading DB"
./loadDB.sh params

echo Benchmarking
./benchmarks.sh params

echo Done.

You'll need to fill in the blanks... Make sure that your script follow the standard of exiting with a non-zero status on error.


text:
Q: How to get a list of indexes from list of counts? Given an input sequence:
Array[Int] = Array(0, 1, 0, 2, 1, 0)

I want a list that gives me indexes of each entry times, the number of times for each entry in the sequence. The output here would be:
Array[Int] = Array(1, 3, 3, 4)

There is one instance of index 1, two instances of index 3, one instance of index 4. How can write a function to do this in scala?
Here is one attempt, but I
val func1 = (cnt: Int, idx: Int) => Array.fill(cnt)(idx)
countarray.zipWithIndex.map(func1)

func1: (Int, Int) => Array[Int] = <function2>
<console>:132: error: type mismatch;
 found   : (Int, Int) => Array[Int]
 required: ((Int, Int)) => ?
              seq_of_vectors.map(_.numNonzeros).zipWithIndex.map(func1)

A: You're quite close.
arr.zipWithIndex.flatMap{case (rep,idx) => Array.fill(rep)(idx)}

Use flatMap() so that all the intermediate Arrays will be flattened into one Array result.


text:
Q: What is the best way to include cards images in my app? I'm writing an android app in java and in one of my activities I want to use a pack of 52 cards, and display a few of them randomly. Do I need to download and keep 52 images or is there other way of doing it?
I want to display different cards, randomly chosen. How can I get those images?

A: I can think of 3 ways of doing this:

*

*Have a different image file for each card.

*Have one large image of all cards and only draw a part of the image for each card.

*Build the image of a card having several small images of the parts of a card.

If you're looking to save space on the device I would suggest number 3.
You would need images of the 4 suits, the faces(J,Q,K) and the blank card. The numbers and letters could simply be written in red and black.


text:
Q: How do I change Bootstrap 3's glyphicons to white? I've got the glyphicons in my page, but they are black. How do I set the glyphicons to white?

A: You can just create your own .white class and add it to the glyphicon element.
.white, .white a {
  color: #fff;
}

<i class="glyphicon glyphicon-home white"></i>


text:
Q: Bootstrap, using nested grid to show a title and form buttons in a card-header I have a nested card header and would like to display my title, and two form + submit buttons (edit, delete) in a row.  (The forms are only submit buttons)  The first example works fine, but I need to use forms and a nested submit button instead of just buttons.  That is shown in the second block.  The submit buttons have a margin issue, I'm guessing from being nested within the form element.  Perhaps I am going about this the wrong way.
visual of what happens

                            myThreadTitle

                        <button class="col-md-1 btn btn-warning btn-sm rounded-0">
                            Edit
                        </button>
                        <button class="col-md-1 btn btn-warning btn-sm rounded-0">
                            Delete
                        </button>

                            {{ $thread->title }}

                            <form
                                action=""
                                method="POST"
                            >
                                <button
                                    type="submit"
                                    class="btn btn-danger btn-sm rounded-0"
                                >
                                    Delete
                                </button>
                            </form>


text:
Q: Python's readline() function seeming not to work? for some reason the readline() function in my following code seems to print nothing.
fileName = input()
    fileName += ".txt"
    fileA = open(fileName, 'a+')
    print("Opened", fileA.name)

    line = fileA.readline()
    print(line)
    fileA.close()

I'm using PyCharm, and I've been attempting to access 'file.txt' which is located inside my only PyCharm project folder. It contains the following:
Opened file!!

I have no idea what is wrong, and I can't find any relevant information for my problem whatsoever. Any help is appreciated.

A: Because you opened the file in a+ mode, the file pointer starts at the end of the file. After all, that is where you would normally append text.
If you want to read from the top, you need to place fileA.seek(0) just before you call readline:
fileA.seek(0)
line = fileA.readline()

Doing so sets the pointer to the top of the file.

Note: After reading the comments, it appears that you only need to do this if you are running a Windows machine.  Those using a *nix system should not have this problem.


text:
Q: How would I create a Workflow? I have two library(Current and Review Library) in one site collection and one archive library in another site collection.
Requirements:
The system will immidiatlly remove the document from the current document grid and place it into a queue for Document review.The fololowing required will happen.
If:
     A- Duplicate document
     B- Document Name incorrectly
     C- Incorrect workspace
     D- Others(If others is selected , then comment field is required)

Note: Remove means to move a document from the current document grid to the drop-off library.


text:
Q: create new cell array using two differently sized source arrays and matching the serial numbers I have an array with a set of chronological serial numbers and another source array with random serial numbers associated with a numeric value. I wish to create a new cell array in MATLAB with the perfectly chronological serial numbers in one column and in the next I wish to insert the associated numeric value if the serial numbers match in both original source arrays. If they don't I simply want to copy the previous associated value until there is a new match.
For example
source input (serial)
1
2
3
4
5
6
7

source input (random)
1    100
2    105
4    106
7    107

desired output (data)
SR No           Value
1               100
2               105
3               105
4               106
5               106
6               106
7               107

Right now, the problem I have is that whenever I run the code below, I end up with empty cell values where there should be repeated values inserted by a (correctly working) program, i.e. in rows with serial numbers 3, 5-29, etc.
Here's the code I've got so far:
j = 1;
A = {serial{1:end,1}};
B = cell2mat(A);
value = random(1,2);
data(:,1) = serial(:,1);

for k = 1:length(random)

    [row, col, vec] = find(B == random{k,1});
    tf = isempty(vec);

    if (tf ~= 1)
        value = random(row,2);
        data(j,2) = random(row,2);
        j = j + 1;
    else
        data(j,2) = value;
        j = j + 1;
    end
end

How do I create this cell array without the empty values?
Note: Serial Values may be repeated in some cases - these are duplicates that cannot (or should not) be removed, but may need to be ignored by the program to avoid infinite loops.
Any suggestions on how to accomplish this would be appreciated.

A: Something like that?
serial = {1,2,3,4,5,6,7};
random = {1,100; 2, 105; 4, 106; 7, 107;};

data(:,1) = cell2mat(serial)';
data(:,2) = NaN;

for k=1:size(random,1)
    data(data(:,1)==random{k,1},2) = random{k,2};
end
for k=2:size(data,1)% what if there is no value for first serial number?
    if isnan(data(k,2))
        data(k,2) = data(k-1,2);
    end
end
disp(data)

BTW: I recommend you not to use MATLAB function name as a your variable name (i.e. random in your code).


text:
Q: How to create an object I am new in js. I am trying to understand how to use "this" correctly. I want to create an object with a behaviour. When the object created, the person is given a name and length of his step.
My question is how I can save the quantity of steps inside the function? how to do it correctly without losing context, because my this always looks to the global object.

A: You can either use a function (not an arrow function) or a class. I have added a code sample of how you can create objects using function
function Person(name) {
    this.name = name;
    this.step =1;
    this.stepIncrease = function() {
        this.step++;
    }
    this.summary = function () {
    return this.step;
    }
}
const person = new Person("john");

A: You need to create a function that will return the person's object. Then, to create a new object, you can use the new keyword and call the function. This will create an object on the fly and assign the this pointer to the object itself.
Things to note about the this:

*

*If a function is called with .call(), .apply() or .bind(), this will be the object that is passed inside the call/apply/bind.

*If a function is called on an object e.g. obj.foo(), this will be the object it was called on.

*If a function is called on its own, foo(), this will be either undefined (strict mode) or the global object (non-strict mode)

function Person(name, step=1) {
    return {
        name,
        step,
        stepIncrease: function() {
            this.step++;
            return this;
        },
        summary: function() {
            console.log(this.step);
        }
    }

}

const john = new Person('John');
john.stepIncrease();
console.log(john);

A: with Class
class Person {
  name = "";
  step = 1;

  stepIncrease() {
    this.step++;
  }

  summary() {
    console.log(this.step);
  }
}

const person1 = new Person();
for(let i = 0; i < 5; i++) {
  person1.stepIncrease();
}
person1.summary();


text:
Q: Error using link_to with to_sentence I have some problems using link_to with to_sentence in Rails.
Using this line of code the html output is wrong.
<%= @story.collections.map{ |u| link_to(u.name, collection_path(u)).html_safe }.to_sentence %>

This code is rendered as text on the page rather than the links
One, Two, and Three

This is what I want instead
One, Two, and Three
Any help is appreciated, thanks!

A: Use safe join as a helper method like this:
In helper:
def story_links(story)
  links = @story.collections.map{ |u| link_to(u.name, collection_path(u)).html_safe }
  safe_join(links, ',')
end

In the view:
<%= story_links(@story) %>

A: <%= @story.collections.map{ |u| link_to(u.name, collection_path(u))}.to_sentence.html_safe %>


text:
Q: Find out word at specific index I have a string with multiple words separated by underscores like this:
string = 'this_is_my_string'

And let's for example take string[n] which will return a letter.
Now for this index I want to get the whole word between the underscores.
So for string[12] I'd want to get back the word 'string' and for string[1] I'd get back 'this'

A: Very simple approach using string slicing is to:

*

*slice the list in two parts based on position

*split() each part based on _.

*concatenate last item from part 1 and first item from part 2

Sample code:
>>> my_string = 'this_is_my_sample_string'
#                              ^ index 14
>>> pos = 14

>>> my_string[:pos].split('_')[-1] + my_string[pos:].split('_')[0]
'sample'

A: This shuld work:
string = 'this_is_my_string'

words = string.split('_')
idx = 0
indexes = {}
for word in words:
    for i in range(len(word)):
        idx += 1
        indexes[idx] = word

print(indexes[1]) # this
print(indexes[12]) #string

A: The following code works. You can change the index and string variables and adapt to new strings. You can also define a new function with the code to generalize it.
string = 'this_is_my_string'

sp = string.split('_')
index = 12
total_len = 0
for word in sp:
    total_len += (len(word) + 1)    #The '+1' accounts for the underscore
    if index < total_len:
        result = word
        break
print result

A: A little bit of regular expression magic does the job:
import re

def wordAtIndex(text, pos):
    p = re.compile(r'(_|$)')
    beg = 0
    for m in p.finditer(text):
        #(end, sym) = (m.start(), m.group())
        #print (end, sym)
        end = m.start()
        if pos < end: # 'pos' is within current split piece
           break
        beg = end+1   # advance to next split piece
    if pos == beg-1:  # handle case where 'pos' is index of split character
        return ""
    else:
        return text[beg:end]

text = 'this_is_my_string'
for i in range(0, len(text)+1):
    print ("Text["+str(i)+"]: ", wordAtIndex(text, i))

It splits the input string at '_' characters or at end-of-string, and then iteratively compares the given position index with the actual split position.


text:
Q: Python: mask/remove the least significant 2 bits of every 16-bit integer I want to remove the least significant 2 bits of every 16-bit integer from a bitarray. They're stored like this:
010101**00**10010101101100**00**10101010.....

(The zeroes between the asterisks will be removed. There are two of them every 16 bits (ignoring the very first)).
I can simply eliminate them with a regular for loop checking indexes (the 7th and 8th after every 16 bits).
But... is there another more pythonic way to do this? I'm thinking about some slice notation or maybe comprehension lists. Perhaps I could divide every number by 4 and encode every one with 14 bits (if there's a way to do that).

A: You can clear bits quite easily with masking. If you want to clear bits 8 and 7 you can do it like this:
a = int('10010101101100',2)
mask = ~((1 << 7) | (1 << 8))
bin(a&mask)

more information about masking from here!


text:
Q: Android datepicker example API17 Can anyone give me good example of Android DatePicker?
I was following this tutorial: http://www.mkyong.com/android/android-date-picker-example/
But the problem is that The method showDialog(int) from the type Activity is deprecated. Can anyone suggest what to use instead of Dialog...?

A: The recommendation is to use DialogFragment and FragmentManager
http://developer.android.com/reference/android/app/DialogFragment.html
http://developer.android.com/reference/android/app/FragmentManager.html

A: Check this out for clarification
Android date picker


text:
Q: Convert Stream to File I'm using WCF web service and I'm curious if there is any way that I can convert Stream to file.
Occasionally I'm having "cross origin request error" problems, on post methods, and I realized that whenever I receive data as Stream there are no problems.
But now I want to post image to my method on the same way (if there is a way)
This is my code:
[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "SaveImage")]
public bool SaveImage(Stream streamData){
   // read the streamData
   // convert streamData to File
   // with something like this: new FileStream(..streamData);
 return true;
}

Edit:
Html Code:
<form><input type="file" name="file"/>
send
</form>

Jquery ajax:
 $('#send').click(function () {
    var allDataFromTheForm = new FormData($('form')[0]);
    $.ajax({
        url: "/url/SaveImage",
        type: "POST",
        data: allDataFromTheForm,
        cache: false,
        contentType: false,
        processData: false,
        success: function (result) {
            alert(result);
        }
    });
});

A: Don't have reference handy, but it is something like this
using(Stream fileStream = File.CreateFile(...))
{
    streamData.CopyTo(fileStream);
}

A: You could do it like this:
string sFileName = "myimage.jpg";
using (Stream f = File.Create(sFileName))
{
    streamData.Seek(0, SeekOrigin.Begin);
    streamData.CopyTo(f);
}

Edit: This excellent answer covers also other .NET versions.


text:
Q: Actionscript: loader not found I am trying to load an image onto my stage. I use the following code:
    public function loadImg():void{

        var iLoader:Loader = new Loader();
        iLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgressStatus);
        iLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaderReady);

        var fileRequest:URLRequest = new URLRequest(imgPath+'testimg.JPG');
        iLoader.load(fileRequest);

    }

    public function onProgressStatus(e:ProgressEvent) {
        trace(e.bytesLoaded, e.bytesTotal);
    }

    public function onLoaderReady(e:Event) {
        this.stage.addChild(iLoader); // error is here
    }

However it seems that iLoader is not found in onLoaderReady:
1120: Access of undefined property iLoader.

How do I pass object iLoader to this function? Or am I doing something wrong?
Thanks for your help in advance! :D

A: See this page on Function scope. Variables defined inside a function are only available within it, so you just need to define them outside of the function:
private var iLoader:Loader;

public function loadImg():void{

    iLoader = new Loader();
    //...

}

A: Judging from your code, it looks like iLoader is a variable scoped to the function loadImg.  You can't access it by that name outside of loadImg.
One workaround is to put your declaration of iLoader in a broader scope.  In this case, that would be outside of all the functions, as David Mear suggests.
However, you should be able to get around it in a more graceful way.  Every event in AS3 has a target property.  In this case, the target should be your loader.  So inside onLoaderReady, you should be able to do the following:
 this.stage.addChild(e.target);

There's a chance this may not work - since the loader is no longer in scope, it may be deleted.  I believe it will stick around long enough for this line of code to succeed, but don't have any way of testing right now.  If you try it and it fails, we'll just go with David's answer and I'll delete mine.


text:
Q: bootstrap button fixed width I found this: http://jsfiddle.net/yNsxU/ and modified from button to anchor, which is what I need. I have spent several hours over the past few days trying to find a solution, would be grateful for any help. Have also tried much of the sample code on stackoverflow. I downloaded all the latest bootstrap code as of 31st March 2016.
A good amount of code I have found uses links, as the top code block shows, and it all works perfect. I have tried to over-ride the btn-group but that has not worked.
Some of the code I have been using came from some samples I downloaded, all of it has been working very well. If I can't get the fixed width working I will have change the code to use buttons instead of links.
Thanks very much for the link:

This does not work

            Save
            Download

This works, but I need the anchors, not the button

            <button href="#" class="btn btn-primary custom">Save</button>
            <button href="#" class="btn btn-success custom">Download</button>

A: You can set display:inline-block on your anchors and it should work.

A: The problem is coming from an older version of Bootstrap. The jsFiddle you linked to is using Bootstrap 2.3.2. If you use a newer version of Bootstrap, 3.3.6 for example, your problem will not exist.
If you are working with Bootstrap 2.3.2 and still want to resolve this problem, this CSS seems to work.
 .custom {
    width: 78px !important;
    display: inline-block;
    padding: 4px 0 !important;
}


text:
Q: How to hash SHA256 byte 00 with Python? I'm trying to SHA256 a byte b"00" with python but don't understand what I have to encode.
import binascii
import hashlib

byte_ = binascii.unhexlify(b"00")
byte_ = b"00".decode("ascii")

hashed_byte = hashlib.sha256(byte_)
print((hashed_byte.hexdigest()))

What am I doing wrong? Why does this work with a string and not a byte?

A: If you are using b'\x00' then you are defining a binary string as indicated in the comment section. As you have directly encoded a byte, the compiler or interpreter already performs the conversion. So you don't have to perform any conversion afterwards.
Note that for Python 3, you could also use bytes(1) which specifies a zero filled byte array of size 1. If you think that is not as readable, you could use bytes.fromhex('00'). In both cases the conversion would be performed at runtime though, so it has an ever so tiny overhead.

A: Python's hashlib already accepts binary strings.
import hashlib

m = hashlib.sha256()

m.update(b"\x00")  #or use m.update(bytes.fromhex('00'))
hashed = m.hexdigest()

print(hashed)

outputs
6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d
There are NIST SHA-256 byte-oriented test vectors, however, there is no test vector for b"\x00". I've tested for other byte values like 0xd3 outputs
28969cdfa74a12c82f3bad960b0b000aca2ac329deea5c2328ebc6f2ba9802c1 correctly.

If you want to see the internals see https://sha256algorithm.com/

A:
The hexadecimal value 00 does not exist in notation.
All though the value 00 can be represented in both notations, the hexvalue 00 is the same as binary value 0, 00, 000, 0000, 00000000000 et infinitum...
This leads to the computational conclusion that a hexadecimal value 00 could represent an infinite amount of logical gates.  logical outcomes between hexadecimal 0 and hexadecimal 00 is either one outcome, or all outcomes that or not false that proceed.... This causes... problems... and is not a logical computation that is quantifiable.

This was the premise for Y2K and the end of the world

binary 00 -->"true" then "true" value is logically different from binary 0--> "true".
Convert them to hexadecimal...
... you get just hexadecimal 0, which represents binary "true", not binary "true" then 'true".
its like seeing two true false questions on an exam that is true, and only answer the one to represent both.

i believe \x00 works for finding 00


text:
Q: VB InStr Equivalent in c# I am not sure why I get the result of 0, which is the correct value of a
I have in VB
Dim searched As String = "<results>" & vbCrLf & "<field name=\""FID\""/>" & vbCrLf & "<field name=\""StartFID\""/>" & vbCrLf & "<field name=\""Vertex1\""/>" & vbCrLf & "<field name=\""Vertex2\""/>" & vbCrLf & "<field name=\""Slope\""/>" & vbCrLf & ""

Dim sought As String = "<rs FID=\""87\"" StartFID=\""87\"" Vertex1=\""29\"" Vertex2=\""30\"" Slope=\""-1\""/>"

Dim a As Integer = InStr(searched, sought)

What I would like to do, is get the same result of a == 0 when converted to c#.
I have tried
int a = String.Compare(searched, sought);
int a = String.IndexOf(searched, sought);
int a = String.Equals(searched, sought);

A: Strings in C# are zero-indexed. If a.IndexOf(b) returns 0, then string b is present in string a at position 0.
If the sought string is not in the input, IndexOf() returns -1.

A: One difference between InStr and IndexOf's behavior is that InStr returns zero when the string is not found, while IndexOf returns -1. Using IndexOf is the idiomatic way of searching for substrings in C#, and the correct method to use in your situation.
If you would like to use InStr directly, you could do it by referencing Microsoft.VisualBasic assembly, and then calling InStr as a static method of the Strings class:
int a = Strings.InStr(searched, sought);

A: Simply You can use IndexOf()+1 to return 0 instead of -1
int a = searched.IndexOf(sought)+1;

it work for me hop it help

A: You can use the searched.Contains(sought)

A: String.IndexOf should work, but if you truly want to use InStr, you can still do it. Just add a reference to Microsoft.VisualBasic.dll, and a "using Microsoft.VisualBasic;" at the top of your file, and you can use Strings.InStr:
Like Strings.InStr(searched, sought)

A: The three methods are all for different purposes and do not the same. That is why they have different names..
int a = String.IndexOf(searched, sought);

This is the method that you should use and is exactly for that purpose.
Alternatively you could use string.Contains().
int a = String.Compare(searched, sought);

Compares two specified String objects, ignoring or honoring their case, and returns an integer that indicates their relative position in the sort order.
bool a = String.Equals(searched, sought);

Determindes equality of two strings.

A: Works... Thanks Carsten
int b = searched.IndexOf(sought);

b = 0
I see the problem I had now... when I move the string to a variable that calculates the string I get the error.  I wasn't sure whether I had the correct use of InStr.


text:
Q: Typescript: generic interface for creating object containing options and a selection I am trying to create a generic option type/interface which will be used to create specific option types. This generic type/interface takes a set of options as input. The parameter value contains the current selection, and options contains all the options. The parameter value should only be allowed to hold strings contained in options and options should be defined from the list of options defined externally.
This is my current progress:
export type GenericListOfOptions<list> = {
    type: 'list',
    name: string,
    value: list,
    options: Array<list>, // I am not sure if this is right...
}

// Here i define my options:
const these_options = ['yes', 'no', 'maybe'] as const;

// Here i define a specific option type from the
// generic option type. This specific option type is
// defined from the 'these_options' constant.
type MySpecificOptions = GenericListOfOptions<typeof these_options[number]>

// Here i use the type to create an option object.
let my_options: MySpecificOptions = {
    type: 'list',
    name: 'am i going to the gym?',
    value: 'no',
    options: these_options, // Here is an error relating readonly properties...
    // 'options' should be equal to ['yes', 'no', 'maybe'].
    // I preferrably want to reuse the 'these_options' array to define the 'options' parameter.
}

The error given is:
The type 'readonly ["yes", "no", "maybe"]' is 'readonly' and cannot be assigned to the mutable type '("yes" | "no" | "maybe")[]'.ts(4104)
interfaces.ts(137, 5): The expected type comes from property 'options' which is declared here on type 'MySpecificOptions '

But maybe there are other more general errors of this idea, so any help would be greatly appreciated!

A: When you initialized these_options as
const these_options = ['yes', 'no', 'maybe'] as const;
// const these_options: readonly ["yes", "no", "maybe"]

you used a const assertion, presumably so the compiler would remember that the elements consist of the string literal types "yes", "no", and "maybe".  But it also has the effect of making these_options have a readonly tuple type, which is a subtype of the ReadonlyArray type.  It is not known to have the mutating methods of the Array type, like the push() method or the splice() method, etc.  ReadonlyArray<T> is therefore wider than Array<T>.  That means Array<T> is assignable to ReadonlyArray<T> but not vice versa.

So given the definition of GenericListOfOptions<T> as
type GenericListOfOptions<T> = {
    type: 'list',
    name: string,
    value: T,
    options: Array<T>,
}

then of course this will be a problem:
let my_options: MySpecificOptions = {
    type: 'list',
    name: 'am i going to the gym?',
    value: 'no',
    options: these_options // error
}

because the options property must be an Array<"yes" | "no" | "maybe">, but these_options is only known to be a ReadonlyArray<"yes" | "no" | "maybe">.

Presumably you don't actually intend to mutate the contents of the options property of GenericListOfOptions<T>.  If so, then the simplest solution is to widen the options property type to ReadonlyArray<T>:
type GenericListOfOptions<T> = {
    type: 'list',
    name: string,
    value: T,
    options: ReadonlyArray<T>, // change
}

let my_options: MySpecificOptions = {
    type: 'list',
    name: 'am i going to the gym?',
    value: 'no',
    options: these_options // okay
}

On the other hand, if you do want to mutate these_options, and you do need Array<T> instead of Readonly<T>, then you could do an array spread to copy the const-asserted tuple into a mutable array:
const these_options = [...['yes', 'no', 'maybe'] as const];
// const these_options: ("yes" | "no" | "maybe")[]

And then you could leave GenericListOfOptions<T> alone.
Playground link to code


text:
Q: How can I take cosine of a variable in python? I am trying to make a program that will find the x and y components of an applied force at an angle.  Here is what I have so far.  When I run it I get an error that basically says that you cannot take the cosine of a variable and that it has to be a real number.  How would I make this type of program work?

Import math
Angle = input("Enter angle:")
Force = input("Enter applied force:")
X = math.cos(angle)
Y = x * force
Print("The x component of the applied force is", y)
B = math.cos(angle)
A = b * force
Print("The y component of the applied force is", A)

A: Here's code after fixing capitalization and changing type of inputted values to floats:
import math
angle = float(input("Enter angle:"))
force = float(input("Enter applied force:"))
x = math.cos(angle)
y = x * force
print("The x component of the applied force is", y)
b = math.cos(angle)
a = b * force
print("The y component of the applied force is", a)


text:
Q: How to add Multiple collection view cells in Swift, where first cell will be constant and rest cells will depend on an array count I am trying to create a view that has collection view in it. The collection view has multiple cells. The first cell will remain constant. and the rest will show depending on the array count. I will post the code that i have written. The problem in my code is - (and where I need your help)
1.The cells are showing but it's taking the image count that I am providing under numberOfItemsInSection function. And due to this the first image in the array is not displaying.
2. I am stuck at getting the right count of cells if the array count gets added to the first cell that is constant.
OutputImage:My output Image
Note: I have added a view controller and registering the cells from the code
Code:
[MultipleCellCollectionViewController -
import UIKit

class MultipleCellCollectionViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    @IBOutlet weak var multipleCellCollectionView: UICollectionView!

    let cellImage: \[UIImage\] = \[#imageLiteral(resourceName: "shirts"),#imageLiteral(resourceName: "hats"),#imageLiteral(resourceName: "hat03"),#imageLiteral(resourceName: "hoodie02")\]

    override func viewDidLoad() {
        super.viewDidLoad()
        multipleCellCollectionView.delegate = self
        multipleCellCollectionView.dataSource = self
        multipleCellCollectionView.register(MultipleCellCollectionViewCell.self, forCellWithReuseIdentifier: "cell1")
        multipleCellCollectionView.register(TwoMultipleCollectionViewCell.self, forCellWithReuseIdentifier: "cell2")
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//        if section == 0{
//        return 1
//        }else {
//            return cellImage.count
//        }
        return cellImage.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if indexPath.item == 0 {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell1", for: indexPath) as? MultipleCellCollectionViewCell
            cell!.labelLabel.text = "HI THERE"
            return cell!
        }else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell2", for: indexPath) as? TwoMultipleCollectionViewCell
            let myImage = cellImage\[indexPath.row\]
            cell!.image.image = myImage
            return cell!
        }
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = collectionView.bounds.width
        return CGSize(width: width/2 - 2, height: width/2 - 2)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 2
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 2
    }
}

MultipleCellCollectionViewCell-
import UIKit

class MultipleCellCollectionViewCell: UICollectionViewCell {

   // @IBOutlet weak var cellView: UIImageView!

    public var labelLabel: UILabel = {
        let labelView = UILabel()
        labelView.translatesAutoresizingMaskIntoConstraints = false
        //labelView.text = "Hello"
        labelView.textColor = .black
        labelView.font = UIFont(name: "Georgia", size: 10.0)
        labelView.textAlignment = .center
        return labelView
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.addSubview(labelLabel)

        labelLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor, constant: -10).isActive = true
        labelLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor, constant: 10).isActive = true
        labelLabel.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true
        labelLabel.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

TwoMultipleCollectionViewCell-
import UIKit

class TwoMultipleCollectionViewCell: UICollectionViewCell {

    public var image: UIImageView = {
           let imageV = UIImageView()
           //imageV.image = UIImage(named: "shirts")
           imageV.frame.size = CGSize(width: imageV.frame.size.width, height: imageV.frame.size.height)
           imageV.contentMode = .scaleAspectFit
           imageV.translatesAutoresizingMaskIntoConstraints = false
           imageV.clipsToBounds = true
           return imageV
       }()

    override init(frame: CGRect) {
           super.init(frame: frame)
           contentView.addSubview(image)

           image.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 0).isActive = true
           image.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 0).isActive = true
           image.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: 0).isActive = true
           image.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 0).isActive = true
       }

       required init?(coder aDecoder: NSCoder) {
           super.init(coder: aDecoder)
       }

}][1]

A: So you have 1 section, need to return cellImage.count + 1 for the number of items in section, and then use indexPath.row - 1 to lookup your cell image in cfiaip if indexPath.item > 0: let myImage = cellImage[indexPath.row - 1]


text:
Q: "The Mental Math Challenge" can this be more efficient? Recently I have been trying to improve my mental math capabilities and I came across this website, https://rankyourbrain.com/mental-math/mental-math-test-easy/countdown. User need to do as many simple math questions as possible within 2 minutes using only +, -, and / .After several trial, I decided to use python web scraping to automate the process to see how far computers could go on the leader-board. Here is my python code....
from selenium import webdriver
from bs4 import BeautifulSoup
from Num import NumericStringParser
import time

browser = webdriver.Chrome()
browser.get('https://rankyourbrain.com/mental-math/mental-math-test-easy/countdown')
time.sleep(6)
for x in range(0, 10000):
    content = browser.page_source
    soup = BeautifulSoup(content, "lxml")
    number = soup.find(id="beforeAnswer").get_text()
    newstr = number.replace("=", "")
    nsp=NumericStringParser()
    result = int(nsp.eval(newstr))
    print(result)
    #time.sleep(0.1)
    username =browser.find_element_by_id("answer")
    username.send_keys(result)

I was only able to boost my score up to 2000 on a good run, seeing the code being not so efficient, I would like to ask if there is other more efficient way of doing this? Especially to score 16383 within 2 minutes the code must be really fast and efficient, so there is a lot more for me to learn I think:D


text:
Q: Can a quadratic approximation be calculated with a table calculator? The continued-fraction-method allows to calculate a linear approximation of a real number with a table calculator.
But I do not know an analogue method for a quadratic approximation.

Given a real number $r$ with $0<r<1$ , how can I find integers $a,b,c$ , lets say with $|a|,|b|,|c|\le 100$ , such that $r$ is near a root of $ax^2+bx+c$ ?

I only heard about the LLL-Method (if I remember the name right), but I did not find a concrete algorithm. It seems that this method is a kind of optimzation algorithm, perhaps simplex, which is probably too complicated for a calculation with a table calculator.
Another possibility would be to transform the continued fraction to a periodic continued fraction near the given one, but usually this will lead to a quadratic equation with coeffcients with large absolute value. Moreover, it is not easy to derive the quadratic equation from the periodic continued fraction.
A method which can be used to find approximative linear dependency's of real numbers, like $e$ and $\pi$, as well, would be best.


text:
Q: Adding redux to react native? i'm currently working on an app using react-native for the first time,
but i'm struggling to add redux.
i get this error TypeError: Cannot read property 'getState' of undefined and i don't know how to fix it.
this my code :
import React from "react";
import Home from "./home";

import { store } from "./redux/store";
import { Provider } from "react-redux";
/* @flow */

import { View, StyleSheet } from "react-native";

class App extends React.Component {
  render() {
    return (
      <Provider store={store}>
        <View style={styles.container}>
          <Home />
        </View>
      </Provider>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1
  }
});

store.js :
import { applyMiddleware, createStore } from "redux";
import logger from "redux-logger";

import reducer from "./reducer";

const middlewares = [logger];

const store = createStore(reducer, applyMiddleware(...middlewares));

export default store;

reducer.js :
import { combineReducers } from "redux";

import mapReducer from "../redux/maps/maps-reducer";

export default combineReducers({
  map: mapReducer
});

maps-action.js:
import MAPSActionTypes from './maps-action-types';

export const currentlocation = () => ({
    console.log(${location});
    type : MAPSActionTypes.GET_CURRENT_LOCATION
});

maps-reducer.js:
import MAPSActionTypes from "./mapsactiontypes";

const INITIAL_STATE = {
  location: {}
};

const mapReducer = (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case MAPSActionTypes.GET_CURRENT_LOCATION:
      return {
        ...state,
        location: action.payload
      };
    default:
      return state;
  }
}

export default mapReducer;

home.js:
import React from 'react';
import {
  StyleSheet,
  View,
  Text,
} from 'react-native';

import {connect} from 'react-redux'

const Home = (props) => {

  return (
      <View style={styles.container}>
        <Text>welcome</Text>
        <Text>{props.location}</Text>
      </View>
  );
};

const styles = StyleSheet.create({
  container:{
    flex:1,
    justifyContent:'center',
    alignItems:'center'
  }
});

const mapStateToProps = (state) => {
  return {
    location: state.map.location
  }
}

export default connect(mapStateToProps)(Home);

i'm all ears from more clarification or more details.
i will be very thankful if there's anyone who can help me to fix that problem.

A: The problem is you export default in store.js file.
export default store;

But in App you import it with {}. So the store you imported is undefined.
import { store } from "./redux/store";

The correct import is
import store from "./redux/store";


text: Q: Redirect to google Login page after Login in laravel 5.8 I am try to run an existing laravel project but after login it will redirect to login page instead of home page. I check in the middleware auth::user is empty also. Need help in it.


text:
Q: How to store the pandas groupby() objects in the same variable with different indexes Suppose I have a data frame df with three columns
df=
id  date       value
A  02-04-2000  3
A  03-04-2000  8
B  04-04-2000  12
B  02-04-2000  7
C  03-04-2000  5
C  04-04-2000  2

I am interested in grouping the data based on df['id'] column and store the values in a variables  new. The new should store the values in such a way that when I call new[1] it should return elements corresponding to id = A leaving the id column and new[2] should return the elements corresponding to id = B and so on.
example output:
new[1]=
date       value
02-04-2000  3
03-04-2000  8

new[2]=
date        value
04-04-2000  12
02-04-2000  7

A: For all solutions is used DataFrame.groupby with remove id column by DataFrame.drop.
If possible indexing by 0, 1,... and output is list of DataFrames:
new = [g.drop('id', axis=1) for _, g in df.groupby('id')]
print (new[0])
         date  value
0  02-04-2000      3
1  03-04-2000      8

If output is dictionary of DataFrames, here are create consecutive groups:
new = {k: g.drop('id', axis=1)
                       for k, g in  df.groupby(df['id'].ne(df['id'].shift()).cumsum())}
print (new[1])
         date  value
0  02-04-2000      3
1  03-04-2000      8

Similar solution (without consecutive groups):
new1 = {k: g.drop('id', axis=1) for k, g in  df.groupby('id')}
print (new1['A'])
         date  value
0  02-04-2000      3
1  03-04-2000      8

Grouping by cosecutive group I try explain in another data:
 print (df)

  id        date  value
0  A  02-04-2000      3
1  A  03-04-2000      8
2  B  04-04-2000     12
3  A  02-04-2000      7
4  A  03-04-2000      5
5  C  04-04-2000      2

new = {k: g.drop('id', axis=1)
                       for k, g in  df.groupby(pd.factorize(df['id'])[0]+1)}

#all A rows is first group
print (new[1])
         date  value
0  02-04-2000      3
1  03-04-2000      8
3  02-04-2000      7
4  03-04-2000      5

#all C rows is third group
print (new[3])
         date  value
5  04-04-2000      2

Grouping by consecutive groups:
print (df)

  id        date  value
0  A  02-04-2000      3 <- 1group
1  A  03-04-2000      8 <- 1group
2  B  04-04-2000     12 <- 2group
3  A  02-04-2000      7 <- 3group
4  A  03-04-2000      5 <- 3group
5  C  04-04-2000      2 <- 4group

new = {k: g.drop('id', axis=1)
                       for k, g in  df.groupby(df['id'].ne(df['id'].shift()).cumsum())}

#first group
print (new[1])
         date  value
0  02-04-2000      3
1  03-04-2000      8

#fourth group
print (new[3])
         date  value
3  02-04-2000      7
4  03-04-2000      5

A: # generate new dict
new = {}
# get unique id values
unique_ids = df['id'].unique()

for index, value in zip(range(len(unique_ids)), unique_ids):
    new[index] = df[df['id'] == value].copy()


text:
Q: Karma/Testacular opens browser without extensions When I run Karma (formerly Testacular) with 'browsers' configured to 'Chrome' and 'Firefox', 2 browser instances indeed open, however the extensions/plugins appear to be missing while I want them running with my tests.
I've configured:
CHROME_BIN=C:\Program Files (x86)\Google\Chrome\Application\chrome.exe and FIREFOX_BIN=C:\Program Files (x86)\Mozilla Firefox\firefox.exe
It kinda looks like the launched Chrome instance is of a different installation or something, as it doesn't have all my Chrome bookmarks (neither the extensions, as written).
Any idea?

A: If you change the index.js like this:
this._getOptions = function(url) {
    // Chrome CLI options
    // http://peter.sh/experiments/chromium-command-line-switches/
return [
    '--user-data-dir=' + this._tempDir,
    '--no-default-browser-check',
    '--no-first-run',
    '--disable-default-apps',
    '--disable-popup-blocking',
    '--start-maximized',
    '--load-extension=' + '<your path to the extension>/2.0_0'
].concat(flags, [url]);

where
<your path to the extionsion>

is something like this:
/Users/dannyb/Library/Application Support/Google/Chrome/Default/Extensions/hmhgeddbohgjknpmjagkdomcpobmllji

That weird number is the extionsion ID that you can find in your extensions page in chrome.

A: If you look at how chrome is run on karma, along with some other command line flags, it disables default apps
on start up. I myself am looking for how to turn these features off, but no luck yet.
https://github.com/karma-runner/karma-chrome-launcher/blob/master/index.js


text:
Q: How do I test for the appearance of a notification in the notification shade? We are testing an iOS application that works the following way:

*

*If the user sends the app to the background while performing a task, the app alerts the user to resume the task.

*Tapping on this notification puts the app back into foreground, and it resumes the task.

*The notification text has some content (e.g. numbers) that needs to be parsed against expected values.

I am using Instruments UI Automation's deactivateAppForDuration method to push the app into the background - which works fine. On my real test devices, the app is actually pushed into the background.
The problem is in detecting the notification - I have read the UI Automation Documentation and there does not seem to be a way to do this. The only alert-handling construct I found is onAlert() which works well for alert dialogs only.
So - has any one found a way to handle notifications in the notification shade using UI Automation?


text:
Q: Will thepresence of clicking the message box affect program output sequence I am trying to write C# code for a memory game. I would like to present the matrix( with 3 elements) to the viewer first, then a number of options for each element, highlighting that cell at a time. User has to select the correct element from  the answer panel. The display answer matrix (defined as a task) does this. The output sequence (display matrix, display answer etc. for each element shown at first) works fine if I put a message box in the for loop of display answer task. I click after every answer show and wait for next. It works fine. But if i remove the message box ( so no click required), program stops after answer showing(for the first element).could anyone help me?
relevant code portions are:
Mainform{
......declare number of textboxes and lables...for matrix display
}
 In the Buttonclick from the main form:
{
var firstTask = new Task(() => invokedisplaymatrix(MatrixInfoValues));

var secondTask = firstTask.ContinueWith((t) => invokedisplayblankmatrix(MatrixInfoValues));

var thirdTask = secondTask.ContinueWith((t) =>invokedisplayanswermatrix(MatrixInfoValues));

var fourthTask = thirdTask.ContinueWith((t) => invokedDoselection(MatrixInfoValues));

            firstTask.Start();
}
  private void invokedisplaymatrix(object Minfo1)
        {
            lock (this)
            {
                Invoke(new displaymatrixdelegate(displaymatrix), new object[] { Minfo1 });
                Thread.Sleep(2000);
            }

        }

        private void invokedisplayblankmatrix(object Minfo2)
        {
            lock (this)
            {
                Invoke(new displayblankmatrixdelegate(displayblankmatrix), new object[] { Minfo2 });
            }

        }

        private void invokedisplayanswermatrix(object Minfo3)
        {

            lock (this)
            {
                Invoke(new displayanswermatrixdelegate(displayanswermatrix), new object[] { Minfo3 });
                // Invoke(new displaymatrixdelegate(displaymatrix),new object[] {indx});
            }
        }
..Then in the display answer matrix function:

 public void displayanswermatrix(int[] Minfo3)

        {
 foreach (int ind in FilledTextBoxID2)

            {
                foreach (Control c in splitContainer1.Panel1.Controls)
                {
                    if (c is TextBox && c != null)
                    {
                        if ((boxindexL + 1) == FilledTextBoxID2[j])
                        {
                            c.BackColor = Color.OrangeRed;

                        }
                        else
                        {
                            c.BackColor = Color.MediumSpringGreen;
                        }
                       boxindexL = boxindexL + 1;
                    }

                }

                int AnswerLocation = RandomNumber(1, 5);
                int[] answeroptions=excludenumberfromarray(MatrixValues2[j]); //write a function to make random numbers between 1 and 9 excluding MatrixValues2[j]

                foreach (Control c in splitContainer1.Panel2.Controls)
                {
                    if (c is TextBox)
                    {

                        //c.Text = Convert.ToString(boxindexR);
                            //answeroptions[boxindexR]);
                        if ((boxindexR + 1) == AnswerLocation)
                        {
                            c.Text = Convert.ToString(MatrixValues2[j]); //boxindexR = boxindexR - 1;
                        }
                        else
                        {
                            c.Text = Convert.ToString(answeroptions[boxindexR]);
                        }
                       //
                       //}//placing the required number in the randomly selected box
                       boxindexR = boxindexR + 1;
                    }
                 }

                Thread.Sleep(2000);
               MessageBox.Show("hello after one number");
 j = j + 1;
                boxindexR = 0; boxindexL = 0;
            }//end of first foreach

        }//display answer matrix end

If I comment the message box, the interface sleeps there after the first element display.
May I know how this error comes?

A: Sleeping on the UI thread is never a good idea - that just marks the program as unresponsive. The UI cannot make itself available to service things like paint-requests until your method finishes - but your method (by sleeping for 2 seconds over and over) is not allowing that. I suspect the MessageBox usage is forcing a redraw outside of the code message-loop, so : working, but working for the wrong reasons.
Basically, if you have delays and pauses, you shouldn't be handling that with Sleep - you should be using some form of Timer. This will allow you to get a callback in 2 seconds, rather than sleep for 2 seconds, but (importantly) lets the app actually respond to the message queue in the interim - i.e. lets it draw itself.
However! If you simply switch to a Timer, you can't do those things as continuations, as the initial "start doing stuff" call will only last a few milliseconds while it sets up the first image.
Conclusion: you've out-clevered yourself using lots of fancy Task etc, when all you need is a Timer, and a callback (Tick / Elapsed) that says:
- is there any more of X to do?
  - yes: do (a single) X
  - no: is there any more of Y to do?
    - yes: do (a single) Y
    - no: is there any more of Z to do?
      - yes: do (a single) Z
      - no: stop timer


text:
Q: getting SIGABRT from trying to populate a table view I have a table view that I need to populate with dynamic data.
I did it previously in a separate controller and just copied everything over.
However, this time I keep on getting a SIGABRT error.
I've found out that it's whenever I include these two line it errors out
//  editJobTable.dataSource = self
//  editJobTable.delegate = self

Here is my full view controller
import Foundation
import UIKit

class HelloworkJobsEditJobViewController: UIViewController{
    fileprivate var presenter: HelloworkJobsEditJobPresenter?

    @IBOutlet weak var editJobTable: UITableView!

    func inject(presenter: HelloworkJobsEditJobPresenter) {
        self.presenter = presenter
    }

    var helloworkJob: HelloworkJob!

    override func viewDidLoad(){
        super.viewDidLoad()
        helloworkJob = presenter?.getHelloworkJob()
        editJobTable.dataSource = self
        editJobTable.delegate = self
//        editJobTable.reloadData()
    }

    @IBAction func tapCloseButton(_ sender: Any) {
        self.dismiss(animated: true, completion: nil)
    }
}

extension HelloworkJobsEditJobViewController: UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return 7
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        print("\(#line): \(#function) \(indexPath.row)")
        let cellIdentifier = "HelloworkJobsEditJobCell"

        guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? HelloworkJobsEditJobCell else {
            fatalError("The dequeued cell is not an instance of HelloworkJobsEditJobCell.")
        }

        cell.cellLabel.text = "labeltest"
        cell.cellTextField.text = "textfieldtest"
        return cell
    }
}

extension HelloworkJobsEditJobViewController: UITableViewDelegate {
}

Any ideas on why it might be throwing this error would be greatly appreciated.

A: You must register the tableView with the cell custom class
tableView.register(UINib(nibName: "engineTableViewCell", bundle: nil), forCellReuseIdentifier:"cellID")

Or
tableView.register(engineTableViewCell.self, forCellReuseIdentifier: "cellID")

A: Use like this:
extension HelloworkJobsEditJobViewController: UITableViewDelegate {

func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return 7
    }
}

extension HelloworkJobsEditJobViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        print("\(#line): \(#function) \(indexPath.row)")
        let cellIdentifier = "HelloworkJobsEditJobCell"

        guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? HelloworkJobsEditJobCell else {
            fatalError("The dequeued cell is not an instance of HelloworkJobsEditJobCell.")
        }

        cell.cellLabel.text = "labeltest"
        cell.cellTextField.text = "textfieldtest"
        return cell
    }
}


text:
Q: Fill a DTO's List attribute with hibernate named query and spring I'm wondering if the following could be achieved with hibernate. considering the following DTO:
public class ClassDTO {
    private String className;
    private List<String> studentNames;
    //getters & setters
}

and the following hbm file containing the sql-query:
<hibernate-mapping>
    <class name="app.ClassDTO">
        <id name="className" type="java.lang.String" />
        <property name="studentNames" type="java.lang.List" />
    </class>

    <sql-query name="classQuery">
        <return alias="class" class="app.ClassDTO" />
            select classTable.CLASS_NAME AS {class.className}, ST.STUDENT_NAME
             from CLASS classTable
            join STUDENT ST on ST.CLASS_ID=classTable.CLASS_ID
            where ST.age<18
    </sql-query>
</hibernate-mapping>

if we run the query in the Database we'll get the following result :
+----------+------------+
|CLASS_NAME|STUDENT_NAME|
+----------+------------+
|  CS106   |   BILL     |
|  CS106   |   GEORGE   |
|  CS106   |   MICHEL   |
|  ELEC8   |   WILL     |
|  ELEC8   |   MIKE     |
|  ELEC8   |   BETTY    |
+----------+------------+

if we run the query in hibernate, we're supposed to get a List of ClassDTO objects. but is it possible to initialize those objects in the following manner?
List<ClassDTO> result = getHibernateTemplate.findByNamedQuery("classQuery").;
resul.size(); //<-- the list size should be 2 (one entry for CS106 and another for ELEC8)
result.get(0).getStudentNames().size(); //<-- the size should be 3 for BILL, GEORGE and MICHEL who are linked to the class CS106

I've searched through hibernate documentation but i haven't succeeded in finding any answer yet. any help is really apreciated.
thanks in advance guys.

A: If you normalize your data a little further and tweak your mapping you can get Hibernate to do this automatically:
<class name="app.ClassDTO">
    <id name="className" type="java.lang.String" />
    <list name="studentNames" table="class_student">
    <key column="class_name" />
        <element type="string"/>
    </list>
</class>

I'll admit, if the only only data present really are these 2 columns then normalization seems silly.  But to a large extent, having Hibernate automatically convert flat table data to a complex object structure requires following certain rules (I'll stop short of calling it a best practice in this particular case).
If you want to leave the table like it is, then you'll need to create the ClassDTO on your own, which really isn't that hard:
final List<Object[]> resultObjects = getSession().getNamedQuery().list();
public Map<String, ClassDTO> resultMap = new HashMap<>(String, ClassDTO);
for (Object[] result : resultObjects) {
    // find ClassDTO in map for class, or create new one
    // add student name to class dto instance
}


text:
Q: Performing Node Searches in API's Consider the following Reddit Post: https://www.reddit.com/r/datascience/comments/xlvr0l/who_is_applying_to_all_these_data_scientist_jobs/
Part 1: Here is an example of comments that were left on this post - Using the Reddit API ("Pushshift"), for a given comment on this post (e.g. a comment left by "Playful_Message_7944"), I would like to retrieve all comments in the conversation, i.e. ALL previous comments in the conversation BEFORE "Playful_Message_7944" replied, and ALL future comments in the conversation AFTER "Playful_Message_7944" replied.

Part 2:

*

*Based on the document for the API (https://github.com/pushshift/api) know that the following query can be used to find out this comment left by "Playful_Message_7944": https://api.pushshift.io/reddit/comment/search?limit=250&q=*&link_id=xlvr0l

*Then, I can identify the exact link (using ctrl+f and searching for the comment text): https://reddit.com/r/datascience/comments/xlvr0l/who_is_applying_to_all_these_data_scientist_jobs/ipln78n/
Part 3: We can now see the JSON information for this comment:
 {
            "all_awardings": [],
            "archived": false,
            "associated_award": null,
            "author": "Playful_Message_7944",
            "author_flair_background_color": null,
            "author_flair_css_class": null,
            "author_flair_richtext": [],
            "author_flair_template_id": null,
            "author_flair_text": null,
            "author_flair_text_color": null,
            "author_flair_type": "text",
            "author_fullname": "t2_eu0saeom",
            "author_patreon_flair": false,
            "author_premium": false,
            "body": "The 6 month certs people are LITERALLY boot campers. The boot camps pay to license the name of the schools so they can provide these \u201ccertificates\u201d",
            "body_sha1": "6a6cf7368516e1583d9a6e4978b3b002c77e37bb",
            "can_gild": true,
            "collapsed": false,
            "collapsed_because_crowd_control": null,
            "collapsed_reason": null,
            "collapsed_reason_code": null,
            "comment_type": null,
            "controversiality": 0,
            "created_utc": 1663943705,
            "distinguished": null,
            "gilded": 0,
            "gildings": {},
            "id": "ipln78n",
            "is_submitter": false,
            "link_id": "t3_xlvr0l",
            "locked": false,
            "no_follow": true,
            "parent_id": "t1_ipljm3d",
            "permalink": "/r/datascience/comments/xlvr0l/who_is_applying_to_all_these_data_scientist_jobs/ipln78n/",
            "retrieved_utc": 1663943724,
            "score": 1,
            "score_hidden": true,
            "send_replies": true,
            "stickied": false,
            "subreddit": "datascience",
            "subreddit_id": "t5_2sptq",
            "subreddit_name_prefixed": "r/datascience",
            "subreddit_type": "public",
            "top_awarded_type": null,
            "total_awards_received": 0,
            "treatment_tags": [],
            "unrepliable_reason": null
        },

Part 4: So far, I am able to partially retrieve comments that came after this "Playful_Message_7944" with the following code: https://api.pushshift.io/reddit/search/comment/?parent_id=ipln78n
QUESTION: But is there a way to retrieve all comments in the specific conversation that come before and after "Playful_Message_7944"'s comment?
To me this seems like a "Node Search" - for a specific comment, I want to retrieve all comments that are connected to this comment, all comments that are connected to comments that are connected to the original comment, etc.
Thank you!

A: I have been able to get all the comments related to the post "Who is applying to all these data scientist jobs?" with the following code :
library(RSelenium)

rd <- rsDriver(chromever = "105.0.5195.52", browser = "chrome", port = 4480L)
remDr <- rd$client
remDr$open()
url <- "https://www.reddit.com/r/datascience/comments/xlvr0l/who_is_applying_to_all_these_data_scientist_jobs/"
remDr$navigate(url)

web_Obj <- remDr$findElement("xpath", "/html/body/div[1]/div/div[2]/div[2]/div/div/div/div[2]/div[3]/div[1]/div[2]")
text <- web_Obj$getElementText()[[1]]
strsplit(text, "\n")[[1]][1 : 90]

[1] "350"
  [2] "publiée par"
  [3] "u/Alex_Strgzr"
  [4] "il y a 9 jours"
  [5] "Who is applying to all these data scientist jobs?"
  [6] "Job Search"
  [7] "I see all these job postings on LinkedIn with 100+ applicants. I'm really skeptical that there are that many data science graduates out there. Is there really an avalanche of graduates out there, or are there a lot of under-qualified applicants? At a minimum, being a data scientist requires the following:"
  [8] "Strong Python skills – but let's face it, coding is hard, even with an idiot-proof language like Python. There's also a difference between writing import tree from sklearn and actually knowing how to write maintainable, OOP code with unit tests, good use of design patterns etc."
  [9] "Statistics – tricky as hell."
 [10] "SQL – also not as easy as it looks."
 [11] "Very likely, other IT competencies, like version control, CI/CD, big data, security…"
 [12] "Is it realistic to expect that someone with a 3 month bootcamp can actually be a professional data scientist? Companies expect at least a bachelor in DS/CS/Stats, and often an MSc."
 [13] "279 Commentaires"
 [14] "Partager"
 [15] "Sauvegarder"
 [16] "Cacher"
 [17] "Signaler"
 [18] "87 upvotes"
 [19] ""
 [20] "commentaire"
 [21] "Trier Par: Meilleures"
 [22] "niveau 1"
 [23] "Arutunian"
 [24] "·"
 [25] "il y a 9 j"
 [26] "My understanding is that LinkedIn considers you to have "applied" if you click the "apply on company website" button, whether or not you actually submitted an application."
 [27] "387"
 [28] "Répondre"
 [29] "Partager"
 [30] "niveau 2"
 [31] "azevedro"
 [32] "·"
 [33] "il y a 8 j"
 [34] "That explains how you can have 1 day posted and 200 applicants my god"
 [35] "33"
 [36] "Répondre"
 [37] "Partager"
 [38] "Continuer ce fil"
 [39] " niveau 2"
 [40] "Alex_Strgzr"
 [41] "OP"
 [42] "·"
 [43] "il y a 8 j"
 [44] "Yeah, some companies have such a long and tedious application form that it wouldn't surprise if some candidates gave up. Still, for the companies with Easy Apply where we know there are that many applicants, there are a lot of applicants for such a technical, hard-to-fill role."
 [45] "101"
 [46] "Répondre"
 [47] "Partager"
 [48] "Continuer ce fil"
 [49] " niveau 2"
 [50] "Muggleish_wizadry"
 [51] "·"
 [52] "il y a 9 j"
 [53] "Really?! I didn't know this. Why would LinkedIn make such an assumption though?"
 [54] "Shouldn't be there a \"check\" on such things? Sometimes, it's just sad to apply for a job after one day of posting, seeing 89 people have already applied. Just happened to me an hour ago. :-("
 [55] "17"
 [56] "Répondre"
 [57] "Partager"
 [58] "Continuer ce fil"
 [59] " niveau 1"
 [60] "jjthejetblame"
 [61] "·"
 [62] "il y a 8 j"
 [63] "Well we hosted an internship this summer, 2300 applicants for one data science internship. We also hired a full time head in February, 250 applicants for one position. So I don't think it's simply how LinkedIn counts "apply" like some others have said here.. we really see this many applicants per job."
 [64] "126"
 [65] "Répondre"
 [66] "Partager"
 [67] "niveau 2"
 [68] "Voth98"
 [69] "·"
 [70] "il y a 8 j"
 [71] "Out of those applicant pools, what percentage were reasonably qualified for the job?"
 [72] "28"
 [73] "Répondre"
 [74] "Partager"
 [75] "Continuer ce fil"
 [76] " niveau 2"
 [77] "crunchytech413"
 [78] "·"
 [79] "il y a 8 j"
 [80] "Yeeesh. I feel bad for these people who are doing data science undergrad degrees now. It's gonna be rough out there."
 [81] "27"
 [82] "Répondre"
 [83] "Partager"
 [84] "Continuer ce fil"
 [85] " niveau 2"
 [86] "Jooylo"
 [87] "·"
 [88] "il y a 8 j"
 [89] "·"
 [90] "a modifié il y a 8 j"

Also, I tried it on another reddit link and it works :
url <- "https://www.reddit.com/r/datascience/comments/xr62ru/what_are_your_flexible_working_hours/"
remDr$navigate(url)

web_Obj <- remDr$findElement("xpath", "/html/body/div[1]/div/div[2]/div[2]/div/div/div/div[2]/div[3]/div[1]/div[2]")
text <- web_Obj$getElementText()[[1]]

So, I think you can just navigate to the page that contains the post you are looking for and use the approach that I propose. It seems all the reddit pages have the same structure. This is the reason the xpath "/html/body/div[1]/div/div[2]/div[2]/div/div/div/div[2]/div[3]/div[1]/div[2]" is working on two different pages.

A: You can consider something like :
library(RSelenium)

rd <- rsDriver(chromever = "105.0.5195.52", browser = "chrome", port = 4480L)
remDr <- rd$client
remDr$open()
url <- "https://www.reddit.com/r/datascience/comments/xlvr0l/who_is_applying_to_all_these_data_scientist_jobs/"
remDr$navigate(url)

list_Text <- list()

for(i in 1 : 100)
{
  print(i)
  xpath <- paste0("/html/body/div[1]/div/div[2]/div[2]/div/div/div/div[2]/div[3]/div[1]/div[2]/div[5]/div/div/div/div[", i, "]/div/div/div/div[2]")
  web_Obj_Temp <- remDr$findElement("xpath", xpath)
  list_Text[[i]] <- web_Obj_Temp$getElementText()
}

list_Text[1 : 10]
[[1]]
[[1]][[1]]
[1] "niveau 1\nArutunian\n·\nil y a 9 j\nMy understanding is that LinkedIn considers you to have "applied" if you click the "apply on company website" button, whether or not you actually submitted an application.\n387\nRépondre\nPartager"

[[2]]
[[2]][[1]]
[1] "niveau 2\nazevedro\n·\nil y a 9 j\nThat explains how you can have 1 day posted and 200 applicants my god\n31\nRépondre\nPartager"

[[3]]
[[3]][[1]]
[1] ""

[[4]]
[[4]][[1]]
[1] "niveau 2\nAlex_Strgzr\nOP\n·\nil y a 9 j\nYeah, some companies have such a long and tedious application form that it wouldn't surprise if some candidates gave up. Still, for the companies with Easy Apply where we know there are that many applicants, there are a lot of applicants for such a technical, hard-to-fill role.\n103\nRépondre\nPartager"

[[5]]
[[5]][[1]]
[1] ""

[[6]]
[[6]][[1]]
[1] "niveau 2\nMuggleish_wizadry\n·\nil y a 9 j\nReally?! I didn't know this. Why would LinkedIn make such an assumption though?\nShouldn't be there a \"check\" on such things? Sometimes, it's just sad to apply for a job after one day of posting, seeing 89 people have already applied. Just happened to me an hour ago. :-(\n17\nRépondre\nPartager"

[[7]]
[[7]][[1]]
[1] ""

[[8]]
[[8]][[1]]
[1] "niveau 1\njjthejetblame\n·\nil y a 9 j\nWell we hosted an internship this summer, 2300 applicants for one data science internship. We also hired a full time head in February, 250 applicants for one position. So I don't think it's simply how LinkedIn counts "apply" like some others have said here.. we really see this many applicants per job.\n128\nRépondre\nPartager"

[[9]]
[[9]][[1]]
[1] "niveau 2\nVoth98\n·\nil y a 9 j\nOut of those applicant pools, what percentage were reasonably qualified for the job?\n30\nRépondre\nPartager"

[[10]]
[[10]][[1]]
[1] ""

> list_Text[1 : 20]
[[1]]
[[1]][[1]]
[1] "niveau 1\nArutunian\n·\nil y a 9 j\nMy understanding is that LinkedIn considers you to have "applied" if you click the "apply on company website" button, whether or not you actually submitted an application.\n387\nRépondre\nPartager"

[[2]]
[[2]][[1]]
[1] "niveau 2\nazevedro\n·\nil y a 9 j\nThat explains how you can have 1 day posted and 200 applicants my god\n31\nRépondre\nPartager"

[[3]]
[[3]][[1]]
[1] ""

[[4]]
[[4]][[1]]
[1] "niveau 2\nAlex_Strgzr\nOP\n·\nil y a 9 j\nYeah, some companies have such a long and tedious application form that it wouldn't surprise if some candidates gave up. Still, for the companies with Easy Apply where we know there are that many applicants, there are a lot of applicants for such a technical, hard-to-fill role.\n103\nRépondre\nPartager"

[[5]]
[[5]][[1]]
[1] ""

[[6]]
[[6]][[1]]
[1] "niveau 2\nMuggleish_wizadry\n·\nil y a 9 j\nReally?! I didn't know this. Why would LinkedIn make such an assumption though?\nShouldn't be there a \"check\" on such things? Sometimes, it's just sad to apply for a job after one day of posting, seeing 89 people have already applied. Just happened to me an hour ago. :-(\n17\nRépondre\nPartager"

[[7]]
[[7]][[1]]
[1] ""

[[8]]
[[8]][[1]]
[1] "niveau 1\njjthejetblame\n·\nil y a 9 j\nWell we hosted an internship this summer, 2300 applicants for one data science internship. We also hired a full time head in February, 250 applicants for one position. So I don't think it's simply how LinkedIn counts "apply" like some others have said here.. we really see this many applicants per job.\n128\nRépondre\nPartager"

[[9]]
[[9]][[1]]
[1] "niveau 2\nVoth98\n·\nil y a 9 j\nOut of those applicant pools, what percentage were reasonably qualified for the job?\n30\nRépondre\nPartager"

[[10]]
[[10]][[1]]
[1] ""

[[11]]
[[11]][[1]]
[1] "niveau 2\ncrunchytech413\n·\nil y a 8 j\nYeeesh. I feel bad for these people who are doing data science undergrad degrees now. It's gonna be rough out there.\n27\nRépondre\nPartager"

[[12]]
[[12]][[1]]
[1] ""

[[13]]
[[13]][[1]]
[1] "niveau 2\nJooylo\n·\nil y a 8 j\n·\na modifié il y a 8 j\nIt is crazy. A ton of undergraduate schools started data science majors a few years ago and there is an astronomical number of people trying to get in. Not to mention all the bootcamps and people trying to transfer from other fields. I got lucky to get in years ago when I did.\n1\nRépondre\nPartager"

[[14]]
[[14]][[1]]
[1] ""

[[15]]
[[15]][[1]]
[1] "niveau 1\nits_a_gibibyte\n·\nil y a 9 j\nMaintainable, OOP code with unit tests and good design patterns?\nI've met about 3 people in my life that write genuinely high quality code. Everyone else's code (including my own) is an embarrassing mess of spaghetti.\n270\nRépondre\nPartager"

[[16]]
[[16]][[1]]
[1] "niveau 2\nlambo630\n·\nil y a 9 j\nYeah also, what is the task? Am I exploring data and trying to throw some models at it? If so, why do I need immaculate code with unit tests?\n78\nRépondre\nPartager"

[[17]]
[[17]][[1]]
[1] ""

[[18]]
[[18]][[1]]
[1] "niveau 2\nkaumaron\n·\nil y a 9 j\nI'd argue that OOP code is unnecessary most of the time and that's as a data engineer\n28\nRépondre\nPartager"

[[19]]
[[19]][[1]]
[1] ""

[[20]]
[[20]][[1]]
[1] "niveau 2\nSeven_Irons\n·\nil y a 8 j\nI'd even argue that maintainable code is unnecessary for a large number of data projects. So much data work is just based upon coming to good conclusions for some set of data, and presenting that data in a clear fashion.\nAll you need for that is some commented code that's repeatable so anyone can double check calculations at a later date.\nThe analysis may vary so much from project to project, based upon the data itself, that maintainable code might be putting the cart before the horse, so to speak.\n10\nRépondre\nPartager"

At the beginning of each paragraphs, you have "niveau 1" ("niveau 1" in french means "level 1" in english), "niveau 2", etc. With this, you can identify all the "subposts" that belong to a "post". All the subposts that are of "niveau 2" belong to the previous post of "niveau 1".
The code will loop over all the post / subposts of the page using the xpath.
Once you have the structure of all the conversations, you can extract the specific conversation you need by searching for the specific text.


text:
Q: Using Vanilla JS to add inline CSS property and fallback value The problem I am trying to solve is basically the issue with Safari iOs and Vh calculations.
Here is the function:
  function overflowHandler() {
    const header = document.querySelector('.header-container').getBoundingClientRect().height;
    const regionTop = document.querySelector('.region-top').getBoundingClientRect().height;
    const totalHeaderHeight = header + regionTop;
    if (window.innerWidth < 1080) {
      flyout.style.height = 'calc(100vh - ' + totalHeaderHeight + 'px)';
    }
  }

But I need to be able to also pass in height: webkit-fill-available as a style as well to fix the bug on iOS where the user can't scroll completely to the bottom of the nav.
I've tried using element.style.cssText to set both height properties, but whatever is the rightmost value is what gets rendered in the browser.
Example of what I mean would be:
element.style.cssText = 'height: calc(100vh - ' + totalHeaderHeight + 'px); height: -webkit-fill-available;'

would render as height: -webkit-fill-available;
I am at a loss on any other way to make it work or how else to ensure the full height of the menu can be scrolled on iOS.

A: Use element.setAttribute('style', 'height: -webkit-fill-available;')