text:
Q: Passing empty string to db helper I'm having some real problems passing a single string from my main activity to my db helper class. Here is my main activity method which I am returning a string 'answerSetId':
 public String showNextRandomQuestion3() {

            SQLDatabaseHelper db = new SQLDatabaseHelper(this);

            //get the data from the database
            List<List<String>> listList = db.getAllAnswersByQuestion1();

            //Get the question/text/answer Strings
            List<String> questionStrings = listList.get(0); //question Strings
            List<String> answerSetIds = listList.get(4);

            //Generate random index
            Random r = new Random();
            int rand = Math.abs((r.nextInt() % questionStrings.size()));

            //get answer description for randomly selected question
            String questionString = questionStrings.get(rand);
            String answerSetId = answerSetIds.get(rand);

            questionView.setText(questionString);

            return answerSetId;
            }

I specifically want to use this 'answerSetId' in one method in my db helper class (as part of a query). Here is my current code - but it is capturing an empty string '[]':
   public List<List<String>> getAnswers(String answerSetId) {

    List<String> array1 = new ArrayList<String>();
    List<String> array2 = new ArrayList<String>();

    System.out.println(answerSetId);

    SQLiteDatabase db = this.getReadableDatabase();

    String[] columns = new String[]{TDESCR, ADESCR};
    String selection = ASID+"=?";
    String[] selectionArgs = new String[]{String.valueOf(answerSetId)};
    Cursor c = db.query(TABLE_ANSWERS, columns, selection, selectionArgs, null, null, null);

   if (c.moveToFirst()) {
    do {

     String textdescr = c.getString(c.getColumnIndex(TDESCR));
     String answersdescr = c.getString(c.getColumnIndex(ADESCR));
     array1.add(textdescr);
     array2.add(answersdescr);

    } while (c.moveToNext());

 }
   List< List<String> > listArray2 = new ArrayList< List<String> >();
   listArray2.add(array1);
   listArray2.add(array2);

   return listArray2;
}

You can see that I want to use this method to retrun some more array data based on the query using the 'answerSetId' string - you'll also see where I have added a system print out which gives the empty value '[]'. But am only bothered about actually capturing the 'answerSetId' value from my main activity at this point.
How best to achieve this?
the arrays of data I will then pass onto my 'showNextAnswer()' method:
        public String showNextAnswers() {

            SQLDatabaseHelper db = new SQLDatabaseHelper(this);

            //get the data from the database
            List<List<String>> listList = db.getAnswers(answerSetId);

            //Get the question/text/answer Strings
            List<String> textDescrs = listList.get(0); //question Strings
//          List<String> answerDescrs = listList.get(1); //text strings

//          System.out.println(answerSetId);
            answerView3.setText(textDescrs.toString());

            String textDescriptions = textDescrs.toString();
//          String regex = "\\[|\\]";
//          textDescriptions = textDescriptions.replaceAll(regex, "");

            //Separate out the question/answer of text description associated with the randomly selected question
            StringTokenizer textDescr = new StringTokenizer(textDescriptions, ",");

            String first = textDescr.nextToken();
//              String second = textDescr.nextToken();
//              String third = textDescr.nextToken();
//              String fourth = textDescr.nextToken();

            subQuestionView1.setText(first);
//              subQuestionView2.setText(second);
//              subQuestionView3.setText(third);
//              answerView3.setText(fourth);
//              System.out.println(textDescr);
            return null;
            }

FYI - I call 'showNextRandomQuestion3()' from an onClick method when user clicks to go to a next question - a new random question and the related answers to that new question will appear each click:
        NextQuestionButton.setOnClickListener(new OnClickListener(){;
                @Override
        public void onClick(View v) {
                    showNextRandomQuestion3();
                    showNextAnswers();
                    countQuestions();

                }});

A: It looks like the solution is very simple.  You just capture the return value of showNextRandomQuestion3(), since it returns answerSetId.
You will need to add a String parameter to the showNextAnswers() method to take the String that was returned from showNextRandomQuestion3().
So in your click event, you would do this:
 NextQuestionButton.setOnClickListener(new OnClickListener(){;
        @Override
        public void onClick(View v) {
                    String answerSetId = showNextRandomQuestion3(); //get return value
                    showNextAnswers(answerSetId); //give the ID here
                    countQuestions();

                }});

Then, just add the parameter to showNextAnswers(), and you're done!
public String showNextAnswers(String answerSetId) {

            SQLDatabaseHelper db = new SQLDatabaseHelper(this);

            //get the data from the database
            List<List<String>> listList = db.getAnswers(answerSetId); //This will work now!

            //.................


text:
Q: Why aren't these modules being resolved? Here is the error output I get. I've tried creating a jsconfig.json to do what the errors describe as a solution but I'm just too inexperienced to understand what's going on...
All of these modules are installed in my node-modules folder.
I'm trying to build a Dapp using react truffle and web3js

Module not found: Error: Can't resolve 'crypto' in
'C:\Users\gavin\WebstormProjects\untitled\blockchain\node_modules\eth-lib\lib'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js
core modules by default. This is no longer the case. Verify if you
need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'
- install 'crypto-browserify' If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "crypto": false } assets by status 6.88 KiB [cached] 1 asset assets by chunk 4.86 MiB (name: main)

The error I'm getting is much larger than this but stackoverflow won't allow me to post the whole thing.

A: Turns out I wasn't following instructions properly. Made the correct changes to webpack.config.js and everything is working good.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to split line with trace by specific length in QGIS I'm modifying the existing water pipeline network. Sometimes I have information that the pipe from the beginning to the 125meter has a diameter 63mm after that point it has a 100meter -diameter 50mm and the rest of it 32mm.
I need to split that 1 pipe into 3 pipes:

*

*125meter,

*100meter,

*and the rest of what was left (to give different diameter attributes(63,50,32)).

And I also need it to be modified in the same shapefile.
Advanced digitizing and v.split don't work in this situation.

A: A workaround:
Create a point layer with points as the split distances using "Geometry by expression":
collect_geometries(array_foreach( array(100,225), end_point(line_substring( $geometry, 0, @element))))

Snap the split tool line to the points


text:
Q: Loading column selectively from TSV in Redshift I am loading a TSV file from S3 file in a RedShift table. TSV file has 10 columns.
I want to select only column 2 and 5 from that CSV.
Previously I was using the COPY command to create table. Can I selectively specify I want to select column 2 and 5?

A: You cannot do this (currently) with a COPY command.  The target table and the CSV/TSV file being loaded need to have the same columns.  You can COPY to a temp table with all the columns then insert the needed data into your table.
If this doesn't work for you then define an external table that points to the CSV file and insert from the external table to your target.


text:
Q: get raw rfc822 message from phpmailer I am trying to use google-api-php-client and gmail-api to allow my users to authenticate their gmail accounts and send emails through my website.  I asked a more generic questions earlier and decided to seek help from the PHPMailer community with this question.
I have used PHPMailer to send emails.  And I want to know if I can extract the raw rfc822 message from my PHPMailer object after setting it up prior to sending.  I should be able to then do a base64_encode on that string and set the "raw" property for my Google_Service_Gmail_Message.

A: No problem: Set up everything as if you were going to send, but instead of calling send(), call preSend(), then fetch the complete message using getSentMIMEMessage().


text:
Q: How to keep privacy between a MySQL server and a PHP server Imagine an architecture composed of 2 Virtual Machines VM1 and VM2 hosted somewhere in the cloud:

*

*VM1 is dedicated to a Web Front End (Apache/PHP)

*VM2 is dedicated to a MySQL server

*VM1 and VM2 are located in the same hosting company

It means that there is traffic between VM1 and VM2 composed of queries/results. As this traffic occurs in a VM hosting farm out of my control, I guess that somebody can be a "man-in-the-middle" to analyze this traffic.
My question : In this context, how to guarantee the security/privacy/integrity of the MySQL transactions between VM1 and VM2?
As far as I know, there is no privacy option in mysqli_connect.
Thanks for your help
::Guillaume::

A: Use an ssl connection to the mysql server.
You can do this in mysql using the mysqli_ssl_set.
You will have to configure your mysql server to accept ssl connections too.
Refer: PHP to MySQL SSL Connections


text:
Q: Limit checked amount of grouped checkboxes (i.e. max 2 groups) This might be simple to solve, but I ran into many issues, so I hope someone can help.
I have groups of checkboxes (options coming form a db), something like this

*

*area1: 4 options

*area2: 6 options

*areaX: X options etc.

The user has to select at least one option from one group/area, but no more than 2/group from max. 2 groups/areas (aka max. 4 options; max 2 options per group/area; max 2 groups/areas).
I know how to limit the amount of checked boxes checked for a simple scenario, but I'm blank with the above problem (also found some posts, i.e. this.
I hope someone can help.
Thanks in advance.
So far I have this (limit the checkboxes per group)

$(function(){
  var max = 2;
  var checkboxes = $('.area > input[type="checkbox"]');
  console.log(checkboxes);
  checkboxes.click(function(){
    var $this = $(this);
    var set = checkboxes.filter('[name="'+ this.name +'"]');
    var current = set.filter(':checked').length;
    return current <= max;

  });
});
.c {
  max-width: 1200px;
  margin: auto;
}
.area {
  margin-bottom: 10px;;
}

            <input type="checkbox" value="Option 1-1" id="option1" name="option1" />Option 11

            <input type="checkbox" value="Option 1-2" id="option2" name="option1" />Option 12

            <input type="checkbox" value="Option 1-3" id="option3" name="option1" />Option 13

            <input type="checkbox" value="Option 2-1" id="option21" name="option2" />Option 21

            <input type="checkbox" value="Option 2-2" id="option22" name="option2" />Option 22

            <input type="checkbox" value="Option 2-3" id="option23" name="option2" />Option 23

            <input type="checkbox" value="Option 3-1" id="option31" name="option3" />Option 31

            <input type="checkbox" value="Option 3-2" id="option32" name="option3" />Option 32

            <input type="checkbox" value="Option 3-3" id="option33" name="option3" />Option 33

            <input type="checkbox" value="Option 4-1" id="option41" name="option4" />Option 41

            <input type="checkbox" value="Option 4-2" id="option42" name="option4" />Option 42

            <input type="checkbox" value="Option 4-3" id="option43" name="option4" />Option 43

/ K

