A silly doubt on Computer Science Objects: Arrays, Lists, Strings, and Vectors, are they the same concept?

First of all I’m a Physics Student and I’ve been arguing with my brother concerning the usage and the fundamental meaning of a vector on Computer Science (CS).

I) Vectors

A vector have a axiomatic meaning, i.e., given a set $mathcal{A}$ of objects, their objects can be called vectors if and only if they satisfy the vector space axioms $(1)$. Of course that, 3D vectors (little arrows), function, matrices and so on are different objects, but under a well defined vector addition $boxplus$, and scalar multiplication $boxdot$ they are the same: Vectors!

Furthermore, I think that is impossible to talk about more complicated objects like Tensors without a vector space structure underlying the mathematical usage of CS objects.

II) My doubt

So, I would like to know: arrays, lists, strings are the same object as vectors? In other words, they satisfy the vector space axioms?

$$* * *$$

$(1)$ https://en.wikipedia.org/wiki/Vector_space#Definition

c++ – im making a dynamically allocated array of structures called restaurant that has dynamically allocated arrays of floats and strings for reviews,

im making a dynamically allocated array of structures called restaurant that has dynamically allocated arrays of floats and strings for reviews, but the code isn’t reading my text file correctly and my compiler is creating a separate main file with question marks. I don’t know what went wrong, also sry for bad formatting

#include <fstream>
using namespace std;

//constants
const int SIZE = 3, REV = 3;

struct restaurant
{
    string name;
    int zip;
    float *reviews;
    string *comments;

    ~restaurant()
    {
        if (reviews) delete () reviews;
        reviews=nullptr;
        if (comments) delete () comments;
        comments=nullptr;
    }
};

//prototypes
void outputRestaurant(restaurant&);

int main() {

    ifstream fin("input.txt");
    restaurant *restaurants = new restaurant (SIZE);
    
    for (int i = 0; i < SIZE; i++)
      {
        getline(fin, (restaurants+i)->name);
        fin >> (restaurants+i)->zip;
        (restaurants+i)->reviews = new float (REV);
        (restaurants+i)->comments = new string (REV);
        for (int j = 0; j < REV; j++)
         {
           fin >> *((restaurants+i)->reviews+j);
           getline(fin, *((restaurants+i)->comments+j));
         }
      }

    for (int i = 0; i < SIZE; i++)
     {
      outputRestaurant(*(restaurants+i));
     }
     
    fin.close();
}

void outputRestaurant(restaurant &a)
  {
    cout << "Restaurant summary:" << endl;
    cout << "t> Name: "<< a.name << endl;
    cout << "t> Zip: "<< a.zip << endl;
    for(int i = 0; i < SIZE; i++)
      {
        cout << "t> Review #"<< i+1 << ": "<< (*(a.reviews+i));
        cout << " : " << (*(a.comments + i)) << endl;
      }
  }

this is the text file

Lori's Diner
94114
4.5
Fantastic dining.
3.8
It was OK; lots of waiting.
2.2
Bugs in the food but 2 stars.
Mel's Diner
94114
3.3
Loved the silverware.
3.9
Glorious luxury dining.
2.9
Couldn't find Mel.
Luke's Diner
94114
5.0
The force was strong here
4.0
Dug the cantina vibe
2.5
Couldn't find Princess Leia.

javascript – Eliminar valores duplicados Array de arrays

Tengo un array de este estilo

(("16/02/2020"),("16/02/2020"),("17/02/2020"),("17/02/2020"),("18/07/2020"))

con valores repetidos, lo que quiero es quedarme unicamente con los valores unicos, se qeu con ...new Set se puede hacer, pero solo lo he conseguido dejando los arrays de dentro como strings (("16/02/2020","16/02/2020","17/02/2020","17/02/2020","18/07/2020"))

┬┐Alguna idea de como hacerlo? Gracias.

algorithms – 2-dimensional ranking of multiple arrays

Given a constant dimension $d$, say $d=2$ we want the following:

Input: $A_1ldots A_m$: $m$ arrays of length $n$ of integers

Each input array $A_i$ must be a permutation of the numbers $1..n$, so in each array each number from $1$ to $n$ appears exactly once.

Output: For each pair (in the case $d=2$; triplets in the case of $d=3$ etc.) of numbers $(1,1),(1,2)dots(n,n)$, we want a count for in how many input arrays the first number of the pair is also the first to appear in the array (among the numbers of that pair).

