Optimization of Do loop with multiple variables

I am pretty new to Mathematica and I would like to optimize a Do loop with multiple variables that I have.

I have three lists of three elements each, with the condition that the first element must be bigger than the second and so on. From those, I construct matrices and make operations on them; since I want to scan on all the possible matrices, I have this big Do loop:

l1={a,b,c};l2={d,e,f};l3={g,h,i}; Do[ m1=Table[(l1[[i]]+l2[[j]]),{i,3},{j,3}]; (*just as an example, not the real operations*) m2=Table[(l1[[i]]+l3[[j]]),{i,3},{j,3}]; {vl,m1d,vr}=SingularValueDecomposition[m1]; {ul,m2d,ur}=SingularValueDecomposition[m2]; ... ,{a,2,5},{b,a-1},{c,0,b-1},{d,2,5},{e,d-1},{f,0,e-1},{g,2,5},{h,g-1},{i,0,h-1} ] 

The operations inside the loop are much more difficult, and this loop would take way too much time to complete. How can I improve my situation? I’ve read something about the use of Map but I didn’t quite understand how it should apply to my case.

Are error variables an anti-pattern or good design?

In order to handle several possible errors that shouldn’t halt execution, I have an error variable that clients can check and use to throw exceptions. Is this an Anti-Pattern? Is there a better way to handle this? For an example of this in action you can see PHP’s mysqli API. Assume that visibility problems (accessors, public and private scope, is the variable in a class or global?) are handled correctly.

PHP no me reconoce variables

tengo un formulario enlazado a un codigo php, pero el php no me reconoce las variables y el correo me llega bien pero sin lo que el usuario introdujo en el formulario.

<!DOCTYPE html> <html lang="es"> <head>  <meta charset="UTF-8">  <title>Formulario de contacto</title> </head> <body>  <form action="enviar.php" method="post">   <h2>CONTACTO</h2>   <input type="text" name="nombre" placeholder="Nombre" required>   <input type="text" name="correo" placeholder="Correo" required>   <textarea name="mensaje" placeholder="Escribe aquí: " required></textarea>   <input type="submit" value="Enviar" id="boton">  </form>  </body> </html>

y el php

<?php  $  destino="correo@midominio.es";  $  nombre=$  _POST["nombre"];  $  correo=$  _POST["correo"];  $  mensaje=$  _POST["mensaje"];  $  contenido="Nombre: ".$  nombre."\nCorreo: ".$  correo."\nMensaje: ".$  mensaje;  mail($  destino,"Contacto", $  contenido); ?> 

muchas gracias de antemano

Terminology: Difference between decision variables, features and attributes?

Could there be a difference between the words “feature”, “attribute”, and “decision variable” when used in the same paper? The one I am specifically thinking about is about an optimization method for clustering, but I am also wondering if there generally are any scenarios for which it could be.

I can’t manage to google up an answer that either confirms or denies that these are the same thing, and I have no formal training in data science.

Swift code review – static variables?

TLDR: (Sent here from StackOverflow) The code I’ve presented is working. I’m looking for a code review from more experienced devs to know if what I have done is OK, and to learn if there are better practices I should focus on to expand my skills and understanding.

Hello. I have completed version 1 of my first app (thanks to all the Q&A’s on StackOverflow who got me there). For version 2 I’m looking to improve the code. I’m not sure if this is the best place to ask for a code review but being one month into self learning swift I don’t know or have anyone to review my work.

I have listed 2 situations that I think I need to improve. If you have the time I’d like some feedback focusing on my use of static variables for changing data between ViewControllers and subviews.

1.0 Image 1 shows the app flow (Left = HomeController), middle = MenuController, Right = FavouritesController)

In HomeController there is a UIView subview. From this subview the current quote (HomeController.homeControllerCurrentQuote) displayed can be saved to favourites array. This is a static array defined in FavouritesController.

The functions below are called from the subview within HomeController. I made HomeController.homeControllerCurrentQuote static because the subview needs access to it. Likewise for FavouritesController.favourites.

// FavouritesController.favourites is static variable! // HomeController.homeControllerCurrentQuote is static variable! updated as user scrolls  func handleFavourite() {     let favourites = FavouritesController.favourites     if favourites.contains(HomeController.homeControllerCurrentQuote) {      removeFromFavourites()     } else { FavouritesController.favourites.append(HomeController.homeControllerCurrentQuote)         UserDefaults.standard.set(try? PropertyListEncoder().encode(FavouritesController.favourites), forKey:"myKey")     } }  func removeFromFavourites() {     var tempArray: [Quote] = [.init(category: "", quote: "", author: "")]     tempArray = FavouritesController.favourites     let searchString = HomeController.homeControllerCurrentQuote.quote     var filteredArray = [Quote]()     filteredArray = tempArray.filter( { !$  0.quote.contains(searchString) } )     UserDefaults.standard.set(try? PropertyListEncoder().encode(filteredArray), forKey:"myKey") }  // update static variable on HomeController internal override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { ....     HomeController.homeControllerCurrentQuote = Quote(category: cell.categoryLabel.text ?? "", quote: cell.quoteLabel.text ?? "", author: author) .... } 