A: Since vanilla is also a go you can try the following
(function () {

      var checkboxes = [];
      var areas = [];
      var maxInArea = null;
      var maxOverall = null;

      function init() {
        //initialize checkboxes and areas as well as limits
        checkboxes = document.querySelectorAll('input[type="checkbox"]');
        areas = document.getElementsByClassName('area');
        maxInArea = 2;
        maxOverall = 4;

        for (var i = 0; i < checkboxes.length; i++) checkboxes[i].addEventListener('click', handleCheckboxClick, false); //add an event listener to each checkbox
      }

      function handleCheckboxClick(e) {
        var currentArea;
        var currentAreaCheckboxes;

        currentArea = e.target.parentElement; //get the current area...
        currentAreaCheckboxes = currentArea.querySelectorAll('input[type="checkbox"]'); //...to count its checked checkboxes

        if ((_getActiveCheckboxesInArea(currentAreaCheckboxes) > maxInArea) //check limits per area...
          || (_getActiveCheckboxesOverall() > maxOverall) ){ //...then overall
          e.target.checked = false;
        }
      }

      function _getActiveCheckboxesInArea(areaCheckboxes) {
        var count = 0;

        for (var i = 0; i < areaCheckboxes.length; i++)
          if (areaCheckboxes[i].checked) count++;

        return count;
      }

      function _getActiveCheckboxesOverall() {
        var count = 0;

        for (var i = 0; i < checkboxes.length; i++)
          if (checkboxes[i].checked) count++;

        return count;
      }

      init();

    })();

As you can see the trick is to have a count for the current area detecting the area parent element when the checkbox is clicked. It looks quite like a long script, but since it is Vanilla you have more control, simplicity and performance than using jQuery, you will notice as soon you give it the first read

A: You can do this by keeping an array of all names for checked boxes, and comparing it against the most recently clicked box:

const max = 2
    let totals = []

  const checkboxes = document.querySelectorAll('.area > input[type="checkbox"]')
    checkboxes.forEach(el => {
        el.addEventListener("click", (e) => {

            //check within group
            let within = totals.filter(name => name === e.target.name)
            if(e.target.checked && within.length >= max && totals.indexOf(e.target.name) > -1){
                console.log("max within group reached")
                e.preventDefault()
                return
            }

            //check all groups
            let without = totals.filter((name, idx, arr) => arr.indexOf(name) === idx)
            if(e.target.checked && without.length >= max && without.indexOf(e.target.name) === -1){
                console.log("max groups reached")
                e.preventDefault()
                return
            }

            if(e.target.checked){
                totals.push(e.target.name)
            }else{
                totals.splice(totals.indexOf(e.target.name),1)
            }
        })
    })
.c {
  max-width: 1200px;
  margin: auto;
}

.area {
  margin-bottom: 10px;
  ;
}

            <input type="checkbox" value="Option 1-1" id="option1" name="option1" />Option 11

            <input type="checkbox" value="Option 1-2" id="option2" name="option1" />Option 12

            <input type="checkbox" value="Option 1-3" id="option3" name="option1" />Option 13

            <input type="checkbox" value="Option 2-1" id="option21" name="option2" />Option 21

            <input type="checkbox" value="Option 2-2" id="option22" name="option2" />Option 22

            <input type="checkbox" value="Option 2-3" id="option23" name="option2" />Option 23

            <input type="checkbox" value="Option 3-1" id="option31" name="option3" />Option 31

            <input type="checkbox" value="Option 3-2" id="option32" name="option3" />Option 32

            <input type="checkbox" value="Option 3-3" id="option33" name="option3" />Option 33

            <input type="checkbox" value="Option 4-1" id="option41" name="option4" />Option 41

            <input type="checkbox" value="Option 4-2" id="option42" name="option4" />Option 42

            <input type="checkbox" value="Option 4-3" id="option43" name="option4" />Option 43


text:
Q: Gradle: download gradle takes "very long time", activity_main.xml keeps showing "Loading" I have installed Android Studio today. I'm a newbie to Android development. I know that it has been asked several times, but my Android Studio is most updated as of now, so none of the solution seems to work. [AndroidStudio v3.6]
After the installation got over, I attempted to create an Empty Project. It opened the whole project as seen below,

After waiting for 7+ minutes (bottom-left), gradle is still not downloaded, and the activity_main.xml file keeps showing "Loading".
Solution 1 - Change the gradle location
I found this location to C:\Users\RAHUL.LAPTOP-DISIIAS2\.gradle\wrapper\dists\gradle-5.6.4-all\ankdp27end7byghfw1q2sw75f, but it contains two files - one is gradle-5.6.4-all.zip.part and other is gradle-5.6.4-all.zip.lck file.
Solution 2 - Invalidate and restart
Doesn't seem to work
Solution 3 - Change gradle settings to work in offline mode
The version I'm using doesn't have the option

How can I fix it?

Here is my gradle-wrapper.properties file:

A: First, check if you are connected to http\://services.gradle.org/distributions with ping command in Command Prompt. If you are connected, then change Proxy Settings in Android Studio to Use System Proxy. If it is downloading slowly again, your internet connection may be slow. Or you best fallow guidelines in this link : Gradle Download: Installing Manually
Then work in offline mode will appear in your settings.


text:
Q: ¿Cómo puedo poner caracteres tales como el ruso o el chino en un JLabel? Mi problema es el siguiente, al cambiar de idioma sea francés, portugués, inglés, etc., lo hace satisfactoriamente, sin embargo al intentar cambiarlo a ruso o chino no es así.
Las opciones del menú son JLabel y es con este con el que da problemas. En versiones anteriores estas opciones eran JMenuItems y todo funcionaba bien. Por eso quería saber si hay una línea de código o clase que se usa para permitir que estos caracteres puedan ser ingresados.
. En la aplicación uso varios archivo-de-propiedades (.properties) con los textos de esta y su idioma correspondiente, y al colocarlo en cualquier jlabel pasa lo antes mencionado.  Esto es lo que tengo en el fichero que contiene al chino, similar a lo que tiene el ruso:
[4]: https://i.stack.imgur.com/Y5Lrj.png

A: Puedes poner caracteres en ruso o Chino si utilizas Unicode en el texto de tu label.
Por ejemplo. El siguiente código imprime un carácter en chino en un Label de un dialogo.
public class Ejemplo {

   public static void main(String[] args)
   {

      JFrame f = new JFrame();
      // en uniconde 8FCA es un código de caracter chino el escape \u
      // indica que el texto es uniconde.
      f.getContentPane().add(new JLabel("\u8FCA" ));
      f.setLocationRelativeTo(null);
      f.pack();
      f.setVisible(true);
   }

}

Con lo agregado debo decirte que lo de los archivos properties para los idiomas es lo correcto.
En el siguiente ejemplo estoy mostrando un combo donde muestro la palabra hola en varios idiomas (lo comento para que sirva de muestra a alguna otra persona que tenga duda y quiera ver un ejemplo completo).
public class EjemploIdioma {

   public static void main(String[] args) {

      // se obtiene el idioma local
      Locale locale = Locale.getDefault();

      // se carga el recurso del directorio i18n todos los recursos inician con el
      // prefijo i18n
      ResourceBundle rb = ResourceBundle.getBundle("i18n/i18n", locale);
      final JFrame f = new JFrame();

      // se indica que el frame estará dividido en regiones (norte, sur, este, oeste y centro
      ((JPanel) f.getContentPane()).setLayout(new BorderLayout());

      // se agrega una etiqueta fija a la region norte
      f.getContentPane().add(new JLabel("Ponga un texto"), BorderLayout.NORTH);

      // se crea un combo con los codigos de idioma y lenguajes soportados
      final JComboBox combo = new JComboBox(new String[]{
     "es_ES",
      "es_MX",
      "en_US",
      "fr_FR",
      // este es el chino
      "zh_CN",
      // este es el ruso
      "ru_RU"
      });

      // se carga una propertie en una etiqueta inicialmente
      final JLabel etiquetaConLeyenda = new JLabel(rb.getString("leyenda"));

      // se agrega un evento al combo para que al elegir un nuevo código de idioma-pais
      combo.addActionListener(new ActionListener() {

     // este evento cambia el idioma en que se presenta la etiqueta
     @Override
     public void actionPerformed(ActionEvent e) {
        System.out.println("Cambiando por " + combo.getSelectedItem() + "");
        String texto = combo.getSelectedItem() + "";
        int indice = texto.indexOf('_');
        String idioma = texto.substring(0, indice);
        String pais = texto.substring(indice + 1);
        System.err.println(" idioma " + idioma + " pais " + pais);

        // se genera un Locale con los datos del idioma y el pais
        Locale locale = new Locale(idioma, pais);

        // se vuelve a recuperar el ResourceBundle
        ResourceBundle rbInterno = ResourceBundle.getBundle("i18n/i18n", locale);
        System.out.println("el locale es " + locale);

        // se imprime el texto en consola para verificar que se ha leido correctamente
        System.out.println("El texto es " + rbInterno.getString("leyenda"));

        // se asigna el nuevo texto a la etiqueta
        etiquetaConLeyenda.setText(rbInterno.getString("leyenda"));

        // se repinta la pantalla
        f.repaint();
     }
      });

      // se agrega el combo de seleccion de idioma al centro del frame
      f.getContentPane().add(combo, BorderLayout.CENTER);

      //se agrega la leyenda traducida en la parte infrerior de la pantalla
      f.getContentPane().add(etiquetaConLeyenda, BorderLayout.SOUTH);

      // se centra el frame
      f.setLocationRelativeTo(null);

      // se auto ajusta la pantalla
      f.pack();
      // se pone si visible la pantalla
      f.setVisible(true);

      // se indica que al cerrar el frame se termina la aplicación
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

   }

}

En un directorio llamado i18n tengo todos los archivos de idioma
i18n  <- directorio
   i18n.properties         <- he puesto lo mismo que en español de españa
   i18n_en_US.properties   <- ingles estadounidense
   i18n_es_ES.properties   <- español de España
   i18n_es_MX.properties   <- español de México
   i18n_fr_FR.properties   <- frances
   i18n_ru_RU.properties   <- ruso
   i18n_zh_CN.properties   <- chino

El último archivo es el del chino y el penúltimo es el del ruso.
En el archivo properties del chino tengo:
leyenda=\u4f60\u597d

En el archivo properties del ruso tengo:
leyenda=\u0417\u0434\u0440\u0430\u0432\u0441\u0442\u0432\u0443\u0439\u0442\u0435

En el archivo properties del frances tengo:
leyenda=Salut

En el archivo properties del español mexicano tengo:
leyenda=\u00bfQu\u00e9 onda?

En el archivo properties del español de España tengo:
leyenda=Hola

La ejecución para el ruso es:

La ejecución para el chino es:

Espero que lo que te he puesto te ayude con tu problema si no es así entonces es necesario ver tu código para ayudarte.


text:
Q: Get items from DataTemplate for ArtOfTest controls I have this kind of object in code:
ArtOfTest.WebAii.Controls.Xaml.Wpf.ListBox

Items of it are in ItemTemplate. I have collection of it:
var listBoxItems = repairComapanyHintsList.Find.AllByType<ListBoxItem>();

and I want to get control from that DataTemplate. How can I do it? That solution doesn't work for DataTemplate (for other situations it's ok):
var textBlock = listBoxItem.Find.ByName("Name");

How can I get it? I tried this solution too, but that controls (from ArtOfTest) doesn't DependencyObject:
How can I find WPF controls by name or type?
I want to select one element depend of that TextBox text value.

