plotting – How to reverse the order in which ListPlot plots multiple array of numbers?

list = {{1, 2}, {1, 2, 3}, {1, 2, 3, 4}};

Add x-coordinates to each data point using MapIndexed + Thread:

list2 = MapIndexed[Thread[{#2[[1]], #}] &, list]
{{{1, 1}, {1, 2}}, 
 {{2, 1}, {2, 2}, {2, 3}},
 {{3, 1}, {3, 2}, {3, 3}, {3, 4}}}
ListPlot[list2, PlotStyle -> PointSize[Large], PlotLegends -> InputForm /@ list]

enter image description here

You can also use MapThread + Thread to construct list2:

list2 = MapThread[Thread[{##}] &, {Range@Length@list, list}]
{{{1, 1}, {1, 2}}, 
 {{2, 1}, {2, 2}, {2, 3}},
 {{3, 1}, {3, 2}, {3, 3}, {3, 4}}}

c# – Entrada de string que muda depende si e string ou array string

eu fazendo um method mas preciso que quando for executado caso eu passe 1 string ele lê como string caso passe uma string() quero que leia como string array

Exemplos não funcionais mais mentais:

public static void AddName(string Name or string() Name)
{
     if(Name.type == array) Nomes.addrange(Name);
     else Nomes.add(Nome);
}

estou faz tempo nesse caso mas não consigo resolver

java – ¿Cómo sacar la longitud de un array en Freemarker?

Llevo ya un rato probando un montón de cosas que veo por internet acerca de como sacar la longitud de un array en Freemarker, pero ninguna funciona. Actualmente estoy trabajando en Java.

Lo que sucede es lo siguiente. Yo saco unos datos de la base de datos, esos datos son pasados a un fichero en formato JSON, y necesito saber la longitud de un array que contiene ese JSON, pero me está explotando todo el rato el programa.

La forma que he visto que es más fiable a la hora de querer sacar la longitud de un array, y la que estoy usando, es la siguiente:

<#assign count = 0>
<#list Tabla_ejemplo.rows as row>
    <#if count < (Tabla_ejemplo.rows?size) - 1>,
        "${row.dato}",
        <#assign count = count + 1>
    </#if>
</#list>

Con esto lo que estoy intentando es mostrar todos los objetos de ese array menos el último, pero a la hora de ejecutarlo, pero salta el siguiente error:

For "?size" left-hand operand: Expected an extended-hash or sequence or extended collection, but this has evaluated to a collection

Alguna sugerencia?

algorithm – Given a 2D array, how do I generate a random path of fixed length from a random point at length 0 to a random point at max length?

I’m trying to generate a random path on a 2D grid given that:

  • The width and height of the grid are given
  • The length of the path to generate is given
  • The path can’t move “back”
  • The path starts from a random point at height 0 and ends at a random point at max height
  • A path segment cannot “touch” with a path segment that is at its height – 1 that is not the latest generated segment of the previous height

This is what two paths generated from the parameters {Width:11, Length:17, PathLength:30} would look like:

generated path example 1
generated path example 2

and this is an example of a path that should not be generated:

Bad example

The result of the algorithm should be a list of value pairs such as this: (8,6) in any order, which indicates the segments of the path.
I’ve been trying to solve this problem for a while, but I have problems understanding how to make this have a given length. If the given length was not a requirement I could just generate it with a nested for cycle and some rules. Please help!

java – Seat Reservation 2D Array Applied to Methods

I have completed my lab assignment for class, but I’m still wondering if there’s any ways I could better optimize my code. specifically my methods isSeatAvailable and reserveSeat.
Here is my problem: Write a program that displays, examines and manipulates a two dimensional array
representing plane seats for a plane with 12 rows and 4 seats per row.
Write methods for the following operations:

fillSeatsRandomly:Fills the array with random values in range from 0 to 1.
Zero represents an empty seat and one represents a reserved seat.

displaySeats: Displays all the seats in the plane row by row. Empty seat is
displayed as 0 and a reserved seat is displayed as X. Create vertical headings
for the row numbers from 1 to 12 on the left hand side and horizontal column
headings from A to D (for the 4 seats in the row).

isSeatAvailable: Receives an integer representing a row number and a character
representing a seat from A to D. This method tests if the specified seat is
available, otherwise it returns false. This method displays an error message
when the seat selection is invalid.

reserveSeat: Reserves a specified seat.
Receives two parameters: an integer representing a row number and a character
representing a seat number from A to D. This method displays an error message
when the seat is invalid.

seatsAvailInRow: counts and returns number of seats available in given row.
Receives an integer representing row number.

findRowWithTwoSeats: This method look for the closest row with two adjacent
available seats. If two adjacent seats are not available it returns 0.

countSeatsAvail: counts the number of all seats available in the plane and
returns that number.

countTakenSeats: counts the number of all seats reserved in the plane and
returns that number.

Here is my code:

public class ArraysLab {

public static void main(String() args) {
    Plane p = new Plane();
    p.fillSeatsRandomly();
    p.displaySeats();
    if (p.isSeatAvailable(2, 'B')) {
        System.out.println("You have reserved seat: 2,B");
        p.reserveSeat(2, 'B');
        p.displaySeats();
    }
    System.out.println("Sorry, seat: 2,B is already taken");
    System.out.println("There is " + p.seatsAvailInRow(5)
            + " seat(s) available in row 5");
    System.out.println("Row " + p.findRowWithTwoSeats()
            + " has 2 adjacent seats");
    System.out.println("Seats available: " + p.countSeatsAvail());
    System.out.println("Seats taken: " + p.countTakenSeats());

}//end of main

}//end of class ArraysLab

class Plane {

int()() seats = new int(12)(4);

public void fillSeatsRandomly() {//fills seats randomly
    for (int() seats1 : seats) {
        for (int col = 0; col < seats1.length; col++) {
            seats1(col) = (int) Math.round(Math.random());
        }//end of nested for
    }//end of for
}//end of fill seats randomly

public void displaySeats() {//displays the seats
    System.out.print("tA  tB  tC  tD n");
    for (int row = 0; row < seats.length; row++) {
        System.out.print(row + 1 + "");
        for (int seatNum = 0; seatNum < seats(row).length; seatNum++) {
            if (seats(row)(seatNum) == 1) {
                System.out.print("tX  ");
            } else {
                System.out.print("t0  ");
            }
        }//end of nested for
        System.out.println();
    }//end of for
}//end of displaySeats

public boolean isSeatAvailable(int row, char column) {  //checks if seat is 
    //available, returns true if it is and false if not
    int rowNum = row - 1;//row number of the seat chosen
    char colChar = column;//character of the seat chosen
    int colNum = 0;//char converted to int for ease of use
    switch (colChar) {
        case 'A':
            colNum = 0;
            break;
        case 'B':
            colNum = 1;
            break;
        case 'C':
            colNum = 2;
            break;
        case 'D':
            colNum = 3;
    }
    //end of switch
    return seats(rowNum)(colNum) == 0;
}//end of isSeatAvail

public void reserveSeat(int row, char column) {//reserves a seat updates array
    int rowNum = row - 1;//Row number of seat chosen
    int colNum = 0;//Column number of seat chosen
    char seatSelect = column;//Character of column chosen
    switch (seatSelect) {
        case 'A':
            colNum = 0;
            break;
        case 'B':
            colNum = 1;
            break;
        case 'C':
            colNum = 2;
            break;
        case 'D':
            colNum = 3;
    }//end of switch
    seats(rowNum)(colNum) = 1;
} //end of reserveSeat

public int seatsAvailInRow(int row) {//checks how many seats are available 
    //in a row determined returns int value
    int rowNum = row - 1;
    int rowSum = 0;
    int avail;
    for (int() plane1 : seats) {
        rowSum = 0;
        for (int j = 0; j < plane1.length; j++) {
            rowSum += seats(rowNum)(j);
        } //end of nested for
    } //end of for
    avail = 4 - rowSum;
    return avail;//returns number of seats available
}//end of seatsAvailInRow

public int findRowWithTwoSeats() {//finds the closest row that has 
    //2 adjacent seats, returns row num, or 0 if none
    for (int i = 0; i < seats.length; i++) {
        for (int j = 0; j < seats(i).length; j++) {
            if (seats(i)(0) + seats(i)(1) == 0 || seats(i)(1)
                    + seats(i)(2) == 0
                    || seats(i)(2) + seats(i)(3) == 0) {
                return i + 1;//returns row num with adjacent seats
            }//end of if
        } //end of nested for
    } //end of for
    return 0;//returns 0 if there is no adjacent seats
}//end of findRowWithTwoSeats

public int countSeatsAvail() {//counts how many seats are available on the
    //plane, returns int value
    int count = 0;//used to keep track of how many seats are available
    for (int() plane1 : seats) {
        for (int j = 0; j < plane1.length; j++) {
            if (plane1(j) == 0) {
                count++;
            } //end of if
        } //end of nested for
    } //end of for
    return count;//returns the number of seats available
}//end of countSeatsAvail

public int countTakenSeats() {//counts number of seats taken on the plane, 
    //returns int value
    int count = 0;//used to keep track of how many seats are taken
    for (int() plane1 : seats) {
        for (int j = 0; j < plane1.length; j++) {
            if (plane1(j) == 1) {
                count++;
            }
        } //end of nested for
    } //end of for
    return count;//returns number of seats taken
}//end of countTakenSeats

}//end of class plane

plugin development – Callback is not called in add_settings_field() when passed as part of an array, but recognises that it’s there. It’s passed Class to Class using OOP

I am building a plugin, I created a new admin page and subpage, and inside that subpage, I want to add some Settings. That’s why I’m building them using the Settings API.
I am using Composer and Object-Oriented Programming. I have a folder called SettingsAPI, with the following namespace namespace BlocksPagesSettingsAPI;
Inside that folder, I have three files: AddSettings.php, Settings.php and SettingsLayout.php. All three of them are correctly connected. The files have the case sensitive names of the Classes. Settings.php has a Class named Settings, and so on.

SettingsAPI Folder Structure

Inside Settings.php I have a function that holds a variety of arrays, inside of those arrays are the values I want to use for the Settings API. This means I have arrays that are used for register_setting(), add_settings_section() and add_settings_field().
Inside AddSettings.php I have the three functions just mentioned. Both register_settings() and add_settings_field() work great. I have problems with add_settings_field().
Inside SettingsLayout.php I have a very simple layout for where the form should be printed, which is also shown on the Subpage. Just the inputs are missing.

Inside AddSettings.php I used a foreach() to loop over the array, if I need to. Which is used for both register_setting() and add_settings_field(), that’s because both of those arrays have arrays inside of them. I’ll show some code used for register_setting() and the foreach().

Settings.php

$configs = (
      ( // Icon
        "option_group"    =>    "iw_" . $n,
        "option_name"     =>    "iw_icon_" . $n,
        "args"            =>    $iconConfigs
      ),
      ( // Titel
        "option_group"    =>    "iw_" . $n,
        "option_name"     =>    "iw_title_" . $n,
        "args"            =>    $titleConfigs
      ),
      ( // Beschreibung
        "option_group"    =>    "iw_" . $n,
        "option_name"     =>    "iw_description_" . $n,
        "args"            =>    $descriptionConfigs
      ),
      ( // Farbauswahl
        "option_group"    =>    "iw_" . $n,
        "option_name"     =>    "iw_colour_" . $n,
        "args"            =>    $colourConfigs
      )
    );

The array above is being passed, alongside the other arrays, to the AddSettings Class and the next function that will process them.

$this->add_settings->setForm( $configs, $segments, $inputs )->register();

setForm() does the following with the arguments.

AddSettings.php

public  function  setForm(  array  $configs,  array  $segments,  array  $inputs )  {
    $this->settings =  $configs;
    $this->sections =  $segments;
    $this->fields =  $inputs;
    return  $this;
}

The variables $settings, $sections and $fields have been created at the beginning of the class as public and empty arrays.

public $settings = array();
public $sections = array();
public $fields = array();

Which then gets registered with the following function:

public  function  functionToAdd()  {
return  $this->registerForm(  $this->settings,  $this->sections,  $this->fields );
}

registerForm() hold all the Settings API functions from WP, here is register_setting().

foreach( $this->settings as $setting ) {
      register_setting( $setting("option_group"), $setting("option_name"), isset( $setting("args") ) ? $setting("args") : "" );
    }

This part works great. It also works with add_settings_section(). What doesn’t work, are the inputs. Which I will present now as well:

Settings.php

Inside this Class is the function/method setForm( $n = NULL ), that’s where all the arrays are, like the one I showed above. Right now $n has no meaning, but it’s going to be a number, so I can loop all over those arrays and settings to create more forms. Whether I keep it at NULL or I change it to 1, does not affect the result, same thing.
Here is the array for the fields.

$inputs =  (
    (
        "id"  =>  "iw_icon_"  .  $n,
        "title"  =>  "Icon Auswahl",
        "callback"  =>  function()  use($n)  {  return  $this->iconInput(  $n );  },
        "page"  =>  "info_kreis_bearbeiten",
        "section"  =>  "iw_item_"  .  $n,
        "args"  =>  (  "label_for"  =>  "iw_icon_"  .  $n )
    ),
    (
        "id"  =>  "iw_title_"  .  $n,
        "title"  =>  "Titel",
        "callback"  =>  function()  use($n)  {  return  $this->titleInput(  $n );  },
        "page"  =>  "info_kreis_bearbeiten",
        "section"  =>  "iw_item_"  .  $n,
        "args"  =>  (  "label_for"  =>  "iw_title_"  .  $n )
    ),
    (
        "id"  =>  "iw_description_"  .  $n,
        "title"  =>  "Kurz Beschreibung",
        "callback"  =>  function()  use($n)  {  return  $this->descriptionInput(  $n );  },
        "page"  =>  "info_kreis_bearbeiten",
        "section"  =>  "iw_item_"  .  $n,
        "args"  =>  (  "label_for"  =>  "iw_description_"  .  $n
    ),
    (
        "id"  =>  "iw_colour_"  .  $n,
        "title"  =>  "Farbe auswählen",
        "callback"  =>  function()  use($n)  {  return  $this->colourInput(  $n );  },
        "page"  =>  "info_kreis_bearbeiten",
        "section"  =>  "iw_item_"  .  $n,
        "args"  =>  ( "label_for"  =>  "iw_colour_"  .  $n )
    )
);

So this is an array with three arrays inside of it. This array has callbacks, and it’s the callbacks that do not work at all. No matter where I put them or how I write them, they are not being echoed. At the bottom, I will list all of the things I have tried.
Like with the settings arrays, they are allso processed like this:

$this->add_settings->setForm( $configs, $segments, $inputs )->register();

AddSettings.php

And then

public  function  setForm(  array  $configs,  array  $segments,  array  $inputs )  {
    $this->settings =  $configs;
    $this->sections =  $segments;
    $this->fields =  $inputs;
    return  $this;
}

and

public  function  functionToAdd()  {
return  $this->registerForm(  $this->settings,  $this->sections,  $this->fields );
}

Which then gets passed to registerForm() with the following function:

foreach(  $this->fields as  $field)  {
    add_settings_field( $field("id"), $field("title"), isset( $field("callback") ) ? $field("callback") : "", $field("page"), $field("section") = 'default', $field("args") = array() );
}

And then nothing. No inputs on my Subpage. Everything but the fields are being echoed.
Form on Subpage
As you can see, the callback used by the section works and shows me the title and description. But the inputs are missing. To show some context on how I called the callback for the sections, here is the one line with the callback from the section array, inside Settings.php:

"callback"  =>  function()  use($n)  {  echo  "<p>Bearbeite hier die Info Nummer "  .  $n .  "</p>";  }

And the function add_settings_section() inside AddSettings.php, no foreach() was used for this one:

add_settings_section(  $sections("id"),  $sections("title"), isset(  $sections("callback")  )  ?  $sections("callback")  :  "",  $sections("page")  );

It’s being called the same way as the fields. But the fields still do not echo anything. And before anyone says I am echoing inside the anonymous callback function instead of returning another function:

I have tried a few things. One of the first things I tried was to edit the way the callback is written. So instead of a function that returns another function, I wrote something simple.

"callback"  =>  function()  {  echo "Echo this please."; },

Didn’t work.

"callback"  =>  array( $this, "iconInput" ),

Also not working
I also tried

"callback"  =>  $this->iconInput( $n ),

Which then called the function and echoed the inputs, but not in the right position. They were at the very top of the page. And if I loop everything, all inputs will be at the top, with the sections below in the right print order. So that’s not the solution either.
What I also tried was to move the callback to AddSettings.php and call it like that.

add_settings_field(  $field("id"),  $field("title"),  function()  { return $this->iconInput();  },  $field("page"),  $field("section")  =  'default',  $field("args")  = array()  );

Didn’t work either.
When I tried to just directly write the function in there, like so

add_settings_field(  $field("id"),  $field("title"),  function()  { echo "Please echo this";  },  $field("page"),  $field("section")  =  'default',  $field("args")  = array()  );

Didn’t work either. I also always put die; at the end, just to see if it’s being called at all, and it has not been. It’s like the function doesn’t exist.
I have also tried to immediately run the function by adding () to it:

add_settings_field( $field("id"), $field("title"), isset( $field("callback") ) ? $field("callback")() : "", $field("page"), $field("section") = 'default', $field("args") = array() );

The same result as earlier. It echoed the inputs, but not in the right position.

I tried looking for an answer, but couldn’t really find one that was similar to mine. I found these questions and solution, tried them, and that also didn’t work:
How to pass arguments from add_settings_field() to the callback function?
and
Add_settings_field() parameterizing callback?

And for clarification, my SettingsLayout.php is build like this:

<form  method="post"  action="options.php"  id="iw_form_<?php  echo  $i?>">
    <?php
        settings_fields(  "iw_"  .  $i  );
        do_settings_sections(  "info_kreis_bearbeiten"  );
        submit_button(  $text  =  NULL,  $type  =  "primary",  $name  =  "submit_"  .  $i  );
    ?>
</form>

$i is the same as $n.

I have run out of options to try. At least of options, I know of. If anyone has any kind of solution, I would be HAPPY to hear them. I also explained myself as best as I could.

And because that’s a lot of code, pasted the relevant code into the online editor for you to look at even better: https://repl.it/@Braweria/Callback-Problems

Edit

Which I forgot to mention, inside my foreach() I also echoed field("id") to see if that works, and it does echo the right ID.

node.js – group all the array data in javascript

I’m new to javascript. I have list of vendors and vendorOrg .if both vendors and vendorOrg’s vendorId matches I need to group the all vendors . But how to group all the vendors category wise

var vendors = (
{
  vendorId: 1,
  name: "vendor-1",
  category: "Dairy",
},
{
  vendorId: 2,
  name: "vendor-2",
  category: "Grocery",
},
{
  vendorId: 3,
  name: "vendor-3",
  category: "Milk",
},
);

var vendorOrg = (
{
  vendorId: 1,
  name: "vendor-1",
  category: "Dairy",
},
{
  vendorId: 23,
  name: "vendor-23",
  category: "Grocery",
},
{
  vendorId: 3,
  name: "vendor-3",
  category: "Milk",
},
);

function lister() {
var List = ();
for (var i = 0; i < vendors.length; i++) {
  for (var j = 0; j < vendorOrg.length; j++) {
    if (vendors(i).vendorId === vendorOrg(j).vendorId) {
      List.push(vendors(i));
    }
  }
}
}

lister();

In this for loop i got my output below,

( { vendorId: 1, name: 'vendor-1', category: 'Dairy' },
  { vendorId: 3, name: 'vendor-3', category: 'Milk' } )

But my expected output is,

{
  Dairy  : ( {vendorId: 1, name: "vendor-1", category: "Dairy"} ),
  Milk : ({ vendorId: 3, name: "vendor-3", category: "Milk" }),
};

How to do that

categories – How to show given products only using product id array from specific category page in woocommerce

I would like to show only the list of product ids in the tax query using filter woocommerce_product_query

So I need to add an additional filter along with a tax query to filter to show only products with given ids.

$tax_query() = array(‘add filter to show only specified products’)
$q->set( ‘tax_query’, $tax_query );

Thanks

php – Solo me valida el primer array

estoy haciendo un log in, tengo un archivo php llamado usuarios.php donde tengo unas constantes en un array con el correo y contraseña, pero la contraseña esta codificada en hash para luego verificar con la función password_verify.

Mi archivo php con las constantes es asi, obviamente las contraseñas y correos son inventados para comprobar:

<?php

    define('USUARIOS',array(
        array(
            'email' => 'admin@admin.com',
            'password' => convertir_hash('iloveu')    
        ),
        array(
            'email' => 'donald@donald.com',
            'password' => convertir_hash('m4k3Am3r1caGr3atAg41n')
        ),
        array(
            'email' => 'gilete@gilete.com ',
            'password' => convertir_hash('ErF4ryS1empr3')
        ),
        array(
            'email' => 'gon@gon.com ',
            'password' => convertir_hash('Fatality')
        ),
    )
    );

    function convertir_hash($pwd){
        return password_hash($pwd, PASSWORD_DEFAULT);
    }

Luego en el php donde compruebo que esto sea correcto solo me valida el primero es decir si el usuario mete en el login admin@admin.com con la contraseña iloveu le redirecciona sin problemas, pero si hace cualquier otro correo y contraseña me salta el alert.

Asi es como lo tengo:

if(empty($errors)){
    foreach(USUARIOS as $vector){
       if($vector('email')===$email_Decod && password_verify($contra_Decod,$vector('password'))){
         header("location: principal.php");
         exit();
      }
   }
                        
   echo "<script language='javascript'> alert('El CORREO $email_Decod Y SON INCORRECTOS'); </script>";
   $errors = "ERROR:VUELVE A INTRODUCIR CORREO Y CONTRASEÑA!";
 }

email_Decod y contra_Decod son variables donde estan descodificados el correo ya que los codificaba con btoa en js y en php hago un base64_decode. El problema creo que el foreach no continua comprobando, pero no estoy seguro.

beginner – Remove duplicates from array and save it to another one

A flag “dup” can be avoided by rearranging the inner loop. Here is a compact version, somehow a bit inside-out so that we can do our thing p(k++)= right on the spot:

    for (int i = 0; i < ARRAY_SIZE; i++) {

        for (int j = i + 1; m(i) != m(j); j++) {

            if (j == ARRAY_SIZE) {
                p(k++) = m(i);        // copy this one, next "i" please
                break;
            }
        }
    }

For clarity I almost prefer this as the inner loop:


     for (int j = i + 1;; j++) {

            if (j == ARRAY_SIZE) {
                p(k++) = m(i);        // copy this one, next please
                break;
            }
            if (m(i) == m(j))
                break;               // skip, next 
        }

This is more symmetric; you can easily compare the two exit conditions for this eternal loop (no middle expression).


For an array like 120000000...000012 I think it would be faster to search in the new, unique array.