On FavouritesController the data contained in FavouritesController.favourites array is used to populate a tableVIew.

Image 1 Image 1

Should I change how this is done? I don’t like the use of static variables but as it’s my first app I was more focused on getting it done rather than how it was done. Is it a good case for using a delegate and protocol to communicate between the views (I’ve never used this before)? If so how would I start to think about implementing it or, as it works, is what I’ve done satisfactory?

2.0 When the app launches on HomeController required data is generated and is stored in a static variable.

                          //  [category : [quote  : author]] static var xQuotesByCategory: [String   : [String : String]] = [:] 

I make this data static because when I instantiate HomeController again from another controller, I don’t want to have to refetch the data. I want to retrieve it once. Then when a new instance of HomeController is called I can make this check which should return false. Is this an appropriate use of a static variable?

if HomeController.xQuotesByCategory.values.isEmpty {     ... fetchJson() } 

Following on from this, as HomeController.xQuotesByCategory is static, on CategoriesController I can call

var categories = Array(HomeController.xQuotesByCategory.keys) 

This get’s only the outer keys (categories) which I use to create the collectionView cells with the text and images shown in image 2. Again, same question, is this appropriate use of a static variable? Is there better way to ensure data is loaded only once and then pass the keys to CategoriesController in a different way when it’s required?

image 2

Sorry in advance if it’s a bad question to ask for a code review on update (StackExchange) StackOverflow, just trying to learn here. Also, to help a beginner out even more there is a test version available on TestFlight. if someone wants to actually see it for themselves and give me some more feedback let me know and I can add you in TestFlight!

Cheers, appreciate any and all help

Three variables bifurcation diagram

I’m trying to reproduce a paper. The point is that I have three variables and I will like to do the bifurcation diagram.The paper is this one:”A chaotic model of migraine headache considering the dynamical transitions of this cyclic disease” by Atiyeh Bayani, Sajad Jafari,Boshra Hatef and Julien Clinton.If you want to check it all. I’ll show you the model in wich all the parameters are fixed except (e01) which is going to be my bifurcation parameter.Any idea? enter image description here

Llamadas XMLHttpRequest a variables JSON específicas creadas en PHP

Tengo esta llamada XMLHttpRequest que me carga una variable JSON en array desde un PHP, funciona pero cuando hay dos variables distintas creo que el script no sabe cuál coger (JSON.parse(this.responseText)):

 $  (document).ready(function (){   var xmlhttpTipagos = new XMLHttpRequest();   xmlhttpTipagos.onreadystatechange = function() {   if (this.readyState == 4 && this.status == 200) {     var objetoTipagos = JSON.parse(this.responseText);           var out = "";     var i;                var myVar = 1;     for(i = 0; i < objetoTipagos.length; i++) {         a = myVar++;         out += '<li>' + objetoTipagos[i].nombre_tipago + '</li>';     }            document.getElementById("nombre_tipago").innerHTML = out;   } }; xmlhttpTipagos.open("GET", ruta+"obtenresultado.worker.php", true); xmlhttpTipagos.send(); }) 

Mis variables están en el mismo archivo PHP y ofrecen resultados diferentes. Si uso dos llamadas XMLHttpRequest distintas que tiran de archivos PHP distintos me funciona bien. Hay alguna manera de llamar específicamente a una variable? Algo como JSON.parse(arrayTipagoJSON ) y JSON.parse(arrayIdiomasJSON), mi intención es recoger todos los arrays del mismo PHP (obtenresultado.worker.php) sin tener que crear un archivo por cada una.

Los arreglos los encodeo así una vez obtenidos

  $  arrayTipagoJSON = json_encode($  arrayTipago);   $  arrayIdiomasJSON = json_encode($  arrayIdiomas); 

¿Cómo cambiar el valor de cierto número de variables dependiendo de la respuesta del usuario?

Estoy creando un conversor de peso en modo consola bastante sencillo. Lo que quiero hacer es que cuando el usuario proporcione el primer tipo de magnitud, el valor de las variables cambie en base a esa respuesta. Por ejemplo, si yo escribo “libra”, entonces las demás variables de equivalencia cambien su valor para proceder a la conversión. Intenté con la instrucción if, lo cual funciona muy bien a la hora de cambiar el valor de las variables. El problema nace cuando pide la segunda magnitud y debe proceder a la conversión, ya que la única forma que se me ocurrió de que el programa supiera a qué magnitud deseaba convertir era usando input, y luego de eso crear más condicionales if para que pudiera elegir el valor de conversión.