A: I solved it, but it is not very good solution. It works for me and maybe it will help somebody.
I do it like that:
var listBoxItem = repairCompanyList.Find.AllByType<ListBoxItem>().FirstOrDefault(r => r.Text == "Name");
Assert.IsNotNull(listBoxItem, "Lack of expected list box item");
listBoxItem.User.Click();

I checked


text:
Q: Time complexity of a function with recursive calls f(n / 2) and f(n - 2)? I'm given this function and want to know the time complexity:
int f2(int n) {
    if(n<2) return 1;
    return f2(n/2)+f2(n-2);
}

I calculated its runtime to be O(n2) using the telescopic expansion method.  Is this correct?
Edit: After reconsidering, I found that this function has a similar structure to mergesort, which has complexity Θ(n log n).  Is that correct?

A: Suppose that it's polynomial in n, i.e. that the running time T(n) is at most a*nb for some constants a and b.  Then, we have:
T(n) = T(n/2) + T(n-2)
     = a*(n/2)^b + a*(n-2)^b
     = a/2^b * n^b + a*n^b + (lower-order terms)
     = a*n^b * (1/2^b + 1) + (lower-order terms)

Where the (lower-order terms) consist of sums and differences of n raised to powers strictly less than b.  For sufficiently large n, the a*nb * (1/2b + 1) term will dominate the lower-order terms, and that will always be larger than a*nb, so it's not true that T(n) is O(nb) for any constant b.
Now suppose that it's exponential in n, i.e. that T(n) is at most a*bn for some constants a and b.  Then:
T(n) = T(n/2) + T(n-2)
     = a*b^(n/2) + a*b^(n-2)
     = a*b^n * (b^(-n/2) + 1/b^2)

Now if b > 1 and n >= -2 log(1 - 1/b2) / log(b), then:
n >= -2 log(1 - 1/b^2) / log(b)
-n/2 <= log(1 - 1/b^2) / log(b) = log_b(1 - 1/b^2)
b^(-n/2) <= 1 - 1/b^2
b^(-n/2) + 1/b^2 <= 1
T(n) = a*b^n * (b^(-n/2) + 1/b^2) <= a*b^n * 1 = a*b^n

Hence, for any a > 0 and b > 1, there exists an N (equal to -2 log(1 - 1/b2) / log(b)) such that for all n >= N, T(n) <= a*b^n.
So what does this say?  T(n) is more than polynomial (for any polynomial; that also includes polylogarithmic functions, such any polylogarithmic function is o(a larger non-logarithmic polynomial)), but T(n) is less than any exponential.  I'm not sure if there's a simple formulation for the exact result, but those are some useful bounds.
EDIT
As nhahtdh points out, this makes the running time something called quasi-polynomial time.

A: TL;DR: I think the recurrence is nO(log n), which is super-polynomial but subexponential.  I don't have a matching lower bound and I doubt this is tight, but it's progress!
I think I can get an upper bound that's subexponential but super-polynomial.  Combined with @Adam Rosenfield's answer that shows that there's no polynomial bound, this shows that

*

*The recurrence has no polynomial bound, but

*Any exponential bound must be weak.

The recurrence we want to solve is

T(n) = T(n - 2) + T(n / 2) + 1
T(1) = T(2) = 1

One idea I had was that we might be able to evaluate this recurrence in a particular order.  Suppose you want to evaluate T(n).  Doing this for one step yields

T(n - 2) + T(n / 2) + 1

Now, suppose we expand out the T(n - 2) term.  This gives

T(n - 4) + T(n / 2 - 1) + T(n / 2) + 2

Now, expand the n - 4 term.  Doing this gives

T(n - 6) + T(n / 2 - 2) + T(n / 2 - 1) + T(n / 2) + 3

We can repeat the process of expanding out the subtractive term (the term of the form T(n - 2k)) over and over again.  So what happens if we expand it out to the point where n - 2k is about n / 2?  That's going to happen about n / 4 times.  If we do this, we get that

T(n) = T(n / 2) + T(n / 2) + T(n / 2 - 1) + T(n / 2 - 2) + ... + T(n / 2 - n / 4) + n / 4

I'm going to make the assumption that T(n) is nondecreasing.  If we do this, we get that

T(n) ≤ T(n / 2) + T(n / 2) + T(n / 2) + ... + T(n / 2) + n / 4
T(n) ≤ (n / 4 + 1) T(n / 2) + n / 4

I'm going to be a bit rough with the math here and make another simplification: instead of having the coefficient of T(n / 2) be (n / 4 + 1), I'm just going to have it be n / 4.  I know this isn't safe, but I'm going to conjecture that it doesn't mess with the result too much.  It would be a good idea to double-check that the rest of this still works after doing that, though!
This means that we can simplify our above recurrence (roughly) to get that

T(n) ≤ (n / 4) T(n / 2) + n / 4

This is something much easier to work with and we can now try to solve it directly.  We'll use the iteration method and just keep plugging it into itself over and over until we spot a pattern.  If we do this, we see the following pattern:

T(n) ≤ (n / 4) T(n / 2) + n / 4
≤ (n / 4)((n / 8) T(n / 4) + n / 8) + n / 4
= (n2 / 32) T(n / 4) + n / 4 + n2 / 32
≤ (n2 / 32) ((n / 16) T(n / 8) + n / 16) + n / 4 + n2 / 32
= (n3 / 512) T(n / 8) + n / 4 + n2 / 32 + n3 / 512
≤ (n3 / 512) ((n / 32) T(n / 16) + n / 32) + n / 4 + n2 / 32 + n3 / 512
= (n4 / 16384) T(n / 16) + n / 4 + n2 / 32 + n3 / 512 + n4 / 16384

Let's look at the pattern that's emerging.  After doing this k times, the coefficient of T(n / 2k) is nk divided by some power of two.  Those powers of two so far are 4,  32, 512, 16384.  Those numbers don't appear to have any obvious pattern to them, but if we rewrite them as 22, 25, 29, 214 we see that they follow the pattern 0, 2, 5, 9, 14, ... .  This is one less than the triangular numbers 1, 3, 6, 10, 15, ... .  This isn't a coincidence: if you think about it, the denominator keeps getting multiplied by the next power of two every time we expand out the recurrence, which increases the exponents on the powers of two from one triangular number to the next.  Therefore, we'd expect the denominator after k iterations to be given by

2(k + 1)(k + 2) / 2 - 1

After doing that, the remaining terms are the sum of powers of n divided by powers of two raised to various triangular numbers.  Therefore, if we expand things out k times, we get

T(n) ≤ (nk / 2(k + 1)(k + 2) / 2 - 1) T(n / 2k) + Σi = 0k (ni / 2(i + 1)(i + 2) / 2 - 1)

Okay!  So that's a mess, but it's not all that bad.  We know that the recursion stops as soon as n / 2k = 1, which happens when k = lg n.  To make things a bit simpler, I'm going to change the base case so that the recursion stops when n / 2k = 2, which happens when k = lg n - 1.  This doesn't change anything by more than a constant factor.  So, if we substitute in k = lg n - 1into the above formula, we can simplify to get a closed-form expression for an upper bound.  Doing this gives the following:

T(n) ≤ (nk / 2(k + 1)(k + 2) / 2 - 1) T(n / 2k) + Σi = 0k (ni / 2(i + 1)(i + 2) / 2 - 1)
= (nlg n - 1 / 2(lg n)(lg n + 1) / 2 - 1) T(2) + Σi = 0lg n - 1 (ni / 2(i + 1)(i + 2) / 2 - 1)

Oof, that's not pretty.  However, it's not as bad as it might seem.  Let's look at the denominator of the first term:

2(lg n)(lg n + 1) / 2 - 1

Using basic laws of exponents, we get that

2(lg n)(lg n + 1) / 2 - 1
= (2lg n)(lg n + 1) / 2 - 1
= n(lg n + 1) / 2 - 1

That's not so bad!  So if we take the expression

nlg n - 1 / 2(lg n)(lg n + 1) / 2 - 1

We see that it simplifies as follows:

nlg n - 1 / 2(lg n)(lg n + 1) / 2 - 1
= nlg n - 1 / n(lg n + 1) / 2 - 1
= n(lg n - 1 - ((lg n + 1) / 2 - 1))
= n(lg n - (lg n + 1) / 2)
= n(2 lg n - lg n - 1) / 2)
= n(lg n - 1) / 2)
= nO(lg n)

Nifty!  That leading term ends up being of the form nO(lg n)!
So what about the rest?  Well, we have this awful summation to contend with:

Σi = 0lg n - 1 (ni / 2(i + 1)(i + 2) / 2 - 1)

Fortunately, one thing we can note is that

ni / 2(i + 1)(i + 2) / 2 - 1
≤ ni / 2(i + 1)(i + 2)
≤ ni / 2(i + 1)
≤ ni / 2i
= (n / 2)i

So if all we want to do is upper-bound the summation, we can do so by using this much simpler sum:

Σi = 0lg n - 1 (n / 2)i

Since n / 2 > 0, this sum is in turn upper bounded by

Σi = 0lg n - 1 (n / 2)lg n - 1
= (lg n)(nlg n - 1) / (2lg n - 1)
= (2 lg n)(nlg n - 1) / n
= (2 lg n)nlg n - 2
= nO(lg n)

And bingo, the second term in that awful sum is also nO(lg n)!  This means that we have that T(n) = nO(log n).  This bound isn't necessarily tight, but it does show that the the recurrence is definitely sub-exponential, since nO(log n) grows more slowly than any exponential function!
Hope this helps!

A: I think it's O(2^sqrt(n))
You have T(n) = T(n/2) + T(n-2).
Plugging in the solution, dividing by 2^sqrt(n), and given n → ∞:
2^sqrt(n) = 2^sqrt(n/2)  +  2^sqrt(n-2)
---------   -----------     -----------
2^sqrt(n)    2^sqrt(n)       2^sqrt(n)

1 = 2^sqrt(-n/2) + 1

And 2^sqrt(-n/2) → 0

A: T(n) = T(n/2) + T(n-2) + 1
we know that T(n-2) > T(n/2)
we can say that:
T(n) = 2T(n-2) + 1
so T(n-2) = 2T(n-4) + 1
T(n) = 4T(n-4) + 2
T(n) = 8T(n-6) + 3
T(n) = (2^k)T(n-2k) + k
since we know that T(1) = 1
then n-2k = 1 -> k = (n-1)/2
T(n) = 2^((n-1)/2)T(1) + (n-1)/2
T(n) = 2^((n-1)/2) + (n-1)/2
T(n) = 2^((n-1)/2)
There must be a better solution though.

A: There's always the empirical approach — time it...
#include "timer.h"
#include <stdio.h>

static
int f2(int n)
{
    if (n < 2)
        return 1;
    return f2(n/2) + f2(n-2);
}