Question: Can this be done quicker than $O(mn^d)$ in the worst case?

Upper and lower bounds

The output is represented as a $d$-dimensional array of length $n$. Therefore a lower bound for the runtime complexity is $O(n^d)$.

The naive approach is to create $m$ mappings from each number to its index for each input array. Then for all $n^d$ tuples, walk through the $m$ mappings, yielding a runtime complexity upper bound of $O(dmn^d)$ and since $d$ is a constant this is $O(mn^d)$.

Examples

A = (1,2,3,4),        Output =  1 2 3 4
    (1,2,3,4),                  -------
    (1,2,3,4),     =>       1 | 4 4 4 4
    (1,2,3,4)               2 | 0 4 4 4
                            3 | 0 0 4 4
    d=2, m=4, n=4           4 | 0 0 0 4

=======================================

A = (4,3,2,1),         Output = 1 2 3 4
    (1,2,3,4),                  -------
    (1,2,3,4)      =>       1 | 3 2 2 2
                            2 | 1 3 2 2
    d=2, m=3, n=4           3 | 1 1 3 2
                            4 | 1 1 1 3

Application

While writing poker analysis software, I’m particularly interested in the case $d=3, mapprox 1250, napprox 1250$. I estimate that the naive $O(mn^d)$ solution takes multiple hours but less than a day when using native Java arrays (no hashmaps etc) on a single thread.

8 – How to add constraints to custom data arrays?

I am validating csv files. I am thinking of using constraints and constraint validator framework available in Drupal to validate the data in the files. However, these seem to be designed to be attached to entity fields. For example.

/**
 Implements hook_entity_base_field_info_alter().
 */
 function projectname_commerce_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
   if ($entity_type->id() === 'commerce_order_item') {
     if (!empty($fields('unit_price'))) {
       $fields('unit_price')->addConstraint('PriceBelowMax');
     }
   }
 } 

where PriceBelowmax is a custom constraint. I would like to attach this constraint to a custom data array. For example

myCustomValidatemethod($data_array, $constraints)

where constraints would be the list of constraints defined in Drupal both core and custom. Is there some reference for the above method.

php – How to INSERT simultaneously two different arrays in PDO MySQL?

I’m having trouble with a PDO insert.
I’d like to insert a multidimensional array into a db, which i managed to.
However, i also would like to insert a completely different array, disconnected from the first one into the same db line (which means same INSERT query).
1st multidimensional array = $_POST(‘training’)
2nd array = $training_diploma
Kinda difficult to explain. Here is the code :

$id = "1";
$training_diploma = ("master", "bachelor");
$id_training_key = $id_training_key = $id.'_'.$training_diploma; (return: 1_master)

$sql = "INSERT INTO users_resumes (id,resume_category,id_training_key,training_diploma,training_school,training_level,training_start_date,training_end_date) VALUES ($id,'Training',$id_training_key,:training_diploma,:training_school,:training_level,:training_start_date,:training_end_date)";
$stmt= $pdo->prepare($sql);
foreach($_POST('training') as $params){
   $stmt->execute($params);
}

Any help is very welcome !!! Thx a looot !

object oriented – Dynamically merge different arrays in javascript

I want to combine two arrays (ranking and matches) that has common properties:

var ranking = ({
    def: "0.58",
    league: "Scottish Premiership",
    name: "Celtic",
    off: "3.33",
    grank: "3",
    tform: "96.33",
},
{
    def: "2.52",
    league: "Scottish Premiership",
    name: "Dundee",
    off: "1.28",
    grank: "302",
    tform: "27.51",
})

var matches = ({
date: "2010-04-22",
league: "Scottish Premiership",
home: "0.0676",
away: "0.8",
draw: "0.1324",
goals1: "3",
goals2: "1",
tform1: "96.33",
tform2: "27.51",
team1: "Celtic",
team2: "Dundee",})

Expected output looks like this:

({
date: "2010-04-22",
league: "Scottish Premiership",
home: "0.0676",
away: "0.8",
draw: "0.1324",
goals1: "3",
goals2: "1",
tform1: "96.33",
tform2: "27.51",
def1: "0.58",
def2: "2.52",
off1: "3.33",
off2: "1.28",
grank1: "3",
grank2: "302",
team1: "Celtic",
team2: "Dundee",})