Lo he probado y funciona muy bien, el problema es que pienso añadir más magnitudes, lo cual implicaría una instrucción if por cada cada tipo de conversión posible. Lo cual a mi parecer, hace que el código sea innecesariamente más largo de lo que debería. Mi pregunta es ¿Hay alguna forma de automatizarlo y simplificarlo para que el programa cambie los valores de las variables y sepa cuál equivalencia de conversión el usuario va a usar?

Mi código es este:

    print("Conversor de peso")     print("----------------------------------------------")      while True:         Magnitud1 = str         Magnitud2 = str         Cantidad = str         print("¿Qué desea hacer? Convertir | Salir: ")         ask = input()         if ask == "salir" or ask == "Salir":             break          if ask == "convertir" or ask == "Convertir":             kilogramo = float             gramo = float             Convalue = float             resultado = float              Q1 = input("¿Qué magnitud desea convertir? ")             if Q1 == "libra":                 kilogramo = 0.45                 gramo = 453.59              Q2 = input("¿A qué magnitud desea convertirlo? ")              Q3 = input("¿Cuántas unidades? ")             Cantidad = float(Q3)              if Q2 == "kilogramo":                 Convalue = kilogramo                 resultado = Cantidad * Convalue              if Q2 == "gramo":                 Convalue = gramo                 resultado = Cantidad * Convalue              print("El resultado es: " and resultado)             print() 

Pumping Lemma for Regular Languages with 3 variables (a^nb^mc^m)

I’ve been trying to understand the pumping lemma, and how to apply it to a language such as a^nb^mc^m where n >= 0 and m >= 0. The pumping lemma states that:

For any regular language L, there exists an integer n, such that for all x ∈ L with |x| ≥ n, there exists u, v, w ∈ Σ∗, such that x = uvw, and

(1) |uv| ≤ n

(2) |v| ≥ 1

(3) for all i ≥ 0: uviw ∈ L

It states that there exists some n such that this holds true. In the language a^nb^mc^m if I were to replace m with the pumping length, and choose a pumping length, for example 3, such that a^nb^pc^p I could get the string:


If I chose:

x = aa

y = b

z = bbccc

then xy or aab <= p and y > 0. Then if I pump up y by 2 for example, I would get the string aabbbbccc. But this is not in the language as there are more b’s then c’s. The problem i’m having is if I instead split my string as such:

x = a

y = a

z = bbbccc

then xy or aa <= p and y > 0. If I pump this string by 2 for example, I would get the string aaabbbccc, which is in the language. So in this case the pumping lemma is passed.

So my question is, for the pumping lemma does my second example passing mean that the language a^nb^mc^m passes the pumping lemma, or does the fact that I found a case where splitting x and y with this pumping length makes it false, mean that the language does not pass the pumping lemma. And if that is the case then if I had the language:

a^nb^m where n >=0 and m >=0 and I choose m to be p, and made the pumping length 3 for example, I could end up with the string:

aabbb, where x = a, y = ab, z = bb, which when pumped would produce aababbb which is not in the language, but I know that a^nb^m is a regular language.

Hopefully you can see where my confusion lies. I been researching for a while and I just can’t find a clear cut answer on this. Any help would be extremely appreciated.

Thank you.

Problema la retornar variables privadas

No logro retornar el resultado en un metodobo abstracto ya que me dice que las variables son privadas a pesar de haber configurado los metodos get y set

Clase estandar:

public class Triangulo extends Poligono implements FigueGeometrica {

public Triangulo(double altura, double base) {     super(altura, base);     setBase(Integer.parseInt(JOptionPane.showInputDialog(null,"Base de triangulo")));     setAltura(Integer.parseInt(JOptionPane.showInputDialog(null,"Altura de triangulo")));     getBase();     getAltura();  }  @Override public double calcularArea() {     return (base*altura)/2; //aqui es donde ocurre el problema.  }  @Override public double calcularPerimetro() {     return 0;   } 

Clase abstracta:

public abstract class Poligono implements FigueGeometrica {

private double altura; private double base;     public void setAltura(double altura) {     this.altura = altura; }  public void setBase(double base) {     this.base = base; }  public double getAltura() {     return altura; }  public double getBase() {     return base; }   public Poligono(double altura, double base) {   } 



public interface FigueGeometrica {

double calcularArea(); double calcularPerimetro();