int main(void)
{

    printf("Fast:\n");
    for (int i = 1; i <= 512; i *= 2)
    {
        Clock clk;
        clk_init(&clk);
        clk_start(&clk);
        long sum = 0;
        for (int j = 0; j < 100; j++)
            sum += f2(i);
        clk_stop(&clk);
        char buffer[32];
        printf("%8d: elapsed %10s s; sum = %12ld\n",
               i, clk_elapsed_us(&clk, buffer, sizeof(buffer)), sum/100);
    }

    printf("\nSlow:\n");
    for (int i = 512; i < 1024; i += 16)
    {
        Clock clk;
        clk_init(&clk);
        clk_start(&clk);
        long sum = 0;
        for (int j = 0; j < 100; j++)
            sum += f2(i);
        clk_stop(&clk);
        char buffer[32];
        printf("%8d: elapsed %7s s; sum = %12ld\n",
               i, clk_elapsed_ms(&clk, buffer, sizeof(buffer)), sum/100);
    }

    return 0;
}

Results:
For the record, the test was run on a MacBook Pro running Mac OS X 10.8.5, Intel Core i7 at 2.3 GHz, with 16 GiB RAM.
Fast:
       1: elapsed   0.000000 s; sum =            1
       2: elapsed   0.000001 s; sum =            2
       4: elapsed   0.000001 s; sum =            4
       8: elapsed   0.000002 s; sum =           10
      16: elapsed   0.000008 s; sum =           36
      32: elapsed   0.000045 s; sum =          202
      64: elapsed   0.000408 s; sum =         1828
     128: elapsed   0.005985 s; sum =        27338
     256: elapsed   0.139971 s; sum =       692004
     512: elapsed   5.273834 s; sum =     30251722

Slow:
     512: elapsed   5.286 s; sum =     30251722
     528: elapsed   6.370 s; sum =     36243644
     544: elapsed   7.609 s; sum =     43234278
     560: elapsed   8.949 s; sum =     51361196
     576: elapsed  10.397 s; sum =     60777212
     592: elapsed  12.171 s; sum =     71651844
     608: elapsed  14.394 s; sum =     84172786
     624: elapsed  16.716 s; sum =     98547380
     640: elapsed  19.176 s; sum =    115004102
     656: elapsed  21.985 s; sum =    133794468
     672: elapsed  25.295 s; sum =    155194954
     688: elapsed  29.170 s; sum =    179508916
     704: elapsed  33.456 s; sum =    207068524
     720: elapsed  38.317 s; sum =    238237116
     736: elapsed  43.776 s; sum =    273411566
     752: elapsed  49.878 s; sum =    313024652
     768: elapsed  56.979 s; sum =    357547444
     784: elapsed  64.456 s; sum =    407492292
     800: elapsed  72.980 s; sum =    463415834
     816: elapsed  82.535 s; sum =    525922004
     832: elapsed  93.062 s; sum =    595665060
     848: elapsed 104.886 s; sum =    673353212
     864: elapsed 118.038 s; sum =    759752270
     880: elapsed 132.569 s; sum =    855689292
     896: elapsed 150.487 s; sum =    962056258
     912: elapsed 166.065 s; sum =   1079814524
     928: elapsed 185.616 s; sum =   1209999302
     944: elapsed 206.875 s; sum =   1353724140
     960: elapsed 230.670 s; sum =   1512185428
     976: elapsed 256.718 s; sum =   1686667684
     992: elapsed 285.158 s; sum =   1878548866
    1008: elapsed 316.281 s; sum =   2089305684

I've not gone curve fitting that data.  Clearly, you could reduce or eliminate the iterations at the larger sizes, and so on and so forth (and that would avoid overflows that occur with 1024, and ...).
If someone's got some expertise in drawing graphs, it might show the result (logarithmic scale for the time).

A: I think it is exponential. Why? Every f(n) leads to calling f(n/2) and f(n-2).
Check this question for details:
Computational complexity of Fibonacci Sequence
This is fibonacci order complexity. Your function structure is similar.