To merge the arrays, I used Lodash _.merge function

var result = _.merge(ranking, matches);

The output it returned did merge some objects and omitted homogeneous objects.

Please I need some help and insight in achieving this task. I wouldn’t mind any javascript (client-side) solution.

json – Dynamically merge all objects in different arrays in javascript (appending similar names)

I want to combine two arrays (ranking and matches) that has common properties:

var ranking = ({
    def: "0.58",
    league: "Scottish Premiership",
    name: "Celtic",
    off: "3.33",
    grank: "3",
    tform: "96.33",
},
{
    def: "2.52",
    league: "Scottish Premiership",
    name: "Dundee",
    off: "1.28",
    grank: "302",
    tform: "27.51",
})

var matches = ({
date: "2010-04-22",
league: "Scottish Premiership",
home: "0.0676",
away: "0.8",
draw: "0.1324",
goals1: "3",
goals2: "1",
tform1: "96.33",
tform2: "27.51",
team1: "Celtic",
team2: "Dundee",})

Expected output looks like this:

({
date: "2010-04-22",
league: "Scottish Premiership",
home: "0.0676",
away: "0.8",
draw: "0.1324",
goals1: "3",
goals2: "1",
tform1: "96.33",
tform2: "27.51",
def1: "0.58",
def2: "2.52",
off1: "3.33",
off2: "1.28",
grank1: "3",
grank2: "302",
team1: "Celtic",
team2: "Dundee",})

To merge the arrays, I used Lodash _.merge function

var result = _.merge(ranking, matches);

The output it returned did merge some objects and omitted homogeneous objects.

Please I need some help and insight in achieving this task. I wouldn’t mind any javascript (client-side) solution.

query – Searching for substring in field that contains variable length of arrays of json objects

I am trying to construct a sql query, that searches for a substring within a field. The issue is that the field contains an array of one or more json objects.

For example the table looks like so:

day     |   items
____________________
Sunday  | [{"apples":5, "bananas":2}, {"pears":12, "cucumbers":9}, ...]
Monday  | [{"apples":6, "bananas":1}, {"watermelon": 1}]
Tuesday | [{"apples":4, "bananas":3}, {"tomatoes": 1}]

How do I construct a SQL query that searches for a substring in items given it is not a string ?

Thanks

python – Create a multi-dimentional array having fixed-length nested arrays from dataframe

I am working to transform my dataframe into an array of fixed-sized segments that I should feed to a convolutional neural net. Specifically, I would like to transfrom the df to list of m arrays each containing segments sized (1,5,4). So at last, I would have an (m,1,5,4) array.

To clarify my question, I explain using this MWE. Suppose this is my df:

df = {
    'id': (1,1,1,1,1,1,1,1,1,1,1,1),
'speed': (17.63,17.63,0.17,1.41,0.61,0.32,0.18,0.43,0.30,0.46,0.75,0.37),
'acc': (0.00,-0.09,1.24,-0.80,-0.29,-0.14,0.25,-0.13,0.16,0.29,-0.38,0.27),
'jerk': (0.00,0.01,-2.04,0.51,0.15,0.39,-0.38,0.29,0.13,-0.67,0.65,0.52),
'bearing': (29.03,56.12,18.49,11.85,36.75,27.52,81.08,51.06,19.85,10.76,14.51,24.27),
'label' : (3,3,3,3,3,3,3,3,3,3,3,3) }

df = pd.DataFrame.from_dict(df)

To do this, I use this function:

def df_transformer(dataframe, chunk_size=5):
    
    grouped = dataframe.groupby('id')

    # initialize accumulators
    X, y = np.zeros((0, 1, chunk_size, 4)), np.zeros((0,))

    # loop over segments (id)
    for _, group in grouped:

        inputs = group.loc(:, 'speed':'bearing').values
        label = group.loc(:, 'label').values(0)

        # calculate number of splits
        N = len(inputs) // chunk_size

        if N > 0:
            inputs = np.array_split(inputs, (chunk_size)*N)
        else:
            inputs = (inputs)
        
        # loop over splits
        for inpt in inputs:
            inpt = np.pad(
                inpt, ((0, chunk_size-len(inpt)),(0, 0)), 
                mode='constant')
            # add each inputs split to accumulators
            X = np.concatenate((X, inpt(np.newaxis, np.newaxis)), axis=0)
            y = np.concatenate((y, label(np.newaxis)), axis=0) 

    return X, y

The df above has 12 rows, so if transformed correctly to the intended form, I should get an array of shape (3,1,5,4). In the above function, segments with less than 5-rows are zero-padded, to make segment shaped (1,5,4).

This function has 2-bugs that I’m yet to figure out how to fix it.

BUG-1: the function introduces an all-zero array (which is totally not intended), like this:

X , y = df_transformer(df(:10))
X

array((((( 1.763e+01,  0.000e+00,  0.000e+00,  2.903e+01),
         ( 1.763e+01, -9.000e-02,  1.000e-02,  5.612e+01),
         ( 1.700e-01,  1.240e+00, -2.040e+00,  1.849e+01),
         ( 1.410e+00, -8.000e-01,  5.100e-01,  1.185e+01),
         ( 6.100e-01, -2.900e-01,  1.500e-01,  3.675e+01))),


       ((( 0.000e+00,  0.000e+00,  0.000e+00,  0.000e+00),
         ( 0.000e+00,  0.000e+00,  0.000e+00,  0.000e+00),
         ( 0.000e+00,  0.000e+00,  0.000e+00,  0.000e+00),
         ( 0.000e+00,  0.000e+00,  0.000e+00,  0.000e+00),
         ( 0.000e+00,  0.000e+00,  0.000e+00,  0.000e+00))),


       ((( 3.200e-01, -1.400e-01,  3.900e-01,  2.752e+01),
         ( 1.800e-01,  2.500e-01, -3.800e-01,  8.108e+01),
         ( 4.300e-01, -1.300e-01,  2.900e-01,  5.106e+01),
         ( 3.000e-01,  1.600e-01,  1.300e-01,  1.985e+01),
         ( 4.600e-01,  2.900e-01, -6.700e-01,  1.076e+01)))))

The all-zero second array shouldn’t have been there. I should have only the first and last arrays in that case.

BUG-2: The function ONLY works for a df with 10 rows or less (i.e. twice chunk_size or less). So passing the entire df above will always fail with an error, like so:

X , y = df_transformer(df)
X

Traceback (most recent call last):
  File "check.py", line 49, in <module>
    X , y = df_transformer(df)
  File "check.py", line 38, in df_transformer
    inpt = np.pad(
  File "<__array_function__ internals>", line 5, in pad
  File "/Users/IT/anaconda3/lib/python3.8/site-packages/numpy/lib/arraypad.py", line 748, in pad
    pad_width = _as_pairs(pad_width, array.ndim, as_index=True)
  File "/Users/IT/anaconda3/lib/python3.8/site-packages/numpy/lib/arraypad.py", line 519, in _as_pairs
    raise ValueError("index can't contain negative values")
ValueError: index can't contain negative values

Expected output: In this case, the output should be sized (3,1,5,4).

(((( 1.763e+01  0.000e+00  0.000e+00  2.903e+01)
   ( 1.763e+01 -9.000e-02  1.000e-02  5.612e+01)
   ( 1.700e-01  1.240e+00 -2.040e+00  1.849e+01)
   ( 1.410e+00 -8.000e-01  5.100e-01  1.185e+01)
   ( 6.100e-01 -2.900e-01  1.500e-01  3.675e+01)))


 ((( 3.200e-01 -1.400e-01  3.900e-01  2.752e+01)
   ( 1.800e-01  2.500e-01 -3.800e-01  8.108e+01)
   ( 4.300e-01 -1.300e-01  2.900e-01  5.106e+01)
   ( 3.000e-01  1.600e-01  1.300e-01  1.985e+01)
   ( 4.600e-01  2.900e-01 -6.700e-01  1.076e+01)))
 
 ((( 7.500e-01  -3.800e-01  6.500e-01  1.451e+01)
   ( 3.700e-01  2.700e-01  5.200e-01  2.427e+01)
   ( 0.000e+00  0.000e+00  0.000e+00  0.000e+00)
   ( 0.000e+00  0.000e+00  0.000e+00  0.000e+00)
   ( 0.000e+00  0.000e+00  0.000e+00  0.000e+00))))

Note: The Idea is to split the df into chunk_size=5 equal sizes, where the last chunk for an id cannot make up to 5 it should be zero-padded.

For couple of days, I am struggling to fix this bug, but not successful. Can someone help with a fix to this bugs please?