text:
Q: Wordpress "redirected too many times" problem but only homepage url everyone I recently migrated my website from one host to another host (ionos to plesk vps), using all one migration plugin website migrated successfully but the website homepage URL shows "too many redirects"` the problem is the only homepage url is not working specifically but all my website pages, url, posts, and WordPress dashboard loading correctly.
I am using Cloudflare for dns & ssl, elementor, woocommerce, etc on my website, When I shift my website back to the old IP (host), the website works but in the new host website homepage url is not working.
the website only works when I disable the Cloudflare proxy so that means the problem is coming from the Cloudflare
fix I try:

*

*Changing the site url

*Changing Cloudflare ssl mode to full, flexible, and full strict

*creating a default .htaccess file

*I try to open the website in incognito mode and another device

*disabling the plugins etc (but nothing working for me)

If anyone can help me with this it would be greatly appreciated


text:
Q: How to update three similar fields on different tables with same data? I have two models Commuter and RideLaterRequest
RideLaterRequest table looks as follows.
create_table "ride_later_requests", force: :cascade do |t|
   t.string   "customer_name"
   t.string   "phone_number"
   t.string   "email"
end

These columns are getting created from a view file where user enters these details and get created by a controller action.
def complete_booking_request
   #create a record of name, phone_number,email on RideLaterRequest
end

view
<%= bootstrap_form_for @ride_later_request ,url: bookings_complete_booking_request_path, id: "get_otp_form", method: :post, remote:true do |f| %>

      <%= f.text_field :customer_name, hide_label:true, placeholder: 'Name', class:'form-control'%>
      <%= f.email_field :email,hide_label:true, placeholder: 'Email', class:'form-control' %>
      <%= f.telephone_field :phone_number, hide_label:true, placeholder: 'Mobile', class:'form-control'%>
<%end%>

Now I have another model Commuter with similar fields.
 create_table "commuters", force: :cascade do |t|
         t.string   "phone_number"
         t.string   "first_name"
         t.string   "email"
  end

Currently there is no option to create a commuter data from template. The fields in both the tables are supposed to carry same data. Seems like earlier developer just generated the table and went off.  How can I can update the phone,email, name from the RideLaterRequest to Commuter table at the time of creation itself?

A: You can use after_save callback to save Commuter data like these in RideLaterRequest model
    after_save { |ride_later_request_data|
      Commuter.create(
        phone_number: ride_later_request_data.phone_number,
        first_name: ride_later_request_data.customer_name,
        email: ride_later_request_data.email
      )
   }

Or you can crate a method like these
    after_save :save_commuter_data

    private

    def save_commuter_data
      Commuter.create(
        phone_number: self.phone_number,
        first_name: self.customer_name,
        email: self.email
      )
   end

A: You can use Active Record Callbacks like after_save/ after_create.
In model RideLaterRequest,
after_save :copy_data_to_commuter
private
def copy_data_to_commuter
  Commuter.create( phone_number: self.phone_number, first_name: self.customer_name, email: self.email )
end
Here self.phone_number gives the value from the object of RideLaterRequest class which is being saved. You can also use phone_number directly instead of self.phone_number


text:
Q: Searching a text in range based on a cell I have the following query for a formula in excel:
A1 = red;
A2 = yellow
From B2:Z2 somewhere there I have the text "blue"
How to create a formula that based on what I have in column A to check whether there is the text "blue" in the given range.
Thanks!

A: Assuming you have a list of colors in column A.
In row 1 columns B-Z you have a list of random words.
Shift A down by one row so that your list starts at A2.
=IF(A2<>"",IF(ISERROR(VLOOKUP(C5,$B$2:$Z$2,1,FALSE)),"Found","Not Found"),"")

Then drag down.
If the color in A* is within the B2:Z2 range then it returns "Found". If the color in A* is not found it returns "Not Found".
Is this what you were wanting?


text:
Q: Using CSV file in Django choices
I have this function that calls the choices and activates them in each Model, however, I would like to know if there is a way to use this CSV file automatically, without having to call it item by item...

def Equipe():
    with open("controle_pav/static/texto/equipes.csv", 'r') as arquivo:
        equipes = arquivo.read()
            EQUIPE = (
                ('equipes', equipes.split()[0]),
                ('equipes', equipes.split()[1]),
                ('equipes', equipes.split()[2]),
                        )
        return EQUIPE

Is there a way to use an iterator or something like that. ?
I tried to make a router with the for but I was not successful

A: You can use pandas to read the CSV as follows:
import pandas as pd
equipes = pd.read_csv("controle_pav/static/texto/equipes.csv", sep=" ", header=None)

equipes will be a pandas DataFrame, which supports all kinds of manipulation.

A: Pandas library could be your solution:
https://pandas.pydata.org/
Please explain more about your csv file and what your Equipe function should return exactly if you need further help


text:
Q: textarea + jquery proble I made some scripts in JS and connected it to html.
These two pieces of code are the same, but for textarea "name" works and for textarea "about" don't. Please help me!
HTML (it isn't the whole document):

  Назва:
 <textarea type="text" class="form-control" class="name" id="name"></textarea>

  Опис товару:
  <textarea type="text" class="form-control" class='about' id='about'></textarea>

JS:
jQuery(document).ready(function($){

    $("#name").change(function(){
        var name1 = $("textarea#name").val();
        $(this).next('.namme').text("Запам'ятовано");
        createCookie("namme", name1, "1");
    });
    $('.name').trigger('change');

    $('#about').change(function(){
        var about1 = $('#about').val();
        $(this).next('.abbout').text("Запам'ятовано");
        createCookie("abbout", about1, "1");
    });
    $('.about').trigger('change');

});

function createCookie(name, value, days) {
    var expires;

    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else {
        expires = "";
    }

    document.cookie = encodeURIComponent(name) + "=" +
        encodeURIComponent(value) + expires + "; path=/";
}

A: Well, on my browser your code as is works fine for both textareas, see below snippet:

jQuery(document).ready(function($){

    $("#name").change(function(){
        var name1 = $("textarea#name").val();
        $(this).next('.namme').text("Запам'ятовано");
        createCookie("namme", name1, "1");
    });
    $('.name').trigger('change');

    $('#about').change(function(){
        var about1 = $('#about').val();
        $(this).next('.abbout').text("Запам'ятовано");
        createCookie("abbout", about1, "1");
    });
    $('.about').trigger('change');

});

function createCookie(name, value, days) {
    var expires;

    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else {
        expires = "";
    }

    document.cookie = encodeURIComponent(name) + "=" +
        encodeURIComponent(value) + expires + "; path=/";
}

        Назва:
        <textarea type="text" class="form-control" class="name" id="name"></textarea>

        Опис товару:
        <textarea type="text" class="form-control" class='about' id='about'></textarea>


text:
Q: High availability solution for NodeJS, Nginx and MongoDB I need opinion and best practice from someone more experienced in configuring nginx+nodejs+mongodb.
I'm working on custom build cloud application based on MongoDB and NodeJS. As reverse proxy server I'm using nginx, and for manage NodeJS I'm using PM2. At this moment I have separate servers, one for MongoDB database and one for serving API application (Nginx + NodeJS). For now I'm using PM2 and I set up that API is running as cluster on 1-core VPS.
In future I will need to configure high availability solution. Regarding database I don't use any replication or clustering yet. I see lots of potential things to optimize in future and I believe that achieving HA is not to hard to achieve with this technologies but can someone say his opinion and what I should take care first? I don't have to much experience in configuring HA so every advice is good advice.
Thanks

A:
"I believe that achieving HA is not to hard ... I don't have to much experience in configuring HA"

There's an old saying that you should never say that don't have experience in something but you don't think it's difficult. How difficult it is you will find out in the worst possible time.
If you don't know how to do it then no one will answer it on Stack Overflow because it takes years to get the required experience. You would be better off by using working solutions instead of reinventing your own. For Mongo you can use Compose or mLab. For Node you can use Heroku or AWS Elastic Beanstalk. For static assets use MaxCDN or Cloudflare. There are much more services to choose from.
Of course if you can do it yourself better then Compose and Heroku then by all means go ahead and do it. But if you don't then you will save yourself a lot of trouble if you go with a working solution.
Another plus is that both Heroku and mLab gives you free plans to start developing right away without paying anything but as soon as your application gains some traction you are in a good place to start scaling it massively if you have to.
Even if you decide to roll your own solution then you should still read the documentation of all of those and similar services because they nicely explain the functionality that you will have o implement and the problems that you are going to face.


text:
Q: Laravel routing (?) problems So I just uploaded my site from my local dev environment to my server.
But there's a problem. Only the index page loads. I've mapped some
controllers to different routes like this:
//controller detection
Route::controller(Controller::detect());

//site routes
Route::get('/','site@index');
Route::get('about','site@about');
Route::get('blog','site@blog');
Route::get('downloads','site@downloads');
Route::get('products','site@products');
Route::get('shop','site@shop');

//admin routes
Route::get('login','admin@login');

//ajax functions
Route::get('loadnews/(:num)','ajax@loadnews');
Route::post('sendmessage','ajax@sendmessage');
Route::post('loadblog','ajax@loadblog');
Route::post('loadblogdetails','ajax@loadblogdetails');

Event::listen('404', function()
{
    return Response::error('404');
});

Event::listen('500', function()
{
    return Response::error('500');
});

Route::filter('before', function()
{
    // Do stuff before every request to your application...
});

Route::filter('after', function($response)
{
    // Do stuff after every request to your application...
});

Route::filter('csrf', function()
{
    if (Request::forged()) return Response::error('500');
});

Route::filter('auth', function()
{
    if (Auth::guest()) return Redirect::to('login');
});

And when I click on the links pointing to these routes, I've get a
simple Error: 324 (net::ERR_EMPTY_RESPONSE): from chrome.
How can I fix this?
The site currently located at: site

A: I was having a similar problem, and I resolved it deleting the line:

Route::controller(Controller::detect());

I'm using named Url's. Give it a try.

A: At least on my end I was able to fix this problem by adding. RewriteBase / to the .htaccess file. Now everything seems to be working properly.

A: Make sure you register the controller if you haven't.
Route::controller(array('site'));

If you're using Apache on your server, make sure mod_rewrite is on and configured as well as a decent .htaccess rule set, laravel comes with a pretty decent .htaccess for Apache servers.
Also make sure you have removed the 'index.php' base url from Application config.
These are probably the most common reasons why Routes don't work. You can also test your routes from the command line that makes this process a little simpler:
php artisan route:call get about

A: I had to put the root route, in your case :
Route::get('/','site@index');

at the bottom of the routes.php file

A: It appears you are using Linux, but in case this is applicable for future readers with the same issue:
For me, the issue was that I am running my app on Windows Server 2008 R2 and I hadn't set up the htaccess properly through my IIS Manager.  I hadn't realized I needed to do this because for other sites, my htaccess files were working fine, but none of them were using mod_rewrite.
The solution was to install "IIS URL Rewrite Module 2", which I then could use from the IIS Manager, where I would choose to "Import" everything from the default htaccess file included with Laravel.
After that, all pages loaded, not just the index.


text:
Q: python == python2 OR python == python3 ? How to package, distribute python py2k scripts? Depending on system, python==python2 or python==python3.
Executable Python scripts, starts with:
#!/usr/bin/env python
#!/usr/bin/env python2
#!/usr/bin/env python3...

For python py3k it is provided in documentation I should/can use it with version number, so I do this:
#!/usr/bin/env python3

But I've found a problem with py2k scripts.
While in py2k documentation it is written to use : #! /usr/bin/env python ,
on some *nix-es python py3k is default, so python==python3. (For example ArchLinux python package , here python package files).
How to package (configure,make) and/or prepare python scripts for distribution to handle that ?
I ask about making software packages that can be run easily by users (without modyfing their environment)
Can I do the same trick for python py2k scripts as for python py3k scripts and set it as : #!/usr/bin/env python2 ?
Can I be sure that each python py2k distribution contains python2 file, so #!/usr/bin/env python2 will work ?
If yes, why it is not proposed as standard, for example in python py2k documentation ?

A: A script can check its Python version and, if that's Python 3, re-start itself using Python 2. Add the following near the head of the script:
if sys.version > '3':
  python2 = os.popen('which python2 2> /dev/null').read().rstrip()
  if python2:
    args = sys.argv[:]
    args.insert(0,python2)
    os.execv(python2,args)
  else:
    sys.exit("%s requires Python Version 2 (python2 not in PATH)" % os.path.basename(__file__))

This uses the system's which command to locate python2 in the environment's PATH. It then relaunches itself with that (or aborts if unable to find it).
Note that the script does need to be valid Python 3 syntax for it to start in Python 3.
Also, any output should be flushed before the execv call or it will be lost. Adding, for example, sys.stdout.flush() just before the call to execv will flush any print statements.

A: On older versions, there may just be python instead of python2. To make your sheebang line clearer, you could create a link python2 -> python so you can use #!/usr/bin/env python2.

A: I think the "standard" is defined in https://www.python.org/dev/peps/pep-0394/

This PEP provides a convention to ensure that Python scripts can
  continue to be portable across *nix systems, regardless of the default
  version of the Python interpreter (i.e. the version invoked by the
  python command).

*

*python2 will refer to some version of Python 2.x.

*python3 will refer to some version of Python 3.x.

*for the time being, all distributions should ensure that python refers to the same target as python2.

*however, end users should be aware that python refers to python3 on at least Arch Linux (that change is what prompted the creation of
  this PEP), so python should be used in the shebang line only for
  scripts that are source compatible with both Python 2 and 3.

*in preparation for an eventual change in the default version of Python, Python 2 only scripts should either be updated to be source
  compatible with Python 3 or else to use python2 in the shebang line.


text:
Q: How can I achieve more control over my XFCE keyboard shortcuts? XFCE has a great keyboard commands editor in the window manager keyboard settings area. I can change the commands that open or close windows or move to workspaces etc. But it is a bit lacking.
What if I want the search prompt from alt+f2 to be called up by the home key instead?
Or what if I want the media button on my keyboard to launch my default media app etc?


text:
Q: what is a good structure to save this data C# WinForms:
The things I want to save:
name: string
previous value: double
new value: double

so each entity has those three fields, the number of them will not be too much at all, maybe 10 max. All I want to do with them is just to be able to add some members to it and then loop through them and read them later.
so one easy way would be having three arrays, one for each.
It is not really thay big of a deal to create a Class for it, etc..so I am looking for some good strudcutres that I can use, Arrays like what I said above?  any better choice?

A: There's nothing wrong with creating classes to hold custom data.
You can even create a private inner class if its not going to be used by anything else.
There is something wrong with using arrays for a need that doesn't require an indexed set of data.

A: Class or struct is clearly the way to go. If you want to avoid a class you could use a Dictionary<string, KeyValuePair<double, double>> where the key is the name and the KeyValuePair represents the previous and new values

A: class Foo
{
   public string Name { get; set; }
   public double PreviousValue { get; set; }
   public double NewValue { get; set; }
}

A: Create an object for them:
public class Foo
{
    public string Name { get; set; }

    public double Value { get; set; }

    public double OldValue { get; set; }
}

Then you can add them to a List and loop through them and access them:
foreach(var foo in myListOfFoos)
{
    // Do something with foo.Name, foo.Value, etc...
}

A: If you're into OOP (and you should) then everything is a class. What's the problem with the classes? They're not selected based on how big they are. If they model something real then they should exist.
I won't create anything different that what others have said.

A: What do you mean with "not really that big of a deal to create a class"?
Classes are not evil. They help structure your data. That's one of the main reasons why they have been invented. Make it a class. It won't kill your code's performance, but will definitely increase readability, maintainability and whatnot compared to using primitives and collections thereof.
If not for yourself, then for the poor chap that will eventually inherit your codebase.
Use a class.
I can point you to some good reading material on object orientation if needed.

A: I think that a class really is the most simple way to store this data. I know that you keep saying it's not a big enough deal to use a class, but if you need to save this data set easily for use later you really need to be using a class. You even said yourself that:

each entity has those three fields

The "entity" you're talking about is an object, which is an instance of a class. You can have a List<T> of the objects and iterate through them easily with a foreach.

A: If you don't want to create a class or struct then you could store your data in a list of tuples.
List<Tuple<string, double, double>> MyData = new List<Tuple<string, double, double>>();
MyData.Add(new Tuple<string, double, double>("test1", 1, 2));
MyData.Add(new Tuple<string, double, double>("test2", 3, 4));

If it were me though I would just go ahead and create a class, it will make it easier for future developers to figure out your code.


text:
Q: Is it possible to mask dns queries? Would it be possible to mask dns queries?
Example scenario : In a corporate network, can an end user machine mask it's dns queries as coming from another machine id.
Thank you.

A:
can an end user machine mask it's dns queries as coming from another machine id

Usually that's not called masking, that's address spoofing. Masking would usually mean making the DNS queries themselves look like something that's not DNS (e.g. through encryption). In your case they're still clearly DNS queries.
Anyway – If the intent is to trick the corporate admins, and if you're talking about another machine in the same network, then it's both a yes and a no:

*

*Yes, it is possible to send queries with a fake source IP address. In many networks (depending on switch-level security), it might be very difficult to tell the difference.

*No, your machine will not be able to actually use DNS this way – it will not receive responses to those fake queries because they'll get delivered to the other machine instead. So you cannot use this method to bypass tracking for yourself, only to incriminate somebody else.
Managed Ethernet switches usually have features to prevent local IP spoofing (e.g. IP-MAC binding, sticky MAC, etc.) but those need to actually be enabled in order to work, and it doesn't help when both machines are still behind the same unmanaged switch.


text:
Q: Registering Entity in Objectify having issue during test cases We have an project developed with Objectify4 and Spring3.1 and deployed and running on GAE and we are using IDE as STS.
When I do project build locally using Maven(cmd mvn install) the test cases are failing and throwing the following exception.
From the exception I observe it is failing while injecting Class1Service service class in test class Class1UnitTest (this is not only in this test class it is giving same exception in every test class wherever we are injecting any service class that extends AbstractBaseImpl).
In the exception stacktrace I see it is pointing to line of registering the Entity class(EntityClassA) in  AbstractBaseImpl.
In the Entitiy class EntityClassA we have used @Mapify, if I remove the @Mapify annotation in the entity class the test case are running without any bean initialisation issues.
I tried building project from STS and also from command still getting the same issue.
From the functionality point of view the application is working fine if I skip the testcases while building.Can anyone see similar issue with the entity having @Mapify defined and getting issue while registering in test case.
Thanks for your time
Here are the details,
EntityClassA.java
@Entity
public class EntityClassA {

    @Index @Mapify( ChildClassAMapper.class )
    private Map<Integer, ChildClassA> intervalToReward = new LinkedHashMap<>();

    @Embed
    public static class ChildClassA extends ClassA {
        private static final long serialVersionUID = 49769454099624971L;
        private int …;
        private long …;

        public ChildClassA(  ) {
            …..
        }
    }

    public static class ChildClassAMapperMapper implements Mapper<Integer, ChildClassA> {

        @Override
        public Integer getKey( ChildClassA value ) {
            return value.getInterval();
        }
    }
}

AbstractBaseImpl.java
@Component
public abstract class AbstractBaseImpl implements BaseService {

    static {
Line-12     ObjectifyService.register( EntityClassA.class );
    }
}

ChallengeServiceImpl.java
@Service
@Slf4j
public class Class1ServiceImpl extends AbstractBaseImpl implements Class1Service {

    // method to store data using objectify..

}

CoreBaseTest.java
@ContextConfiguration(
    locations = { "classpath*:META-INF/spring/core-applicationContext.xml" } )
@RunWith( SpringJUnit4ClassRunner.class )
public abstract class CoreBaseTest {

    private final LocalServiceTestHelper helper = new LocalServiceTestHelper(
        new LocalDatastoreServiceTestConfig().setApplyAllHighRepJobPolicy(),
        new LocalBlobstoreServiceTestConfig(),
        new LocalTaskQueueTestConfig(),
        new LocalMemcacheServiceTestConfig() );
}

Class1UnitTest.java
public class Class1UnitTest extends CoreBaseTest {

    @Resource( name = "class1Service" )
    private Class1Service class1Service;

    //Testcases…

}

core-applicationContext.xml

<bean id="class1Service" class="com.suvs.app.core.spring.services.Class1ServiceImpl" />

Exception
TestCrud(test.core.Class1UnitTest')  Time elapsed: 0.163 sec  <<< ERROR!

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'test.core.Class1UnitTest': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'class1Service' defined in URL [file:/Users/suvs/core-app/target/classes/META-INF/spring/core-applicationContext.xml]: Instantiation of bean failed; nested exception is java.lang.AssertionError
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:307)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:374)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:321)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:290)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
    at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
    at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
    at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'class1Service' defined in URL [file:/Users/suvs/core-app/target/classes/META-INF/spring/core-applicationContext.xml]: Instantiation of bean failed; nested exception is java.lang.AssertionError
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:997)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:943)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:443)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:417)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:559)
    at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:150)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:304)
    ... 32 more
Caused by: java.lang.AssertionError
    at com.googlecode.objectify.impl.translate.CreateContext.enterCollection(CreateContext.java:70)
    at com.googlecode.objectify.impl.translate.CollectionTranslatorFactory.create(CollectionTranslatorFactory.java:49)
    at com.googlecode.objectify.impl.translate.TranslatorRegistry.create(TranslatorRegistry.java:90)
    at com.googlecode.objectify.impl.translate.ClassTranslator.(ClassTranslator.java:52)
    at com.googlecode.objectify.impl.translate.EmbedClassTranslatorFactory.create(EmbedClassTranslatorFactory.java:43)
    at com.googlecode.objectify.impl.translate.TranslatorRegistry.create(TranslatorRegistry.java:90)
    at com.googlecode.objectify.impl.translate.MapifyTranslatorFactory.create(MapifyTranslatorFactory.java:62)
    at com.googlecode.objectify.impl.translate.TranslatorRegistry.create(TranslatorRegistry.java:90)
    at com.googlecode.objectify.impl.translate.ClassTranslator.(ClassTranslator.java:52)
    at com.googlecode.objectify.impl.translate.EntityClassTranslator.(EntityClassTranslator.java:46)
    at com.googlecode.objectify.impl.Transmog.(Transmog.java:49)
    at com.googlecode.objectify.impl.ConcreteEntityMetadata.(ConcreteEntityMetadata.java:58)
    at com.googlecode.objectify.impl.Registrar.register(Registrar.java:74)
    at com.googlecode.objectify.ObjectifyFactory.register(ObjectifyFactory.java:180)
    at com.googlecode.objectify.ObjectifyService.register(ObjectifyService.java:62)
    at com.suvs.app.core.spring.services.AbstractBaseImpl.(AbstractBaseImpl.java:12)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:76)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:990)
    ... 45 more

A: Does ChildClassA also contain a collection, thus you are trying to nest two embedded collections? It looks like it from that stacktrace. This is not possible in Objectify4. I highly recommend the upgrade to 5.


text:
Q: Using the KKT conditions on a system with a large number of inequality constraints Does it make sense to use the KKT conditions to transform an optimization problem with a large number of inequality constraints into an unconstrained optimization problem?  I don't yet fully understand the KKT formulation, however I have seen a factor of $2^n$ mentioned.  So before I spend more time investigating KKT, is it feasible to use for a system of say 50 inequality constraints?
To give more detail, I have $N+1$ constraints with the following form:
$C_1$: $\sum_{i=1}^N x_i \le Q$
$C_2...C_{N+1}$: $C_i \ge 0$; $i=1...N$
Does KKT infer I have to investigate $2^{N+1}$ possibilities?


text:
Q: Setting hovered style for material-ui IconButton According to React Material-UI docs, I have a prop hoveredStyle to work with: http://www.material-ui.com/#/components/icon-button
I want to use IconButton for two purposes:

*

*Utilize its tooltip prop for accessibility

*I can wrap Material-UI svg icons directly

However, I don't want the cursor to change to a pointer when I hover (which is default behavior I believe), so I changed it like so.
import DeleteIcon from 'material-ui/svg-icons/action/delete

const hoveredStyle = {
    cursor: 'initial'
}

render() {
    return (
        <IconButton tooltip="Description here" hoveredStyle={hoveredStyle}>
            <DeleteIcon />
        </IconButton>
    )
}

This works fine, except that the split millisecond that I enter hover mode on the icon, I still see the default hand pointer before it gets set to the normal mouse pointer. How do I approach this?

A: Some notes for people stumbling upon this thread. If you are having a problem with hover styles for an icon if you are using Material-ui you might have forgot something.
In my case I used a <KeyboardArrowLeft/> and wrapped it in a <Tooltip/>. I could not get hover styles in there at all including a simple hand "cursor". I had to wrap the icon with <IconButton>. It is in that element where you can pass styles.
While the example that was provided before as the "accepted answer" does solve the initial problem, it is not production level.
If you are using reactjs you will need to import the following into your component, switch with your respective icon
import Tooltip from '@material-ui/core/Tooltip';
import IconButton from '@material-ui/core/IconButton';
import KeyboardArrowLeft from '@material-ui/icons/KeyboardArrowLeft';

In the icon wrap as follows
<Tooltip title="">
  <IconButton
    aria-label=""
    style={componentStyle.iconBack}
  >
    <KeyboardArrowLeft
      style={componentStyle.eventHeadingBack}
      onClick={}
    />
  </IconButton>
</Tooltip>

*

*In the Tooltip, give it a title of what the user should expect when clicking the button.

*In the IconButton, add some description for aria (screen readers) like "back to home page". In the style, use a class. You will have a const that you can use for that component you are working on, then give the classname for the actual element a descriptive title. This is where you can control the cursor and hover actions.

*

*In the actual icon, give it a class so you can do things like change color.

Now you will need to style the component, name it however you want but ideally according to the components purpose.
const componentStyle = {
  container: {
    display: 'flex',
    width: '100%',
    height: '100vh',
    backgroundColor: '#212121',
  },
  iconBack: {
    cursor: 'crosshair'
  },
  eventHeadingBack: {
    color: '#fff',
    marginRight: '16px'
  }
}

A: I just tested adding a cursor: default to the style of both IconButton and DeleteIcon and it seems to have the functionality you want. (No pointer cursor on hover.)
const noPointer = {cursor: 'default'};
return (
  <div>
    <IconButton tooltip="Description here" style={noPointer}>
      <DeleteIcon style={noPointer} />
    </IconButton>
  </div>
);


text:
Q: Understanding Illegal Generic Cast I'm having some trouble understanding why a cast I'm performing is throwing runtime exceptions stating that it's an illegal cast.  I did a bit of research and found this answer, which lead me to the MSDN article Covariance and Contravariance in Generics.  However, I'm still a bit confused so if anyone can help clarify it would be greatly appreciated.
Here's the object hiearchy for 2 class types:
IMongoEntity (interface)
  |   - MongoEntity (abstract)
  |     |    -SalesProject (concrete)
  |     |    -ManagementProject (concrete)

IEntityService<T> where T : IMongoEntity (interface)
  |      -EntityService<T> where T : IMongoEntity (concrete superclass)
  |       |    - MgmtService : EntityService<ManagementProject> (subclass)
  |       |    - SalesService : EntityService<SalesProject> (subclass)

The two non generic services were only created so I could create some specific methods that only apply to those specific types (predefined lookups into the db essentially).
I then have this line, which throws the InvalidCastException:
IEntityService<IMongoEntity> service = fromsales ?
    (IEntityService<IMongoEntity>)salesService :
    (IEntityService<IMongoEntity>)mgmtService;

Since both services are derived from the same interfaces & abstract classes and the type parameters used are derived from the same abstract class, then why is this cast illegal?
NOTE:  I have workarounds for this, so I'm not really looking for a solution, but instead I want to understand why this is not allowed.

A: MyType<Base> and MyType<Derived> do not have any inheritance relationship, even if Derived derives from Base. The two generic types are just two different types.
One way to come around this problem is to have a non-generic interface as base interface:
public interface IEntityService
{
    void DoSomething(object item);
}

public interface IEntityService<T> : IEntityService
{
    void DoSomething(T item);
}

This pattern is used in the .Net Class Library (for e.g. IEnumerable/IEnumerable<T>, IList/IList<T>).
If you know that your interface uses the generic type (T) only for outputs, you can use the out keyword IMyInterface<out T>. You can then provide a more derived type for T. This is called covariance. The return values of the methods will then yield a more derived type as expected by the consumer and this is ok.
If it uses the generic type only for inputs, use the in keyword IMyInterface<in T>. You can then provide a less derived type for T. This is called contravariance. The input arguments of the methods will then get a more derived type as expected and this is ok.


text:
Q: Is there an $\epsilon$- self isometry such that it is not an isometry? Let $f:(X, d)\to (X, d)$ be a a bijection on metric space $(X, d)$.
For $\epsilon>0$, the bijection map $f$ is called $\epsilon$- self isometry, whenever $$\sup_{x,y\in X}|d(x, y)- d(f(x), f(y)|\leq \epsilon.$$ It is clear that if $f:(X, d)\to (X, d)$ is an isometry ( that is $d(f(x), f(y))=d(x, y)$), then it is an $\epsilon$- self isometry, for all $\epsilon>0$.
Question. Let $\epsilon>0$ be given. Is there an $\epsilon$- self isometry such that it is not an isometry?

A: Let $X$ be a metric space whose topology is nondiscrete, i.e. $X$ contains a non-isolated point $x$. Then for each $\epsilon>0$ there exists an $\epsilon$-isometry $f: X\to X$ which is not an isometry. To prove this, take a point $x\in X$ which is the limit of a sequence of pairwise distinct points $x_n$. Now, take $f(x)=x_n$, $f(y)=y$ for all $y\in X - \{x\}$. Then for all sufficiently large $n$, $f$ is an $\epsilon$-isometry but not an isometry.
Edit. Since you want bijective maps, take $f(x)=x_n, f(x_n)=x$ and $f(y)=y$ for all $y\notin \{x, x_n\}$. This map is discontinuous at $x$, hence, not an isometry.

A: Consider $$X=\{ (x,0)\in \mathbb{E}^2| x\geq 1\} \cup \{ (x,1/x) \in
 \mathbb{E}^2| x\geq 1\} $$ which have a metric induced from the standard metric on
$\mathbb{E}^2$.
Define $f_n(x,0)=(x,0),\ f_n(x,1/x)=(x,1/x)$ where $x<n$ and
$f_n(x,0)=(x,1/x),\ f_n(x,1/x)=(x,0)$ where $x\geq
n$.
So $$ ||f_n(p)-f_n(q)| -|p-q|| \leq |f_n(p)-p| + |f_n(q) -q| \leq
 \frac{2}{n}$$

A: Yes, there is an $\epsilon$-isometry of $\mathbb{R}^n$ which is not an isometry. One idea is to develop a map which contracts $\mathbb{R}^n$ near the origin, but only barely moves other points. This is the approach I'll take here.
Consider a "radial contraction function" $$g(r) \equiv \begin{cases}1 &\text{if }r \geq 1 \\ r^2 & \text{if }r < 1\\\end{cases}$$
As a first pass, let's define a bijection $\widetilde f: \mathbb{R}^n\rightarrow \mathbb{R}^n$ which scales each vector by an amount $g(||x||)$; that is, it scales each point by an amount that depends on how far the point is from the origin:
$$\widetilde f (x) \equiv g(||x||)\cdot x $$
Note how this bijection behaves: points outside the unit ball are not moved at all, while points within the unit ball are moved slightly closer to the origin. Moreover, intuitively, the radius of that unit ball constrains how far points can move: we must have that for every point $x\in \mathbb{R}^n$,
$$|x - f(x)| < 2$$
since points outside the unit ball don't move, and points within the unit ball remain within the unit ball.
Hence we have for all $x$ and $y$:
\begin{align}
d(|x-y|, |f(x)-f(y)|)  &\leq  |x - f(x)| + |f(y)-y| & \text{triangle inequality}\\
&\leq 2 + 2 & \text{unit ball constraint}\\
& = 4
\end{align}
So even this crude function $\widetilde{f}$ is an $\epsilon$-isomorphism (for $\epsilon = 4$) while definitely not an isomorphism (since points in the unit ball are brought closer together).
We can make this trick work more generally, for any $\epsilon > 0$, by shrinking the radius of the ball where points are allowed to move: define
$$f(x) = g\left(\frac{4}{\epsilon}||x||\right) \cdot x.$$
Scaling the argument of $g$ has the effect of shrinking the radius of the ball to size $\epsilon/4$. Hence, by the same reasoning we have already employed, we find that for all points $x$ and $y$,
$$d(|x-y|, |f(x) - f(y)|) \leq 4\frac{\epsilon}{4} = \epsilon.$$
Q.E.D.

A: Fix $\epsilon > 0$. If $f:X \to X$ is a bijection satisying $d(x, f(x)) \leq \epsilon/2$ for all $x$, then $f$ is an $\epsilon$-self isometry by the triangle inequality: For all $x$ and $y$ in $X$,
\begin{gather*}
  d(x, y) \leq d(x, f(x)) + d(f(x), f(y)) + d(f(y), y) \leq d(f(x), f(y)) + \epsilon, \\
  d(f(x), f(y)) \leq d(x, f(x)) + d(x, y) + d(f(y), y) \leq d(x, y) + \epsilon,
\end{gather*}
from which it follows at once that
$$
\bigl|d(x, y) - d(f(x), f(y))\bigr| \leq \epsilon\quad\text{for all $x$, $y$ in $X$.}
$$
Bijections of this type are easy to find in Euclidean space (the space of interest according to the comments): Just swap a pair of points whose distance is at most $\epsilon/2$. For a continuous example, take an arbitrary continuous bijection that fixes every point outside some ball of radius $\epsilon/4$, or use Anthony's idea of a small-time flow of a bounded vector field.

A: These are plentiful; we can even demand the map be a homeomorphism
Let $(X,d)$ be your favourite space with finite-diameter $D$ and $f : X \to X$ your favourite homeomorphism that is not an isometry. Let $(X,\rho)$ be a new metric space where we define. . .
$\displaystyle \rho(x,y) = \frac{\epsilon d(x,y)}{2D} \displaystyle$
Exercise: show $f$ is a homeomorphism but not an isometry on $(X,\rho)$.
We claim $f$ is an $\epsilon$ self isometry on $(X,\rho)$. This is because. . .
$\sup|\rho(x, y)- \rho(f(x), f(y)| \le \sup \Big (|\rho(x, y)|+ |\rho(f(x), f(y)|\Big) < 2$diam$(X,\rho)$
Exercise: show $(X,\rho)$ has diameter $\epsilon/2$.
We conclude $\sup|\rho(x, y)- d(f(x), f(y)| \le \epsilon$


text:
Q: simple sets, cofinite sets, filters Let $\mathcal S$ be the class of simple sets and $\mathcal C$ the class of cofinite sets. Prove that $\mathcal S\bigcup \mathcal C$ is a filter in $\mathcal E$.
Definitions:
An infinite set is "immune" if it contains no infinite c.e. set.
A c.e. set $A$ is simple if $\bar{A}$ is immune.
A filter of $\mathcal E$ is a subset of the lattice that is closed upward and under intersections.

A: Fairly Complete Outline: It suffices to show that $\mathcal{S} \cup \mathcal{C}$ is closed under (r.e.) supersets and intersections.

*

*Clearly every r.e. superset of a simple set is either simple or cofinite, and every superset of a cofinite set is cofinite, so $\mathcal{S} \cup \mathcal{C}$ is closed under supersets.

*Now suppose $A , B \in \mathcal{S} \cup \mathcal{C}$, and go through the cases to show that $A \cap B \in \mathcal{S} \cap \mathcal{C}$:

*

*If $A , B \in \mathcal{S}$, then $A \cap B$ is r.e. and co-infinite.  If $A \cap B$ were finite, then $A \cap \overline{ A \cap B } = A \cap \overline{B}$ would be an infinite r.e. subset of $\overline{B}$, and so $A \cap B$ must be infinite.  If $Z \subseteq \overline{A \cap B} = \overline{A} \cup \overline{B}$ is an infinite r.e. set, then, without loss of generality, $Z \cap A \subseteq \overline{B}$ is infinite (and r.e.), contradicting the simplicity of $B$!

*If $A \in \mathcal{S}$ and $B \in \mathcal{C}$, then $A \cap B$ is r.e., infinite and co-infinite.  If $Z \subseteq \overline{ A \cap B } = \overline{A} \cup \overline{B}$ is r.e., then $Z \cap B \subseteq \overline{A}$ is r.e., and so it must be finite, and so $Z$ itself is finite.  Thus $A \cap B$ is simple.

*If $A , B \in \mathcal{C}$, then $A \cap B$ is cofinite.


text:
Q: Avoid background color in image c# I have a image processing in my uwp app where i read the colors of the image and display the results based on the matching colors.
To read the colors i use Color theif and get the color palette.
The problem is at times the background color is considered as the primary color since it is dominent

In the above image the second color must be the primary color of the image which i need. But the gray is obtained as primary color.

A: Since image background could be of any color, I think the best bet is to pick colors from the corners of an image (which more likely to be of background color) and compare them against the colors of the palette returned by ColorThief using the Color difference formula.
You could then use color differences and the amounts of times the color from ColorThief palette was a match to corner pixel color as weight coefficients to decide which one of the ColorThief palette colors is more likely to be the background color of the image.


text:
Q: Should I use Caller and Called arguments or From and To in Twilio callback request body I am receiving the same information in the following POST body arguments from twilio callback requests:

*

*Caller and Called

*From and To
I couldn't find any documentation about the first arguments. Are Caller and Called deprecated?

A: To and From should be used.
Caller and Called are duplication of From and To. Used for consolidation data for additional info, like FromCity, FromState, ToCity, ToState etc. If such data is available.
https://www.twilio.com/docs/voice/twiml#request-parameters


text:
Q: How do I write a generic udev rule to assign my network's interface name? I am trying to write a "generic" udev rule to assign an interface name to my NIC card.
For a particular application i require the ability to boot a headless server where the NIC can be changed at any point. However the Make and model of the NIC will stay the same.
so i have attacked the problem by trying to write a generic udev rule which will assign the required name (to be later matched to specific static network settings) to any NIC matching the Vednor and Model ID. my output of udevadm:
micromass@ComExATE:/sbin> sudo ./udevadm info --attribute-walk --query=all --pat          h=/sys/class/net/eth4
P: /devices/pci0000:00/0000:00:1c.5/0000:05:00.0/net/eth4
E: UDEV_LOG=3
E: DEVPATH=/devices/pci0000:00/0000:00:1c.5/0000:05:00.0/net/eth4
E: INTERFACE=eth4
E: IFINDEX=2
E: SUBSYSTEM=net
E: ID_VENDOR_FROM_DATABASE=Broadcom Corporation
E: ID_MODEL_FROM_DATABASE=NetXtreme BCM5761 Gigabit Ethernet PCIe
E: ID_BUS=pci
E: ID_VENDOR_ID=0x14e4
E: ID_MODEL_ID=0x1681

so my rule looked like this:
SUBSYSTEM=="net", ACTION=="add", ATTR{IDVENDOR_ID}=="0x14e4", ATTR{ID_MODEL_ID}=="0x1681", NAME="my-device"

However no luck. so i tried something a bit simpler and decided to match the first 3 sets of the MAC address (which are assigned to a vendor)
SUBSYSTEM=="net", ACTION=="add", ADDRESS=="00:30:64??:??:??", NAME="my-device"

Still no luck. i cant ever seem to change these rules to add symlinks instead of renaming.
Not sure where to go from here so any help would be great.

A: You misspelled the attribute name:
It's ID_VENDOR_ID. Not IDVENDOR_ID

A: Run udev debug and look at syslog, does it match your rules or not. What opensuse version do you use? Btw, I'm not sure you can add ? in MAC address field. First check if udev can rename interface at all in your setup (here is an example config).


text:
Q: Manifest merger failed with multiple errors, see logs even after setting export in all components I am getting below error while building apk. It is running properly on android device but apk is not build. I have set android:exported="false" in all activity, receiver and services.

Task :app:processDebugAndroidTestManifest FAILED
[androidx.test.espresso:espresso-core:3.2.0] /home/bansal/.gradle/caches/transforms-2/files-2.1/a88c494942c30cb858ca2f4a16161a0e/espresso-core-3.2.0/AndroidManifest.xml Warning:
Package name 'androidx.test.espresso' used in: androidx.test.espresso:espresso-core:3.2.0, androidx.test.espresso:espresso-idling-resource:3.2.0.
/home/bansal/Documents/Buyer/mycall-android/app/build/intermediates/tmp/manifest/androidTest/debug/manifestMerger12251506600435692045.xml Error:
Apps targeting Android 12 and higher are required to specify an explicit value for android:exported when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details.
/home/bansal/Documents/Buyer/mycall-android/app/build/intermediates/tmp/manifest/androidTest/debug/manifestMerger12251506600435692045.xml Error:
Apps targeting Android 12 and higher are required to specify an explicit value for android:exported when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details.
/home/bansal/Documents/Buyer/mycall-android/app/build/intermediates/tmp/manifest/androidTest/debug/manifestMerger12251506600435692045.xml Error:
Apps targeting Android 12 and higher are required to specify an explicit value for android:exported when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details.

A: you might set up exported in all YOUR components, but does all your dependencies do the same? open your manifest and below it you have "merged manifest" tab - in there you will see your manifest entries + all needed by dependencies, all merged into one manifest file (e.g. some lib may provide own Activity or Service, which also needs to be included in manifest, these may not have exported tags)
your problematic dependency is androidx.test.espresso according to posted error - you are using 3.2, newest one is 3.4. update dependency version, lib creators should fix that on their side already. if not - afaik you can't do anything besides manually importing sources, adding missing XML attributes and importing this modified lib instead of "official" one. or by "pinging" owner for do so in official repo... :)


text:
Q: How to write the commits of a remote branch to my local branch? I have a remote branch, let's called it FIN-985_the_original. I have my local branch, which is called FIN-985_v2. FIN-985_v2 is a branch from master.
I did two commands and I'm confused as one clearly gave me what I want
First one is the one below
git rebase --onto FIN-985_the_original FIN-985_v2

This one put the content of FIN-985_the_original into FIN-985_v2, issue is it seems to replace the contents of FIN-985_the original into FIN-985_v2, wiping out the commits done into FIN-985_v2.
The second part seems to give me what I want but it kind of defy my logic
git checkout FIN-985_the_original
git rebase FIN-985_v2

I was expecting that the the rebase would be done on FIN-985_v2 and instead, it was done on FIN-985_the_original. From my command, I know it makes sense as the checkout was done on FIN-985_the_original but it bugs my logic as I've read this
Any tips are more than welcomed to deconfuse me.
Cheers

A: Basic rebase (your second case)
I'll start with your second case, since that's the easier one to explain.
git checkout A
git rebase B

asks Git to take any commits in A that are not in B, and move them to the end of B.
Sample scenario:
-- 0 (master)
    \
     1 -- 2 -- 3 (B)
      \
       4 -- 5 (A)

If, while A is checked out, I do git rebase B, I pluck commits 4 and 5 (they're on A but not on B) and move them to the end of B:
-- 0 (master)
    \
     1 -- 2 -- 3 (B)
                \
                 4' -- 5' (A)

So now A will have all the commits of B followed by the commits of A.
In your case, the commits of the_original should now be after those of v2, and the_original should be a branch of v2, although I'm not sure that's what you're saying happened.
Using --onto
When you use --onto, things get weird. I'll start with a checkout again because the branch that is currently checked out still is the one being moved:
git checkout A
git rebase --onto C B

asks Git to take the commits that are on A but not on B and move them, same as without --onto. But now, we gave the rebase a destination: put them at the end of C.
Let's add C to my initial scenario:
     6 (C)
    /
-- 0 (master)
    \
     1 -- 2 -- 3 (B)
      \
       4 -- 5 (A)

Since I'm on A, we're still going to move 4 and 5: they're on A but not on B; but we'll place them on C, i.e., after 6:
       6 (C)
      / \
     /   4' -- 5' (A)
    /
-- 0 (master)
    \
     1 -- 2 -- 3 (B)

So in your case, what should have happened depends on what was checked out before the rebase: the commits in the branch that was checked out that were not in v2 should have gotten moved to the end of the_original.
I find I rarely want --onto, and frankly I find it confusing enough that I would probably cherry pick the commits around instead of using git rebase --onto...
Pedantic notes
Following the convention at https://git-scm.com/docs/git-rebase, I'm using ' to mark the moved commits, since 4' and 5' are new commits reproducing 4 and 5, not 4 and 5 themselves.
I'm taking a linguistic shortcut when I say "moved": commits are not technically moved, they are re-applied, thus creating new commits that look more or less the same as the originals.


text:
Q: print js variable into innerHTML call in another js file Basically I have two javascript files that are separated but linked to a single html file. In this html file, in the js sections (i.e script section) I have declared a variable which I would like to print in an innerHTML part of the other js file where I am currently making a table.
Here I declared the variable in the script section of the html file:
 var varIwanttoprint = 'data/rnase.mtz'

Here is the code for the table
var tab1 = document.getElementById("tab1");
tab1.innerHTML ='

General data
' +
'
'+
'
Path	**The variable i want to print here**
'

However, I can't seem to find a way to print the js value of the js variable inside the html table. Is there any way I can do this?
Thank you

A: If the innerHTML part of the code is in a function then you can pass the value as an argument.
If innerHTML not in a function make sure the js file which including the innerHTML code is bellow the script section of varIwanttoprint and then you can concatenate the value.
var tab1 = document.getElementById("tab1");
tab1.innerHTML ='

General data
' +
'
'+
'
Path	'+varIwanttoprint+'
'

A: 1st way
function retrunParam(){
var varIwanttoprint = 'data/rnase.mtz';return varIwanttoprint;

}

var tab1 = document.getElementById("tab1");
tab1.innerHTML ='

General data
' +
'
'+
'
Path	'+retrunParam()+'
'

2nd way
var tab1 = document.getElementById("tab1");
tab1.innerHTML ='

General data
' +
'
'+
'
Path	**The variable i want to print here**
'

 var varIwanttoprint = 'data/rnase.mtz'
document.getElementById("replaceHere").innerHTML = varIwanttoprint;


text:
Q: Symfony stops working after user login
I am trying to write a simple loginpage using Symfony 3.3. Therefor I followed the guide which I found on the symfony page. Every time I try to log in with my user I get a http 500 error. I am using the build-in php server. I created my user using a trial page which I wrote before. The server only stops working when trying to log-in, although the log says, that the login was successful. Without the login all pages are working as expected. Also when I am using plain HTTP-Authentication everything works fine. This occurs only to me when I am trying to use form authentication. Even when I enter wrong credentials the error is displayed. Is there anybody who could help me?
My security.yml
security:
    encoders:
        AppBundle\Entity\User:
            algorithm: bcrypt
            cost: 12

    providers:
    mariadb_provider:
        entity:
            class: AppBundle:User

    firewalls:
       dev:
           pattern: ^/(_(profiler|wdt)|css|images|js)/
           security: false

        main:
            anonymous: ~
            form_login:
                login_path: login
                check_path: login
                default_target_path: dashboard

     access_control:
        - {path: ^/login$, roles: IS_AUTHENTICATED_ANONYMOUSLY}
        - {path: ^/user, roles: [ROLE_ADMIN, ROLE_USER] }

Login Controller
namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;

class LoginController extends Controller
{
    /**
     * @Route("/login", name="login")
     */
    public function loginAction(Request $request, AuthenticationUtils $authUtils)
    {
        $error = $authUtils->getLastAuthenticationError();
        $username = $authUtils->getLastUsername();

        return $this->render(":abistuff:login.html.twig",     array("last_username" => $username, "error" => $error));
    }
}

dev.log

[2017-09-20 19:37:00] request.INFO: Matched route "login". {"route":"login","route_parameters":{"_controller":"AppBundle\\Controller\\LoginController::loginAction","_route":"login"},"request_uri":"localhost:8000/app_dev.php/login","method":"GET"} []
[2017-09-20 19:37:00] security.INFO: Populated the TokenStorage with an anonymous Token. [] []
[2017-09-20 19:37:00] request.INFO: Matched route "_wdt". {"route":"_wdt","route_parameters":{"_controller":"web_profiler.controller.profiler:toolbarAction","token":"6fb00a","_route":"_wdt"},"request_uri":"localhost:8000/app_dev.php/_wdt/6fb00a","method":"GET"} []
[2017-09-20 19:37:05] request.INFO: Matched route "login". {"route":"login","route_parameters":{"_controller":"AppBundle\\Controller\\LoginController::loginAction","_route":"login"},"request_uri":"localhost:8000/app_dev.php/login","method":"POST"} []
[2017-09-20 19:37:05] doctrine.DEBUG: SELECT a0_.id AS id_0, a0_.username AS username_1, a0_.password AS password_2, a0_.displayname AS displayname_3, a0_.is_admin AS is_admin_4, a0_.is_active AS is_active_5 FROM abistuff_users a0_ WHERE a0_.username = ? ["admin"] []
[2017-09-20 19:37:05] security.INFO: User has been authenticated successfully. {"username":"admin"} []
[2017-09-20 19:37:05] security.DEBUG: Stored the security token in the
session. {"key":"_security_main"} []
[2017-09-20 19:37:05] request.INFO: Matched route "dashboard". {"route":"dashboard","route_parameters":{"_controller":"AppBundle\\Controller\\User\\DashboardController::showAction","_route":"dashboard"},"request_uri":"localhost:8000/app_dev.php/user/dashboard","method":"GET"} []

My login.html.twig

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

    <link rel="stylesheet" href="{{ asset("lib/styles/font-awesome.min.css") }} ">

    <link rel="stylesheet" href="{{ asset("lib/styles/main.css") }}">

 Eingang zum Abistuff!

        {% if error %}

{{ error.messageKey|trans(error.messageData, 'security') }}

        {% endif %}

            <form action="{{ path('login') }}" method="post">

                    <input autofocus="" class="form-control" id="UserName" name="_username" placeholder="max.mustermann" type="text" value="{{ last_username }}">

                    <input class="form-control" id="Password" name="_password" placeholder="Passwort" type="password">

                <button type="submit" class="btn btn-primary btn-lg btn-block"> Login</button>
            </form>