text:
Q: Swift: Create String from HTML with custom font I'm trying to convert a HTML-String coming from my backend into a NSAttributedString for my textView, but I want to set the font myself.
Here is an example of a HTML-String coming from my server:

Title

Extra info ..

- Some more info

- Contact

Some stackoverflow topics suggest setting the font in the server-backend, however this isn't possible in my situation.
I searched online on how to create the NSAtrributedString: use a WebView or a NSAttributedString, I went with the second for certain reasons. I use the following method to convert my HTML-String into a NSAttributedString:
    func setHTMLFromString() -> NSAttributedString{
    let attrStr = try! NSMutableAttributedString(
        data: self.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!,
        options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
        documentAttributes: nil)
    return attrStr
}

This method works, however it overrides the default System font I have set for my textView. So I tried adding the font as an attribute:
    func setHTMLFromString() -> NSAttributedString{
    let attrStr = try! NSMutableAttributedString(
        data: self.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!,
        options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
        documentAttributes: nil)

    if #available(iOS 8.2, *) {
        attrStr.addAttributes([NSFontAttributeName : UIFont.systemFontOfSize(16.0, weight: UIFontWeightThin),
            NSForegroundColorAttributeName: UIColor(rgb: 0x555555)], range: NSMakeRange(0, attrStr.length))
    } else {
        attrStr.addAttributes([NSFontAttributeName : UIFont.systemFontOfSize(16.0),
            NSForegroundColorAttributeName: UIColor(rgb: 0x555555)], range: NSMakeRange(0, attrStr.length))
    }

    return attrStr
}

Now the font I want to display does show correctly, however all the HTML tags stopped working. Anyone have a solution on how to set the font and keep the HTML tags working?

A: You could embed a CSS font style in your HTML after you receive the HTML from the server and prior to handing it off to the attributed string. Font details could be dynamically set using string interpolation on the CSS style. You can grab your text view's font to set it. I've done something like this before and it worked, but I don't really love it.

A: If by "not working", you mean that the "strong" text is coming out with the same font as the rest of the text, I think that's just a result of applying a font attribute to the whole string - it ends up overriding the font attributes that were originally set up by the HTML. I don't think NSAttributedString attributes nest in the same way that they do in HTML.
I'm not sure why the attributed string would be overriding the default font set on the textView in the first place, though. I haven't seen that in the case of setting an AttributedString as the title of a button, for example. I think it must be that the conversion from HTML to attributed string is introducing some default font attributes.
Not sure what the best way to fix this is - maybe insert a font style into the HTML pre-conversion? Otherwise, I suppose you could loop over the attributes in the string, and replace/modify any font attributes, but that seems messy.


text:
Q: Separate JSON Arrays in PostgreSQL I have uploaded a JSON file into PostgreSQL 10, but my output is the following:
{
  "type":"name",
  "properties":{
    "name":"urn:ogc:def:crs:OGC:1.3:CRS84"
  }
}

[
  {
    "type":"Feature",
    "geometry":{
      "type":"Polygon",
      "coordinates":[
        [
          [
            -69.63156338410452,
            18.423064855125194
          ],
          [
            -69.63158484940756,
            18.42306049063717
          ],
          [
            -69.6316055531327,
            18.42316231511968
          ],
          [
            -69.63158408782962,
            18.4231666796077
          ],
          [
            -69.63156338410452,
            18.423064855125194
          ]
        ]
      ]
    },
    "properties":{
      "id":579,
      "top":2087416.483723811,
      "left":-7751401.453397826,
      "right":-7751399.014997826,
      "bottom":2087404.291723811
    }
  },
  {
    "type":"Feature",
    "geometry":{
      "type":"Polygon",
      "coordinates":[
        [
          [
            -69.63158408782962,
            18.4231666796077
          ],
          [
            -69.6316055531327,
            18.42316231511968
          ],
          [
            -69.6316262568703,
            18.42326413966371
          ],
          [
            -69.63160479156727,
            18.423268504151732
          ],
          [
            -69.63158408782962,
            18.4231666796077
          ]
        ]
      ]
    },
    "properties":{
      "id":580,
      "top":2087404.291723811,
      "left":-7751401.453397826,
      "right":-7751399.014997826,
      "bottom":2087392.099723811
    }
  },
  {
    "type":"Feature",
    "geometry":{
      "type":"Polygon",
      "coordinates":[
        [
          [
            -69.63160479156727,
            18.423268504151732
          ],
          [
            -69.6316262568703,
            18.42326413966371
          ],
          [
            -69.63164696062047,
            18.423365964269255
          ],
          [
            -69.6316254953174,
            18.42337032875728
          ],
          [
            -69.63160479156727,
            18.423268504151732
          ]
        ]
      ]
    },
    "properties":{
      "id":581,
      "top":2087392.099723811,
      "left":-7751401.453397826,
      "right":-7751399.014997826,
      "bottom":2087379.907723811
    }
  },
  {
    "type":"Feature",
    "geometry":{
      "type":"Polygon",
      "coordinates":[
        [
          [
            -69.6316254953174,
            18.423370328757276
          ],
          [
            -69.63164696062047,
            18.423365964269255
          ],
          [
            -69.6316676643831,
            18.423467788936325
          ],
          [
            -69.63164619908007,
            18.423472153424346
          ],
          [
            -69.6316254953174,
            18.423370328757276
          ]
        ]
      ]
    },
    "properties":{
      "id":582,
      "top":2087379.9077238112,
      "left":-7751401.453397826,
      "right":-7751399.014997826,
      "bottom":2087367.7157238112
    }
  },
  {
    "type":"Feature",
    "geometry":{
      "type":"Polygon",
      "coordinates":[
        [
          [
            -69.63164619908007,
            18.423472153424346
          ],
          [
            -69.6316676643831,
            18.423467788936325
          ],
          [
            -69.63168836815828,
            18.423569613664906
          ],
          [
            -69.63166690285523,
            18.42357397815293
          ],
          [
            -69.63164619908007,
            18.423472153424346
          ]
        ]
      ]
    },
    "properties":{
      "id":583,
      "top":2087367.7157238112,
      "left":-7751401.453397826,
      "right":-7751399.014997826,
      "bottom":2087355.5237238111
    }
  },
  {
    "type":"Feature",
    "geometry":{
      "type":"Polygon",
      "coordinates":[
        [
          [
            -69.63166690285523,
            18.42357397815293
          ],
          [
            -69.63168836815828,
            18.423569613664906
          ],
          [
            -69.63170907194598,
            18.423671438455013
          ],
          [
            -69.63168760664291,
            18.423675802943034
          ],
          [
            -69.63166690285523,
            18.42357397815293
          ]
        ]
      ]
    },
    "properties":{
      "id":584,
      "top":2087355.5237238111,
      "left":-7751401.453397826,
      "right":-7751399.014997826,
      "bottom":2087343.331723811
    }
  },
  {
    "type":"Feature",
    "geometry":{
      "type":"Polygon",
      "coordinates":[
        [
          [
            -69.63158484940756,
            18.42306049063717
          ],
          [
            -69.63160631471062,
            18.423056126149138
          ],
          [
            -69.63162701843578,
            18.423157950631648
          ],
          [
            -69.6316055531327,
            18.42316231511968
          ],
          [
            -69.63158484940756,
            18.42306049063717
          ]
        ]
      ]
    },
    "properties":{
      "id":596,
      "top":2087416.483723811,
      "left":-7751399.014997827,
      "right":-7751396.576597827,
      "bottom":2087404.291723811
    }
  },
  {
    "type":"Feature",
    "geometry":{
      "type":"Polygon",
      "coordinates":[
        [
          [
            -69.6316055531327,
            18.42316231511968
          ],
          [
            -69.63162701843578,
            18.423157950631648
          ],
          [
            -69.63164772217337,
            18.423259775175687
          ],
          [
            -69.6316262568703,
            18.42326413966371
          ],
          [
            -69.6316055531327,
            18.42316231511968
          ]
        ]
      ]
    },
    "properties":{
      "id":597,
      "top":2087404.291723811,
      "left":-7751399.014997827,
      "right":-7751396.576597827,
      "bottom":2087392.099723811
    }
  },
  {
    "type":"Feature",
    "geometry":{
      "type":"Polygon",
      "coordinates":[
        [
          [
            -69.6316262568703,
            18.42326413966371
          ],
          [
            -69.63164772217337,
            18.423259775175687
          ],
          [
            -69.63166842592354,
            18.423361599781227
          ],
          [
            -69.63164696062047,
            18.423365964269255
          ],
          [
            -69.6316262568703,
            18.42326413966371
          ]
        ]
      ]
    },
    "properties":{
      "id":598,
      "top":2087392.099723811,
      "left":-7751399.014997827,
      "right":-7751396.576597827,
      "bottom":2087379.907723811
    }
  },
  {
    "type":"Feature",
    "geometry":{
      "type":"Polygon",
      "coordinates":[
        [
          [
            -69.63164696062047,
            18.423365964269255
          ],
          [
            -69.63166842592354,
            18.423361599781227
          ],
          [
            -69.6316891296862,
            18.423463424448297
          ],
          [
            -69.6316676643831,
            18.423467788936325
          ],
          [
            -69.63164696062047,
            18.423365964269255
          ]
        ]
      ]
    },
    "properties":{
      "id":599,
      "top":2087379.9077238112,
      "left":-7751399.014997827,
      "right":-7751396.576597827,
      "bottom":2087367.7157238112
    }
  },
  {
    "type":"Feature",
    "geometry":{
      "type":"Polygon",
      "coordinates":[
        [
          [
            -69.6316676643831,
            18.423467788936325
          ],
          [
            -69.6316891296862,
            18.423463424448297
          ],
          [
            -69.63170983346134,
            18.423565249176885
          ],
          [
            -69.63168836815828,
            18.423569613664906
          ],
          [
            -69.6316676643831,
            18.423467788936325
          ]
        ]
      ]
    },
    "properties":{
      "id":600,
      "top":2087367.7157238112,
      "left":-7751399.014997827,
      "right":-7751396.576597827,
      "bottom":2087355.5237238111
    }
  },
  {
    "type":"Feature",
    "geometry":{
      "type":"Polygon",
      "coordinates":[
        [
          [
            -69.63168836815828,
            18.423569613664906
          ],
          [
            -69.63170983346134,
            18.423565249176885
          ],
          [
            -69.63173053724903,
            18.423667073966993
          ],
          [
            -69.63170907194598,
            18.423671438455013
          ],
          [
            -69.63168836815828,
            18.423569613664906
          ]
        ]
      ]
    },
    "properties":{
      "id":601,
      "top":2087355.5237238111,
      "left":-7751399.014997827,
      "right":-7751396.576597827,
      "bottom":2087343.331723811
    }
  },
  {
    "type":"Feature",
    "geometry":{
      "type":"Polygon",
      "coordinates":[
        [
          [
            -69.63160631471062,
            18.423056126149138
          ],
          [
            -69.6316277800137,
            18.42305176166112
          ],
          [
            -69.63164848373884,
            18.423153586143624
          ],
          [
            -69.63162701843578,
            18.423157950631648
          ],
          [
            -69.63160631471062,
            18.423056126149138
          ]
        ]
      ]
    },
    "properties":{
      "id":613,
      "top":2087416.483723811,
      "left":-7751396.576597827,
      "right":-7751394.138197826,
      "bottom":2087404.291723811
    }
  }
]

There are numerous polygons contained in this field. I'd like to be able to separate them into different rows for each polygon and into type, name and properties columns. Is this achievable in PostgreSQL?
For example:

Type
ID
Properties
Geometries

Feature
579
"left": -7751401.453397826,"top": 2087416.483723811, "right": -7751399.014997826, "bottom": 2087404.291723811
[-69.63156338410452, 18.423064855125194],[-69.63158484940756, 18.42306049063717],[-69.6316055531327, 18.42316231511968],[-69.63158408782962, 18.4231666796077],[-69.63156338410452, 18.423064855125194]

A: There are two bits of json in the string above. First,
"{"type": "name", "properties": {"name": "urn:ogc:def:crs:OGC:1.3:CRS84"}}"

And then an array which looks much better with proper indentation indented (results here):
[
  {
    "type": "Feature",
    "geometry": {
      "type": "Polygon",
      "coordinates": [
        [
          [
            -69.63156338410452,
            18.423064855125194
          ],
          [
            -69.63158484940756,
            18.42306049063717
          ],
          [
            -69.6316055531327,
            18.42316231511968
          ],
          [
            -69.63158408782962,
            18.4231666796077
          ],
          [
            -69.63156338410452,
            18.423064855125194
          ]
        ]
      ]
    },
    "properties": {
      "id": 579,
      "top": 2087416.483723811,
      "left": -7751401.453397826,
      "right": -7751399.014997826,
      "bottom": 2087404.291723811
    }
  },

So, I'll assume all the objects have the same structure, similar as above. Let's put the json into a table for convenience...
CREATE TABLE foo ( d jsonb );
INSERT INTO foo VALUES ('the above json data')

The following should do what you want, including conversion to postgres geometric types:
SELECT
typ,
BOX( POINT((prop->>'left')::FLOAT,  (prop->>'top')::FLOAT),
     POINT((prop->>'right')::FLOAT, (prop->>'bottom')::FLOAT) ) bbox,
     REPLACE(REPLACE((geom->'coordinates')->>0,'[','('),']',')')::POLYGON
FROM (
SELECT
    elem->>'type'         AS typ,
    elem->'properties'    AS prop,
    elem->'geometry'      AS geom
FROM (
SELECT jsonb_array_elements(d) elem FROM foo
) f1
)f2;

However, processing this kind of json in a SQL query is not flexible, so if you have several types of geometry (not just polygons) or if the json structure can vary, it would be better to process it in a more suitable language before using SQL.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Stop loading of images with javascript (lazyload)? I am trying to stop the loading of images with javascript on dom ready and then init the loading whenever i want, a so called lazy loading of images. Something like this:

$(document).ready(function () {
  var images = $('img');
  $.each(images, function() {
    $(this).attr('src', '');
  });
});

This doesn't work (tested in ff3.5, safari 3-4). The images is getting loaded anyway, i dont get it.
For example this plugin, www.appelsiini.net/projects/lazyload, is doing the exact same thing, removing the src attribute on page load.
What am i missing?
EDIT: I added a test page here: http://dev.bolmaster2.com/dev/lazyload-test/
I first remove the src attribute completely, then after 5 seconds I add it with the original image. Still doesn't work, at least firebug says the images get loaded at start, is firebug to trust?

A: try removeAttr("src"); as in http://www.appelsiini.net/projects/lazyload
$(document).ready(function () {
  var images = $('img');
  $.each(images, function() {
    $(this).removeAttr("src");
  });
});

If it still is not working. Check this.loaded - maybe they are loaded too fast.

A: If your goal is to prevent the server from loading the images, then clearing the "src" attribute will not work when you run in at document.ready (at least not always - try downloading pinterest's html for example and addy your script to the saved html - you will see that the browser will request the images from the server before the src is cleared).
Instead you can try to use the same code (or better, without jQuery, to make sure it runs as fast as possible) by putting it in the "head" section inside a setInterval loop that will clear the "src" attribute from all images as soon as the  tags are present (before jQuery document ready is fired).
Example:
remove the images without jQuery:
function removeImagesBeforeTheyAreRequested(options) {
  var images = document.getElementsByTagName('img');
  for (var i = 0; i < images.length; i++) {
    var orgSrc = images[i].src;
    images[i].removeAttribute('src');
  }
}

fire this code in the "head" section, before the body is ready (basically monitor the existence of img tags):
var timer = setInterval(function() {
   removeImagesBeforeTheyAreRequested();
}, 1);

quit trying to look for images after 3 seconds:
setTimeout(function() { clearInterval(timer); }, 3000);

Note that you might want to check if images are cached before removing their "src" attribute (those would be loaded by the browser really fast and there's no point in removing their "src" for the purpose of removing load from the server as they are not requested from the server again).

A: I think the problem is that you are emptying the 'img' attribute, not the 'src'.
If you are testing this on a local page, then your local images may be loading too fast. Or maybe they are taken directly from browser cache. Try checking if the image is already loaded before emptying its 'src'.

A:
$(document).ready(function () {
    var images = $('img');
    $.each(images, function() {
        $(this).attr('src', '');
    });
});

This won't work because jQuery is being called after the page has loaded at:
$(document).ready()
all this code would be doing is removing the src value after the image has already been called from the server.

A: I don't know if you have written wrong in the question but the attribute the you should set to an empty string is "src" not "img". Try this:
$(document).ready(function () {
  var images = $('img');
  $.each(images, function() {
    $(this).attr('src', '');
  });
});

A: I think your problem is you're running the code within $(document).ready, which is called when the document is ready - ie. when it is fully loaded, including the images.  The LazyLoad plugin you linked to doesn't use $(document).ready, and the script is placed in the header, so it runs before/while the page loads rather than afterwards.

A: I'd suggest using the Jquery Lazyload plug-in for this.  It does exactly what you want.
http://www.appelsiini.net/projects/lazyload

A: I had the same problem when putting the image load on the hover event on my thumbnail image, in IE it causes a "Stack Overflow" when I hover on the thumbnail image.
But it is solved now. This code saved my day:
$(document).ready(function() {
  var images = $('img');
  $.each(images, function() {
    $(this).removeAttr("src");
  });
});

A: With JavaScript you do it like this.
var imagesArray = document.querySelectorAll('img');

for(var i=0; i<imagesArray.length; i++) {
    imagesArray[i].src = '';
}

Consider using Vanilla Javascript first.


text:
Q: ¿Como llamar a una actividad desde un fragment? Android Studio + Kotlin Quiero llamar o abrir una actividad desde un fragment en mi aplicacion con kotlin, lo trate de llamar con setOnClickListener pero algo pasa con intent, porque no lo reconoce.
Normalmente para llamar a una actividad se usa:
        textView12.setOnClickListener {
            val intent = Intent(this , miactvidad::class.java)
            startActivity(intent)
        }

Pero talvez la forma de llamar a una desde un fragment sea diferente
Este es el codigo que tengo:
package com.example.bottom.ui.notifications

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.example.bottom.R
import com.example.myapplication.olvidaste
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_main.olvidasteContraseña
import kotlinx.android.synthetic.main.fragment_notifications.*

class NotificationsFragment : Fragment() {

    private lateinit var notificationsViewModel: NotificationsViewModel

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,savedInstanceState: Bundle?): View? {
        notificationsViewModel =
                ViewModelProviders.of(this).get(NotificationsViewModel::class.java)
        val root = inflater.inflate(R.layout.fragment_notifications, container, false)
        textView12.setOnClickListener {
            val intent = Intent(this , olvidaste::class.java)
            startActivity(intent)
        }
        val textView: TextView = root.findViewById(R.id.text_notifications)
        notificationsViewModel.text.observe(viewLifecycleOwner, Observer {
            textView.text = it
        })
        return root
    }
}

Por cierto este es el error que recibo al tratar de ejecutar mi app:
e: C:\Users\brand\AndroidStudioProjects\bottom\app\src\main\java\com\example\bottom\ui\notifications\NotificationsFragment.kt: (27, 26): None of the following functions can be called with the arguments supplied:
public constructor Intent(p0: Context!, p1: Class<*>!) defined in android.content.Intent
public constructor Intent(p0: String!, p1: Uri!) defined in android.content.Intent
Gracias si pueden resolver mi problema

A: Lo que pasa es que startActivity es un método de Context, y para crear un Intent explicito también necesitas un Context.
La clase Fragment no hereda de Context, por lo que deberás obtener el Context llamando a requireContext()
textView12.setOnClickListener {
    requireContext().let{
        it.startActivity(Intent(it, olvidaste::class.java))
    }
}


text:
Q: Sum of while row I'm new to php and I'm stuck. I have a report that allows a supervisor to show the working hours of the operators. I can show all the hours from the db, but I can't make a sum of all the hours.  I want to display one more row that shows the total hours.  How can I do that?
<?php
    if(isset($_SESSION['username'])) {
        $username = $_SESSION['username'];
    } else {
        header('Location: index.php');
        die();
    }

    include('connect.php');

    @$oret_e_punes       = $_POST['oret_e_punes'];
    @$grupi              = $_POST['grupi'];
    @$data_e_inserimit   = $_POST['data_e_inserimit'];
    @$data_e_inserimit_2 = $_POST['data_e_inserimit_2'];

    $sql = "select grup_name from grupi";
    $result = mysqli_query($dbCon, $sql);
    if(!$result) {
    die("Error");
    }
?>

//html form

<?php
    if(isset($_POST['insert'])) {
        $insert = "select * from ore where grupi='$grupi' and (data between '$data_e_inserimit' and '$data_e_inserimit_2' and ore !=0)";
        $result_insert = mysqli_query($dbCon, $insert);
        if(!$result_insert) {
            die("Error");
        }

    echo "

        Operatori
        Grupi
        Oret e punes
        Data

";
    while ($row = mysqli_fetch_assoc($result_insert)) {
        $id = $row['id'];
        echo "

            ".$row['usr']."
            ".$row['grupi']."
            ".$row['ore']."	 ---->working hours
            ".$row['data']."

";
            $id++;
    }
        echo "
";
        $_SESSION['$id'] = @$id;
    }
?>

A: have a variable for hours before loop starts. Add in it hour of each record. After loop will end you will have your total hours
echo "

    Operatori
    Grupi
    Oret e punes
    Data

";
$hours = 0;
while ($row = mysqli_fetch_assoc($result_insert)) {
    $id = $row['id'];
    echo "

        ".$row['usr']."
        ".$row['grupi']."
        ".$row['ore']."	 ---->working hours
        ".$row['data']."

";
        $hours += $row['ore'];
        $id++;
}
echo "
Total	$hours
";
echo "
";


text:
Q: Let P(n) be the proposition that 6 divides n^3 − n whenever n is a nonnegative integer. I solved the problem using Induction. But how to solve this using Strong Induction?
Problem:
Let P(n) be the proposition that 6 divides n^3 − n whenever n is a nonnegative integer.
Use strong induction to prove P(n).

A: Hard to guess the problem composer's intent, because the problem doesn't even require induction, let alone strong induction.
I interpret strong induction to signify that you use the fact that the a proposition $P(k)$ is true for each positive integer $(k)$ from $1$ through $(n)$ inclusive, and use this to conclude that the proposition $P(n+1)$ is also true.
One (convoluted) approach is to assume that once the proposition is manually verified for each positive integer element in $\{1,2,3,4,5,6\}$, then you can reason as follows:
Assume that the proposition has been proven true for each positive integer $(k) \in \{1,2,\cdots,n\} ~: n \geq 6.$
In order to then prove that the proposition holds for $(n+1)$ you can reason that there must exist some element $(k)$ in $\{1,2,\cdots,n\}$ such that $k \equiv (n+1) \pmod{6}$.
This will imply that $k^3 \equiv (n+1)^3 \pmod{6}.$
This will imply that the proposition is true for $(n+1)$ if and only if the proposition is true for $(k)$.  Since you are guaranteed that the proposition is true for $(k)$, you have proven that the proposition is true for $(n+1).$

Note that this convoluted attempt to employ strong induction is actually employing a disguised form of weak induction.  You could just as easily reason that there are only $6$ congruence classes, $\pmod{6}$, that $n$ can belong to.
Thus, $n$ must be an element in one of

*

*$\{1,7,13, \cdots\}$.

*$\{2,8,14, \cdots\}$.

*$\{3,9,15, \cdots\}$.

*$\{4,10,16, \cdots\}$.

*$\{5,11,17, \cdots\}$.

*$\{6,12,18, \cdots\}$.

Then, you could employ weak induction on each separate subset, reasoning that if the proposition is true for $n$, then the proposition must be true for $(n+6).$

Even more bizarre is that induction isn't even needed, since the product of three consecutive numbers must be a multiple of $(3)$.  However, since the posted question is asking how to reverse engineer the problem composer's intent that strong induction be employed, the analysis at the start of my answer is the best that I can conjure.

A: Here's one way.  Note:  $(n+2)^3 - (n+2) = (n^3 + 3\times 2n^2 + 3\times 2^2 n + 2^3)-(n+2) =$
$(n^3 + 6n^2 + 12n + 8)-(n+2) = (n^3 - n) + 6n^2+12n + 6$.
As $6|6n^2 + 12n + 6$ we have $P(n) \implies P(n+2)$ (actually it is an if and only if for all integers)
So to do strong induction we have to just do 2 base cases.
$0^3 - 0=0$ is divisible by $6$ so $P(0)$ is true.  And $1^3 -1 = 0$ is divisible by $6$ so $P(1)$ is true.
Inductive step:  Suppose $P(k)$ is true for all $k \le n$.  If $n=0$ then $P(n+1)=P(1)$ is true.  If $n \ge 1$ then $P(n-1)$ is true.  Therefore $P((n-1) + 2)=P(n+1)$ is true.  So $P(k); \forall k \le n \implies P(n+1)$.  Our induction step is done.


text:
Q: Get free space of HDD in linux Within a bash script i need to get the total disk size and the currently used size of the complete disk.
I know i can get the total disk size without needed to be root with this command:
cat /sys/block/sda/size

This command will output the count of blocks on device SDA.
Multiply it with 512 and you'll get the amount of bytes on this device.
This is sufficient with the total disk size.
Now for the currently used space. I want to get this value without being root.
I can assume the device name is SDA.
Now there is this command: df
I thought i could use this command but it seems this command only outputs data of the currently mounted partitions.
Is there a way to get a total of space used on disk SDA without needing to be root and not all partitions needs to be mounted?
Let's assume the following example:
/dev/sda1 80GB Linux partition 20GB Used
/dev/sda2 80GB Linux Home partition 20GB Used
/dev/sda3 100GB Windows Parition. 30GB Used

Let's assume my SDA disk is partitioned like above. But while i'm on Linux my Windows partition (sda3) is not mounted.
The output of df will give me a grand total of 40 GB Used so it doesn't take sda3 in account.
Again the question:
Is there a way without root to get me a grand total of 70 GB used space?

A: I think stat command should help. You can get the get the partitions from /proc/partitions.
Sample stat command output:
$ stat -f /dev/sda1
  File: "/dev/sda1"
    ID: 0        Namelen: 255     Type: tmpfs
Block size: 4096       Fundamental block size: 4096
Blocks: Total: 237009     Free: 236970     Available: 236970
Inodes: Total: 237009     Free: 236386

A: You can use df.
df -h --output='used' /home
Used
3.2G

If you combine this with some sed or awk you can have the value you seek


text:
Q: Async Compute on User interaction I have a standard web page with Ajax update panel. WorkFlow of the page is : The user can add some entity, delete some entity(on click of their respective buttons) to create some definition. And then user can save these definition, edit it and delete it.
Upon adding/deleting the entities, a complex calculation needs to take place which would be time intensive. What I want is, when the user adds or deletes some entity, a separate thread should do the computation and update the UI. The point to be kept in mind here is, when the entity are added or deleted , the corresponding server side code need to be run first, which adds/deletes the entities from a collection stored in session(that means I can not launch a ajax call on the button, because the server side code for the button needs to run first), and then the logic for computation.
What I have thought of doing is
1. Make the server call for button click
2. When response returns, use AJAX client life cycle to catch the response before page is rendered. This is the place where I would make ajax call, if request was for add/delete entity.
This how ever seems over complicated. I am sure, there must be a easy way to do this.

A: Found out answer to my problem. What I needed was PageAsyncTask which is in built in asp.net for these kind of jobs.
Google


text:
Q: Spring JPA repositories - save() doesn't show child element in database I have two JPA entities Task and TaskList.
The Task class is this:
@Entity(name = "task")
public class Task implements Serializable {

    // Id and 3 fields

    @ManyToOne
    @JoinColumn(name="tasklist_id")
    private TaskList parentList;

    // 3 more fields

    // Constructor
    public Task() {}

    //Getters and Setters
}

and the TaskList class is this:
@Entity(name = "task_list")
public class TaskList implements Serializable {

    // Id and two fields

    @OneToMany(mappedBy="parentList")
    private List<Task> tasks;

    // Constructor
    public TaskList() {}
}

When I do this:
TaskList parent_list = repo.findOne(listId);

Task t = new Task();
// set fields for t

parent_list.getTasks().add(t);
repo.save(parent_list);

It doesn't work. I get a null value for Task t.
If I use a repository for Task and save the task using its own repository, it works fine.
What I'd like to do is save both TaskList parent_list and Task t at the same time, using one call to parent_list's save() method and the relation in the entity classes.
How do I make this work?

A: Adding cascade attribute to oneToMany annotation and setting the parentlist for the newly created task should help.


text:
Q: flutter, app crashes when touch the screen with stlyus button pressed (Samsung tablet) Hi I'm new to flutter and sorry for my bad english.
I'm making a drawing app with using Samsung tablet S6, when I touch the screen with the pressed stylus button, app crashes.
I want to handle this problem only with the flutter, not using the method channel.
This is my sample code

sample code

import 'dart:ui';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

void main () {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Scaffold(
        body: Stack(
          children: [
            Positioned.fill(child: Container(
              color: Colors.yellow,
            )),
            GestureDetector(
              child: Listener(
                behavior: HitTestBehavior.opaque,
                onPointerHover: (s) {
                  if(s.kind == PointerDeviceKind.stylus && s.buttons == kPrimaryStylusButton) {
                    print("Stylus is hovering");
                    // it works well
                  }
                },
                onPointerDown: (s) {
                  if(s.kind == PointerDeviceKind.stylus) {
                    print("Stylus is touched the screen");
                    // works well
                  } else if (s.kind == PointerDeviceKind.stylus && s.buttons == kPrimaryStylusButton) {
                    print("Stylus is touched the screen with pressed button");
                  }
                },
                onPointerMove: (s) {
                  if(s.kind == PointerDeviceKind.stylus) {
                    print("Stylus is moving on the screen");
                    // it works well
                  } else if (s.kind == PointerDeviceKind.stylus && s.buttons == kPrimaryStylusButton) {
                    print("Stylus is moving on the screen with pressed button");
                  }
                },
                onPointerCancel: (s) {
                  print("detached the stylus");
                },
              ),
            ),

          ],
        ),
      ),
    );
  }
}

and it's error message in Logcat
and it said AssertionError with Unexpected masked action

Error Message

E/MessageQueue-JNI(26267): Exception in MessageQueue callback: handleReceiveCallback
E/MessageQueue-JNI(26267): java.lang.AssertionError: Unexpected masked action
E/MessageQueue-JNI(26267):  at io.flutter.embedding.android.AndroidTouchProcessor.getPointerChangeForAction(AndroidTouchProcessor.java:384)
E/MessageQueue-JNI(26267):  at io.flutter.embedding.android.AndroidTouchProcessor.onTouchEvent(AndroidTouchProcessor.java:124)
E/MessageQueue-JNI(26267):  at io.flutter.embedding.android.AndroidTouchProcessor.onTouchEvent(AndroidTouchProcessor.java:104)
E/MessageQueue-JNI(26267):  at io.flutter.embedding.android.FlutterView.onTouchEvent(FlutterView.java:940)
E/MessageQueue-JNI(26267):  at android.view.View.dispatchTouchEvent(View.java:15076)
E/MessageQueue-JNI(26267):  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3917)
E/MessageQueue-JNI(26267):  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:3581)
E/MessageQueue-JNI(26267):  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3923)
E/MessageQueue-JNI(26267):  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:3538)
E/MessageQueue-JNI(26267):  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3923)
E/MessageQueue-JNI(26267):  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:3538)
E/MessageQueue-JNI(26267):  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3923)
E/MessageQueue-JNI(26267):  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:3538)
E/MessageQueue-JNI(26267):  at com.android.internal.policy.DecorView.superDispatchTouchEvent(DecorView.java:1015)
E/MessageQueue-JNI(26267):  at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1962)
E/MessageQueue-JNI(26267):  at android.app.Activity.dispatchTouchEvent(Activity.java:4265)
E/MessageQueue-JNI(26267):  at com.android.internal.policy.DecorView.dispatchTouchEvent(DecorView.java:973)
E/MessageQueue-JNI(26267):  at android.view.View.dispatchPointerEvent(View.java:15335)
E/MessageQueue-JNI(26267):  at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:7794)
E/MessageQueue-JNI(26267):  at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:7567)
E/MessageQueue-JNI(26267):  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:6901)
E/MessageQueue-JNI(26267):  at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:6958)
E/MessageQueue-JNI(26267):  at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:6924)
E/MessageQueue-JNI(26267):  at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:7122)
E/MessageQueue-JNI(26267):  at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:6932)
E/MessageQueue-JNI(26267):  at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:7179)
E/MessageQueue-JNI(26267):  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:6905)
E/MessageQueue-JNI(26267):  at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:6958)
E/MessageQueue-JNI(26267):  at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:6924)
E/MessageQueue-JNI(26267):  at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:6932)
E/MessageQueue-JNI(26267):  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:6905)
E/MessageQueue-JNI(26267):  at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:10354)
E/MessageQueue-JNI(26267):  at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:10202)
E/MessageQueue-JNI(26267):  at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:10158)
E/MessageQueue-JNI(26267):  at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:10486)
E/MessageQueue-JNI(26267):  at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:259)
E/MessageQueue-JNI(26267):  at android.os.MessageQueue.nativePollOnce(Native Method)
E/MessageQueue-JNI(26267):  at android.os.MessageQueue.next(MessageQueue.java:335)
E/MessageQueue-JNI(26267):  at android.os.Looper.loopOnce(Looper.java:186)
E/MessageQueue-JNI(26267):  at android.os.Looper.loop(Looper.java:313)
E/MessageQueue-JNI(26267):  at android.app.ActivityThread.main(ActivityThread.java:8663)
E/MessageQueue-JNI(26267):  at java.lang.reflect.Method.invoke(Native Method)
E/MessageQueue-JNI(26267):  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:567)
E/MessageQueue-JNI(26267):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)
D/AndroidRuntime(26267): Shutting down VM
I/flutter (26267): Hovering stylus and button is pressed!
E/AndroidRuntime(26267): FATAL EXCEPTION: main
E/AndroidRuntime(26267): Process: com.example.stylus_test2, PID: 26267
E/AndroidRuntime(26267): java.lang.AssertionError: Unexpected masked action
E/AndroidRuntime(26267):    at io.flutter.embedding.android.AndroidTouchProcessor.getPointerChangeForAction(AndroidTouchProcessor.java:384)
E/AndroidRuntime(26267):    at io.flutter.embedding.android.AndroidTouchProcessor.onTouchEvent(AndroidTouchProcessor.java:124)
E/AndroidRuntime(26267):    at io.flutter.embedding.android.AndroidTouchProcessor.onTouchEvent(AndroidTouchProcessor.java:104)
E/AndroidRuntime(26267):    at io.flutter.embedding.android.FlutterView.onTouchEvent(FlutterView.java:940)
E/AndroidRuntime(26267):    at android.view.View.dispatchTouchEvent(View.java:15076)
E/AndroidRuntime(26267):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3917)
E/AndroidRuntime(26267):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:3581)
E/AndroidRuntime(26267):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3923)
E/AndroidRuntime(26267):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:3538)
E/AndroidRuntime(26267):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3923)
E/AndroidRuntime(26267):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:3538)
E/AndroidRuntime(26267):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3923)
E/AndroidRuntime(26267):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:3538)
E/AndroidRuntime(26267):    at com.android.internal.policy.DecorView.superDispatchTouchEvent(DecorView.java:1015)
E/AndroidRuntime(26267):    at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1962)
E/AndroidRuntime(26267):    at android.app.Activity.dispatchTouchEvent(Activity.java:4265)
E/AndroidRuntime(26267):    at com.android.internal.policy.DecorView.dispatchTouchEvent(DecorView.java:973)
E/AndroidRuntime(26267):    at android.view.View.dispatchPointerEvent(View.java:15335)
E/AndroidRuntime(26267):    at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:7794)
E/AndroidRuntime(26267):    at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:7567)
E/AndroidRuntime(26267):    at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:6901)
E/AndroidRuntime(26267):    at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:6958)
E/AndroidRuntime(26267):    at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:6924)
E/AndroidRuntime(26267):    at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:7122)
E/AndroidRuntime(26267):    at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:6932)
E/AndroidRuntime(26267):    at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:7179)
E/AndroidRuntime(26267):    at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:6905)
E/AndroidRuntime(26267):    at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:6958)
E/AndroidRuntime(26267):    at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:6924)
E/AndroidRuntime(26267):    at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:6932)
E/AndroidRuntime(26267):    at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:6905)
E/AndroidRuntime(26267):    at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:10354)
E/AndroidRuntime(26267):    at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:10202)
E/AndroidRuntime(26267):    at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:10158)
E/AndroidRuntime(26267):    at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:10486)
E/AndroidRuntime(26267):    at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:259)
E/AndroidRuntime(26267):    at android.os.MessageQueue.nativePollOnce(Native Method)
E/AndroidRuntime(26267):    at android.os.MessageQueue.next(MessageQueue.java:335)
E/AndroidRuntime(26267):    at android.os.Looper.loopOnce(Looper.java:186)
E/AndroidRuntime(26267):    at android.os.Looper.loop(Looper.java:313)
E/AndroidRuntime(26267):    at android.app.ActivityThread.main(ActivityThread.java:8663)
E/AndroidRuntime(26267):    at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(26267):    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:567)
E/AndroidRuntime(26267):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)
I/Process (26267): Sending signal. PID: 26267 SIG: 9
Lost connection to device.


text:
Q: PHP mail MMS attaching image not working Hello guys I am working on webapplication for sending multimedia messages upon user input of their phone numbers. I am successfully able to send emails with images in HTML form. Now, I am trying to send my customers MMS via PHP mail function, but the only thing they receive is the link that I send them with the message.
Here is what I have come up with so far.
<?php
$email = '1234567890@somenetwork.domain';
$link = $_COOKIE["coupon"];
$to = $email;
$subject = 'Some Subject';
$message = " Hello, This is Testing Text 8.0
            Your Link  ";

$message->addAttachment("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS0dA2aipmy9hwAitgD8U5n8l_afNBvxYc3gnOFi7hOGoGAGIHssw", "image/gif");
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: someone <support@someone.com>' . "\r\n";
mail($email, $subject, $message, $headers);

?>

A: When sending to a phone as MMS, you have to send the image as an attachment.
I found the following answer to be very helpful for easily sending attachments, even though it references "mail", not MMS:
Send attachments with PHP Mail()?

A: One of the issues is that you can't fetch that image in that fashion.
I.e. https://encrypted-tbn0.gstatic.com/images?\
             q=tbn:ANd9GcS0dA2aipmy9hwAitgD8U5n8l_afNBvxYc3gnOFi7hOGoGAGIHssw
returns an empty file.
Also, since when can you send MMS via PHP's mail() function?
The most reliable way in my experience to send images via SMS/MMS is to send a WAP push msg.


text:
Q: Android: Kotlin Room how to take unique data from table and use this in recycle view I have a table with lessons and I need to select all the unique group names from there to display them in the recycle view
Lesson data class
@Entity(tableName = "lesson_table")
data class Lesson (
    @PrimaryKey(autoGenerate = true) val id: Int?,
    @ColumnInfo(name = "lesson_name") val lessonName: String?,
    @ColumnInfo(name = "Group_name") val groupName: String?,
    @ColumnInfo(name = "day") val day: Int?
)

LessonDAO
@Dao
interface  LessonDao {
    @Query("SELECT * FROM lesson_table")
    fun getAll(): List<Lesson>
    @Query("SELECT DISTINCT Group_name FROM lesson_table")
    fun findallgroup(): List<Lesson>

And this in fragment code to inset data in rcview
  private fun init(){
        binding.apply {

            gridLayoutManager = GridLayoutManager(requireContext(), 2, LinearLayoutManager.VERTICAL, false)
            rcView.layoutManager = gridLayoutManager
            rcView.adapter=adapter

        }
        GlobalScope.launch { adapter.addItems(appDb.lessonDao().findallgroup())}
    }

It doesnt work, but if I use getAll() from DAO its works
Please help
P.S. if I use findallgroup() i get that error
E/AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-1
    Process: com.example.calendar2, PID: 5833
    android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

A: Don't use GlobalScope. You should use a lifecycle scope so it is bound to the Main thread, which is required when working with any UI components. A lifecycle scope also automatically cancels its coroutines when the view is destroyed, which avoids leaking memory or causing crashes that could happen when trying to reference views that no longer exist.
In an Activity:
lifecycleScope.launch { adapter.addItems(appDb.lessonDao().findallgroup()) }

In a Fragment:
viewLifecycle.lifecycleScope.launch { adapter.addItems(appDb.lessonDao().findallgroup()) }


text:
Q: Can I pass props to a React Component from a general function?    import B from './B.js';
   const Test = () => {

      async function getResults() {
        await axios
          .get(`http://localhost:2000/?url=${link}`)
          .then((response) => {
            <B data={response.data} />
          });
      }
      return (
        <>
          <div>
           <button onClick={getResults}> Click </button>
         </div>
        </>
          )

I was trying to pass the axios data as props to my component B. But in console I got undefined value. How to solve this issue. Should I pass the props inside the return area of the Test Component only?

A: You need to use useState to store data
import B from './B.js';
import { useState } from 'react'
const Test = () => {
  const [data, setData] = useState({})
  async function getResults () {
    await axios
      .get(`http://localhost:2000/?url=${link}`)
      .then((response) => {
        setData(response.data)
      });
  }
  return (
    <>
      <div>
        <button onClick={getResults}> Click </button>
        <B data={data} />

      </div>
    </>
  )
}


text:
Q: Getting change color with mouse hover to work using Angular http://codepen.io/Feners4/pen/KggAwg
I want to get the cubes to change color with mouse hover using Angular. Ive managed to get it to work on one side of a cube, but I want the effect to change the whole cube color.
This is my HTML:

  Angularity

hjskl</hi>

AAA

AAA

My JS:
angular.module('App', [])
  .directive('changeBackground', ['$animate', function($animate) {
    return {
      restrict: 'EA',
      scope: {
        colorcode: '@?'
      },
      link: function($scope, element, attr) {
        element.on('mouseenter', function() {
          element.addClass('change-color');
          element.css('background-color', $scope.colorcode);
        });
        element.on('mouseleave', function() {
          element.removeClass('change-color');
          element.css('background-color', '#fff');
        });
      }
    };
  }])

How can I get the cubes to Change color on Mouse hover to work and when Mouse leaves it changes back?

A: One of the main problems here is how you defined ng-app, as I've stated in my comment this defines the root of the application to be used by Angular. Placing it in such a specific location would mean none of the other elements are connected to Angular. The first thing that needs to be done is your HTML should be cleaned up, there are duplicate closing header tags with no openings and there is not a closing body. Since you never defined a controller and it's not being used I removed it (otherwise it will throw an error) After that you can just define your ng-app on the body and that will allow to use your directive on any element:

  Angularity

hjskl</hi>

AAA

AAA


text:
Q: Status of the first infinite ordinal $\omega$ within non-standard analysis? With newfound freetime during the pandemic, I have been studying non-standard analysis. I wasn't too fond of ultrafilters, so I've gravitated toward Nelson's internal set theory and Hrbacek set theory. Although I prefer the latter, I have more experience with Nelson's work, so I will phrase things in terms of IST.
I have basic knowledge of ordinal numbers in set theory, of which $\omega$ is the first. I want to know where the set fits into IST. Is it simply a standard hyperfinite number? Intuitively, the fact that $\omega > n$ for every natural number $n$, caused me to assume that $\omega$ could be a member of ${}^*\mathbb{N}$, as this is the defining property of these natural numbers. I found a paper (Taras Kudryk et al., 2004) mentioning standard hyperfinite integers that proved in its Proposition 2.1 that:

There exists a $\mathbf{standard}$ R-infinite [i.e. in ${}^*\mathbb{N}\setminus\mathbb{N}$] hypernatural number.

As I understand it, every set uniquely defined in ZFC without reference to the standard predicate is standard. Hence, the first transfinite ordinal $\omega$ is a standard set. With this, I have been hoping to prove that $\omega\in{}^*\mathbb{N}\setminus\mathbb{N}$. However, at the same time, I recall that there is no least hyperfinite natural number. This seems to contradict the fact that $\omega$ is the least ordinal number.
At this point, my lack of experience with set theory is probably showing. Looking at questions discussing the differences between $\omega$ and $\mathbb{N}$ makes me realize that I might be over my head here. Could I have some clarification from those with more experience with set theory and its non-standard extensions? Where does $\omega$ (and really the ordinal numbers in general) fit into IST?

A: The smallest transfinite von Neumann ordinal $\omega$ and the elements of ${}^*\mathbb{N}\setminus\mathbb{N}$ are different sorts of objects altogether. Asking "does $\omega$ belong to the set ${}^*\mathbb{N}\setminus\mathbb{N}$?" does not make much sense, the same way asking "does the group $S_3$ contain the set $\mathbb{R}$ as an element?" does not make much sense.
I can arrange a situation where the answer to the latter question is technically yes. E.g. by defining the group $S_3$ as the group with underlying set
$S_3 = \{A,B,C,D,E,\mathbb{R}\}$ and with multiplication table
S_3  ℝ   A   B   C   D   E
--+------------------------
ℝ |  ℝ   A   B   C   D   E
A |  A   B   ℝ   D   E   C
B |  B   ℝ   A   E   C   D
C |  C   E   D   ℝ   B   A
D |  D   C   E   A   ℝ   B
E |  E   D   C   B   A   ℝ

we have not only that $\mathbb{R} \in S_3$, but also that $\mathbb{R}$ is the identity element of $S_3$. This is of course a meaningless technicality, and should not be mistaken for a mathematical relationship between the group $S_3$ and the real numbers $\mathbb{R}$.
Depending on your construction of the extension ${}^*\mathbb{N}$, you can similarly arrange to make $\omega \in {}^*\mathbb{N} \setminus \mathbb{N}$ hold, but that does not teach you anything about the ordinals: you could arrange e.g. $\mathbb{R} \in {}^*\mathbb{N}$ in exactly the same way.

With that out of the way, is there a natural mathematical way in which the ordinal $\omega$ corresponds to some fixed nonstandard natural number? The answer to that question is no, and it remains no even if we replace "fixed nonstandard natural number" with "fixed standard element of ${}^*\mathbb{N}\setminus\mathbb{N}$ where ${}^*\mathbb{N}$ denotes some standard hyperextension of $\mathbb{N}$" (in fact, I'd suggest avoiding these mixed IST and Robinsonian NSA notions until you become much more comfortable with both formalisms).
The same goes for your implicit question about obtaining "concrete" nonstandard numbers: you won't be able to pin down any concrete nonstandard number using the IST axioms. The only way to construct nonstandard numbers is via Idealization (if you omit the Idealization axiom from IST, it's consistent with the resulting system that all objects are standard), and one can construct models of IST where every specification by Idealization (essentially every non-isolated 1-type) is realized by at least two different elements of the model.


text:
Q: problems with importing `requests` when using py2exe TL;DR
Importing the requests library fails within a Python3 project when frozen with py2exe.
The unfrozen project works.
The problem seems to be related to relative imports within the requests module.
long description
I've created a little project using Python3, and would like to turn it into an executable for w32.
The project depends on PySide and requests (2.13.0; actually this is a secondary dependency of the used pyapi-gitlab package).
All dependencies have been installed via pip3.
Python version is 3.4.4 (since PySide doesn't support any later versions of Py3).
I'm using py2exe 0.9.2.2.
Everything  (e.g. importing and using PySide) works great, but the import requests deep inside fails.
Here's a somewhat minimal example to illustrate the problem:
import logging
logging.basicConfig()
log = logging.getLogger()

import sys
print("Python: %s" % (sys.version,))

try:
    import requests
except ImportError:
    log.fatal("failed to import 'requests'", exc_info=True)

When I run this from the cmdline, I get:
E:\p2e> python p2e.py
Python: 3.4.4 (v3.4.4:737efcadf5a6, Dec 20 2015, 19:28:18) [MSC v.1600 32 bit (Intel)]
E:\p2e>

Nice.
The following minimal setup.py is supposed to turn this into an exe:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from distutils.core import setup
import py2exe

setup(console=['p2e.py'])

Doing the actual conversion gives a number of "missing modules" warnings:
E:\p2e> python setup.py py2exe
running py2exe

  24 missing Modules
  ------------------
? Cookie                              imported from requests.compat
? OpenSSL                             imported from requests.packages.urllib3.contrib.pyopenssl
? Queue                               imported from requests.packages.urllib3.connectionpool
? _abcoll                             imported from requests.packages.urllib3.packages.ordered_dict
? backports                           imported from requests.packages.urllib3.packages.ssl_match_hostname
? certifi                             imported from requests.certs
? chardet                             imported from requests.packages
? cookielib                           imported from requests.compat
? cryptography                        imported from requests.packages.urllib3.contrib.pyopenssl
? idna                                imported from requests.models, requests.packages.urllib3.contrib.pyopenssl
? netbios                             imported from uuid
? readline                            imported from cmd, code, pdb
? simplejson                          imported from requests.compat
? six                                 imported from requests.packages.urllib3.contrib.pyopenssl
? socks                               imported from requests.packages.urllib3.contrib.socks
? urllib.getproxies                   imported from requests.compat
? urllib.proxy_bypass                 imported from requests.compat
? urllib.quote                        imported from requests.compat
? urllib.quote_plus                   imported from requests.compat
? urllib.unquote                      imported from requests.compat
? urllib.unquote_plus                 imported from requests.compat
? urllib.urlencode                    imported from requests.compat
? urllib3                             imported from requests.packages
? win32wnet                           imported from uuid
Building 'dist\p2e.exe'.
Building shared code archive 'dist\library.zip'.
Copy c:\windows\system32\python34.dll to dist
Copy C:\Python34\DLLs\_ssl.pyd to dist\_ssl.pyd
Copy C:\Python34\DLLs\_lzma.pyd to dist\_lzma.pyd
Copy C:\Python34\DLLs\select.pyd to dist\select.pyd
Copy C:\Python34\DLLs\_hashlib.pyd to dist\_hashlib.pyd
Copy C:\Python34\DLLs\_ctypes.pyd to dist\_ctypes.pyd
Copy C:\Python34\DLLs\_bz2.pyd to dist\_bz2.pyd
Copy C:\Python34\DLLs\_socket.pyd to dist\_socket.pyd
Copy C:\Python34\DLLs\pyexpat.pyd to dist\pyexpat.pyd
Copy C:\Python34\DLLs\unicodedata.pyd to dist\unicodedata.pyd
E:\p2e>

I routinely ignore these warnings, and run the generated exe:
E:\p2e> dist\p2e.exe
CRITICAL:root:failed to import 'requests'
Traceback (most recent call last):
  File "c:\Python34\lib\site-packages\requests\packages\__init__.py", line 27, in <module>
    from . import urllib3
  File "c:\Python34\lib\site-packages\requests\packages\urllib3\__init__.py", line 8, in <module>
    from .connectionpool import (
  File "c:\Python34\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 28, in <module>
    from .packages.six.moves import queue
  File "c:\Python34\lib\site-packages\requests\packages\urllib3\packages\six.py", line 92, in __get__
    result = self._resolve()
  File "c:\Python34\lib\site-packages\requests\packages\urllib3\packages\six.py", line 115, in _resolve
    return _import_module(self.mod)
  File "c:\Python34\lib\site-packages\requests\packages\urllib3\packages\six.py", line 82, in _import_module
    __import__(name)
ImportError: No module named 'queue'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "p2e.py", line 9, in <module>
  File "c:\Python34\lib\site-packages\requests\__init__.py", line 63, in <module>
    from . import utils
  File "c:\Python34\lib\site-packages\requests\utils.py", line 24, in <module>
    from ._internal_utils import to_native_string
  File "c:\Python34\lib\site-packages\requests\_internal_utils.py", line 11, in <module>
    from .compat import is_py2, builtin_str, str
  File "c:\Python34\lib\site-packages\requests\compat.py", line 11, in <module>
    from .packages import chardet
  File "c:\Python34\lib\site-packages\requests\packages\__init__.py", line 29, in <module>
    import urllib3
ImportError: No module named 'urllib3'
Python: 3.4.4 (v3.4.4:737efcadf5a6, Dec 20 2015, 19:28:18) [MSC v.1600 32 bit (Intel)]
E:\p2e>

I'm totally puzzled.
It seems that the requests package does some import magic to
- support both included 3rd-party libs (urllib) and libs installed by package managers.
- support both Py2 and Py3 (using a local copy of six)
Both seem to create problems.
I can amend the urllib3 problem, by patching requests to only search for that package in relative paths (even though the original code does the same, only enclosed by a try/catch that catches any ImportError and then falls back to import globally.)
I have no idea how to fix the import queue problem.
And after all, it is working properly when I run the script in the Py3 interpreter.
NOTE
There's a similar (maybe the same) issue, but it doesn't include that much information: py2exe "requests" module missing

A: It looks like urllib3 tries to import the queue module which fails. When that fails, requests fails to import `urllib3.
To force py2exe to include the queue module, use --includes queue when you invoke it.


text:
Q: (PostgreSQL) "Advanced" Check Constraint Question I use PostgreSQL but am looking for SQL answer as standard as possible.
I have the following table "docs" --
    Column  |          Type          | Modifiers
------------+------------------------+--------------------
 id         | character varying(32)  | not null
 version    | integer                | not null default 1
 link_id    | character varying(32)  |
 content    | character varying(128) |
Indexes:
    "docs_pkey" PRIMARY KEY, btree (id, version)

id and link_id are for documents that have linkage relationship between each other, so link_id self references id.
The problem comes with version. Now id is no longer the primary key (won't be unique either) and can't be referenced by by link_id as foreign key --
my_db=# ALTER TABLE docs ADD FOREIGN KEY(link_id) REFERENCES docs (id) ;
ERROR:  there is no unique constraint matching given keys for referenced table "docs"

I tried to search for check constraint on something like "if exists" but didn't find anything.
Any tip will be much appreciated.

A: I usually do like this:
table document (id, common, columns, current_revision)
table revision (id, doc_id, content, version)

which means that document has a one-to-many relation with it's revisions, AND a one-to-one to the current revision.
That way, you can always select a complete document for the current revision with a simple join, and you will only have one unique row in your documents table which you can link parent/child relations in, but still have versioning.

A: Sticking as close to your model as possible, you can split your table into two, one which has 1 row per 'doc' and one with 1 row per 'version':
You have the following table "versions" --
    Column  |          Type          | Modifiers
------------+------------------------+--------------------
 id         | character varying(32)  | not null
 version    | integer                | not null default 1
 content    | character varying(128) |
Indexes:
    "versions_pkey" PRIMARY KEY, btree (id, version)

And the following table "docs" --
    Column  |          Type          | Modifiers
------------+------------------------+--------------------
 id         | character varying(32)  | not null
 link_id    | character varying(32)  |
Indexes:
    "docs_pkey" PRIMARY KEY, btree (id)

now
my_db=# ALTER TABLE docs ADD FOREIGN KEY(link_id) REFERENCES docs (id) ;

is allowed, and you also want:
my_db=# ALTER TABLE versions ADD FOREIGN KEY(id) REFERENCES docs;

of course there is nothing stoping you getting a 'combined' view similar to your original table:
CREATE VIEW v_docs AS
SELECT id, version, link_id, content from docs join versions using(id);

A: Depending on if it's what you want, you can simply create a FOREIGN KEY that includes the version field. That's the only way to point to a unique row...
If that doesn't work, you can write a TRIGGER (for all UPDATEs and INSERTs on the table) that makes the check. Note that you will also need a trigger on the docs table, that restricts modifications on that table that would break the key (such as a DELETE or UPDATE on the key value itself).
You cannot do this with a CHECK constraint, because a CHECK constraint cannot access data in another table.


text:
Q: Openerp how to update field values in two classes There are two classes that I am currently working with and I am in a mess right now. Please help me to solve this
What I need to do is once an employee in "roster_allocation" class want to cancel his/her allocated roster, then for that purpose you have to go through "roster_substitution"class, which keeps records of the original allocation and substitute allocation and date and time. Once you entered a record via that table I want to update that particular "roster_allocation" table record with updating the existing employee_id with the substitute_employee_id from **"roster_substitute"**table.
these are my two classes
Roster Allocation Class
   class roster_allocation(osv.osv):

         _name="roster.allocation"
         _description ="Allocate rosters on employees"

         _columns={

             'emp_id':fields.many2one('hr.employee','Employee'),
             'department_id':fields.many2one('hr.department','Department'),
             'roster_allocation_allocation':fields.one2many('roster.days.allocation','roster_allocation_connection','Days connection'),
             'roster_time':fields.char('Take the related field  roster_time.name'),
             'monthly allocation':fields.char('Month')   ,
             'roster_rest_allocation':fields.one2many('roster.rest.days','roster_id','Rest Days'),
             'roster_substitute':fields.one2many('roster.substitution','allocation_id','Substitution'),

roster_allocation()

Roster days allocation class ( which keeps the records of start date, roster type and time slot)
class roster_days_allocation(osv.osv):
    _name="roster.days.allocation"
    _description = "To allocate days in to the already defined time slots"

    def get_domain_useer_id(self,cr,uid,ids,roster_type_list,context=None):
      mach=[]
      filter = self.pool.get('roster.type').search(cr,uid,[('id','=',roster_type_list)])
      return {'domain':{'roster_time_list':[('rostertype','=',filter)]}}

    _columns={
            'name':fields.char('Days_Allocation'),
            'allocation_start_day':fields.date('Start Date',required=True),
            'allocation_end_day':fields.date('End Date',required=True),
            'type_connection':fields.one2many('roster.type','date_allocation_connection','Roster Type'),
            'roster_type_list':fields.many2one('roster.type','Rosters'),
            'roster_time_list':fields.many2one('roster.time','Time Slot'),

            'roster_allocation_connection':fields.many2one('roster.allocation','Allocation Connection')

              }

roster_days_allocation()

Roster Substitution class (which keeps the record of originally allocated employee and substitute employee)
class roster_substitution(osv.osv):

    _name="roster.substitution"
    _description="Substituting employees "
    _columns={
             'allocation_id':fields.many2one('roster.allocation','Allocation'),
             'employee':fields.many2one('hr.employee','Employee'),
             'sub_employee':fields.many2one('hr.employee','Employee'),
             'time_slot':fields.many2one('roster.time','Roster'),
             'roster_day':fields.date('Day'),
             'reason':fields.text('Reason'),
             'department_id':fields.many2one('hr.department','Department'),

             }

    def onchange_date(self, cr, uid, ids, roster_date):
        result = {'value': {'type': False}}
        if type_id:
            type = self.pool.get('roster.time').browse(cr, uid, roster_date)
        result['value'] = {'time_slot': type.name.id}
        return result

roster_substitution()

Please help me to solve this

A: I'm sorry I read your post over and over but I don't understand what you are exactly trying to do (might be because you name some fields different ways in the code and in the text). But anyway:
I think you have to modify your emp_id in your roster_allocation class.
'emp_id': fields.function(_creation_function,
                                     type="many2one",
                                     obj='hr.employee',
                                     string='Employee',
                                     store={
                                     'roster.substitution': (_modify_function,
                                                            ['field_that_change'],
                                                            10)}),

with _creation_function the function you have to define for the value emp_id has when you create it.
_modify_function the function that will modify your emp_id when field_that_change will be modified in 'roster.substitution'.
This is because onchange don't allow you to modify a field in model_A from model_B. It doesn't save anything in the database except if the field that is updated thanks to the onchange is modified on your screen and you save afterward.
If you want to add some fields you want to keep an eyes on you can add them in ['field_that_change', 'second_field'] if in the same object, or by adding a second objet with the same syntax in the store.


text:
Q: How to compile a visual studio c++ project on linux efficiently I'm having a C++ Project in Visual Studio 2017 which uses curl. It compiles fine on a linux machine. But i think my procedure is not efficient. Im just copying my source files to the linux machine and run
g++ one.cpp two.cpp etc.cpp -lcurl

or even
g++ *.cpp -lcurl -o output

Is there something to do this a "cool" way? Like cmake or something (sorry im not into this).  An Example would be really helpful

A: Your options range wildly from:

*

*Just keep doing what you're doing

*Wrap that command in a shell script so you don't have to keep typing it

*Make a Makefile to auto-generate that command

*Use CMake to auto-generate the Makefile (or automake or something else)

*Use an IDE (examples for various platforms: Eclipse, Xcode, Visual Studio) to fully manage the project for you, including build rules/commands — Visual Studio Code in particular may be of interest here

It is completely up to you what you pick.
Personally, in your situation, right now I'd just throw together a Makefile and be done with it, until your needs become more complex.
Whichever of the latter 3 options you pick, there are abundant examples online and in your book already.
I would say, please don't use a really complicated solution to solve a simple problem just because it's "cool", because that's not what cool is.


text:
Q: Remove text from search bar once clicked on something Though the title seems straight forward and simple, what I am trying to do is a little bit more than it seems.
What I have is a search box to search for users on my website, to send a message to. It returns a list of users and you then click on the user(s) that you want to send a message to. Upon clicking on said user(s), I append the user in a li (it's a contentEditable div by the way), and then allow for the user to continue searching for additional users. This all works how I want it to, what I am trying to do now is to remove the plain text from the search box.
so if someone types say, "Rober" and then clicks the user, "Robert Smith", it should remove all plain text that is not wrapped in a li element.
I believe it would be something along the lines of say:
$("div.search").clone().children().remove().end().text();

I use this to filter the li text and such out when searching.
In a non working example of usage, I would say it should be something like this:
var text = $("div.search").clone().children().remove().end().text();

$("div.search").find(text).notIn("li").remove();

Edit
Rather than searching for the exact text to remove, it would probably be better and easier to just rmeove all text that is not wrapped in an li element.

A: $('div.search').find(':not(li):contains(' + text + ')').remove();

A: dunno if this is what you're looking for but:
var d = $('<div>');
$('div.search').children().appendTo(d);
$('div.search').html('').append(d.children());

this will keep all the html elements and remove all the other text that is not inside nodes.
you can filter the children to keep only "li"


text:
Q: How to arrange ArrayList values into rows and columns of html table? I am a beginner to programming, please be kind if I have committed any blunders in programming.
Below is my MySql table, it have one more row "Priority"
+-----------+-------------+-------------+-------------+--------+---------------------+
| pk_vcl_id | vehicle_nm  | reg_nu      | officer_mob | active | updated_at          |
+-----------+-------------+-------------+-------------+--------+---------------------+
|         1 | FireEngine1 | KL 07 AB 11 | 9744231482  |      0 | 2016-01-19 21:42:36 |
|         2 | Ambulance1  | KL 07 CD 43 | 9446238433  |      0 | 2016-01-15 00:23:20 |
|         3 | policecar1  | KL 07 E 52  | 8129938273  |      0 | 2016-01-15 00:23:38 |
|         8 | Signal      | NIL         | 1111111111  |      0 | 2016-01-18 23:42:01 |
+-----------+-------------+-------------+-------------+--------+---------------------+

I need to arrange the above data obtained from array list to the rows and columns of an html table. I tried several ways but not getting properly aligned.
Below is my arraylist in Java page:-
    while(rsgsts.next())
        {
        database.add(rsgsts.getString("vehicle_nm"));
        database.add(rsgsts.getString("reg_nu"));
        database.add(rsgsts.getString("active"));
        database.add(rsgsts.getString("officer_mob"));
        database.add(rsgsts.getString("priority"));
        database.add(rsgsts.getString("updated_at"));

        }

Below is my jsp page:-
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%--     <%@page contentType="text/html; charset=UTF-8" errorPage="errorpage.jsp" pageEncoding="UTF-8"%> --%>
<%--      <%@ page import="com.my.classes.*" %> --%>

<%@ page import="java.util.*"%>
<%@ page import="java.util.Map"%>

<%@ page import="java.util.Arrays.*"%>
<%--         <%@page import="org.json.JSONArray"%> --%>
<%@ page import="java.util.ArrayList.*"%>
<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="HandheldFriendly" content="true">
<meta name="viewport"
    content="width=device-width, initial-scale=0.666667, maximum-scale=0.666667, user-scalable=0">
<meta name="viewport" content="width=device-width">
<link rel="icon" type="image/png" href="favicon.png">

<title>Database</title>

<%
    String xyz="name";
    //dbLayer db=new dbLayer();
    ArrayList<String> data = new ArrayList<String>();
    data.add("Test");
    data.add("Test1");
    data.add("Test2");
    data.add("Test3");
    data.add("Test4");
    data.add("Test5");
    data.add("Test6");
//    data.add("Test7");
//    data.add("Test8");
//    data.add("Test9");
    //db.getdata(xyz);

    int dbsize=data.size();
    int i=0;
    %>

            Vehicle
            RegNumber
            Status
            MobileNum
            Priority
            Last_seen

        <% //java goes here
            //int num = data.size() % 5;
            //if(num){}
                        /*To know how many 5 columns rows are in the arraylist*/
                        for (int n = 1; n < data.size() % 5; n++ ){
            %>

            <% //Loop through first row of table, aka first set of strings in arraylist

                        for (String str : data){
            %>

                <% out.print(str);%>

            <%
                     }
                 %>
            <%
                  }
                 %>

Updated Output 23-Jan-2016:-
Vehicle RegNumber   Status  MobileNum   Priority    Last_seen
Test    Test1   Test2   Test3   Test4   Test5   Test6

Test 6 is printed as an additional row after Last_seen and when I added "test7, 8, 9" to arraylist nothing is being printed. Same when I tried with my actual arraylist returned from database.


text:
Q: GridView paging not working as expected I'm starting on vb.net and I have to make a GridView that shows registers from an sql query with paging enabled on the GridView. But the paging only works for the first registers in page 1, when I click page 2 it shows less registers than it should and the bar with the page numbers dissapears.
I've seen people with a similar problem, all that's said is to put:
 Protected Sub GridView2_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridView2.PageIndexChanging
    GridView2.PageIndex = e.NewPageIndex
    GridView2.DataBind()
End Sub

But it doesnt seem to work.
Here are the codes that fill the GridView with two possible queries. If I disable paging, they work just fine, so the problem is not on the queries:
 Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

    Dim command As String
    command = "SELECT [GVA14]. [COD_CLIENT] As Codigo, [GVA14].[RAZON_SOCI] As Nombre,tabla.[periodo] As Cuota FROM [GVA14] LEFT JOIN (SELECT cod_client as cod_client ,MAX(periodo) as periodo FROM emCuotas GROUP BY cod_client) As tabla ON ([GVA14]. [COD_CLIENT] COLLATE DATABASE_DEFAULT=tabla.[cod_client] COLLATE DATABASE_DEFAULT) ORDER BY [GVA14].[COD_CLIENT]"
    Dim dTable As New DataTable
    Dim dataAdapter = New OleDbDataAdapter(command, con)

    dataAdapter.Fill(dTable)
    GridView2.DataSource = dTable
    GridView2.DataBind()
    nro = 1

End Sub

 Protected Sub Button4_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button4.Click
    Dim f1 As String
    f1 = TextBox1.Text
    Dim f2 As String
    f2 = TextBox2.Text
    Dim command As String
    Dim cuantos As Integer = 50
    Dim inicio As Integer=0
    command = "SELECT COD_CLIENT,RAZON_SOCI,FECHA_ALTA FROM GVA14 WHERE FECHA_ALTA BETWEEN CONVERT(datetime,'" & f1 & "',103) AND CONVERT(datetime,'" & f2 & "',103) Order By COD_CLIENT,FECHA_ALTA"
    Dim dTable As New DataTable
    Dim dataAdapter = New OleDbDataAdapter(command, con)
    dataAdapter.Fill(dTable)
    GridView2.DataSource = dTable
    GridView2.DataBind()
    command = "SELECT Count(FECHA_ALTA) FROM GVA14 WHERE FECHA_ALTA BETWEEN CONVERT(datetime,'" & f1 & "',103) AND CONVERT(datetime,'" & f2 & "',103)"
    Dim comand As New Data.OleDb.OleDbCommand(command, con)

    Label1.Text = comand.ExecuteScalar
    nro=2

End Sub

A: Remove these lines of code
GridView2.PageIndex = e.NewPageIndex
GridView2.DataBind()

and just specify GridView.PageSize (and allow paging, of course)

A: Here is what I did...
    Protected Sub gvExistingICByUser_PageIndexChanging(sender As Object, e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles gvExistingICByUser.PageIndexChanging
       Dim grid As GridView = DirectCast(sender, GridView)
       GetExistingICByUser(CurrentUser)
       grid.DataSource = dtExistingICByUser
       grid.PageIndex = e.NewPageIndex
       grid.DataBind()
    End Sub

Line breakdown inside the PageIndexChanging event....
1) cast ur gridview as a grideview. (i'm not sure exactly y its done this way, but it works w/ it and not w/o)
2)LOAD YOUR GRID VIEW (i did this in another function that returns a data table)
3)Set the page index
4)Bind


text:
Q: Mongo query to find single doc based on status fieds with respect to other docs status Mongo query to find single doc based on status fields with respect to other docs status
docs
{
_id:some mongo id,
name : "test one",
status:"new",
created_at:datetime,
updated_at:datetime
}
{
_id:some mongo id,
name : "test two",
status:"new",
created_at:datetime,
updated_at:datetime
}
{
_id:some mongo id,
name : "test one",
status:"started",
created_at:datetime,
updated_at:datetime
}

I need to find one doc with status "new" if no doc with status "started"
note
we need to consider doc with status "started" if current time & updated_at difference less than 1 hr
Is there any way ?

A: Try this:
  db.coll.aggregate(
   [
     { $redact: {
        $cond: {
           if: { $and: [{ $eq: [ { $lte: [  {$divide: [{$subtract: [new Date(), "$updated_at"]}, 3600000]} , 1] }, true]}, { "status": "started" }] },
           then: "$$KEEP",
           else: "$$PRUNE"
         }
       }
     },
     { $match: { "status": "new" } },
     {"$limit":1}
   ]
);

Explanation:
1st pipeline: If any document with our given condition matches, $redact keeps all fields at this current document/embedded document level, without further inspection of the fields.
Else all documents are pruned.
2nd pipeline: Out of all documents returned, match only with status new.
3rd pipeline: limit result to 1
Alternatively, you can also try to do this in two steps.
Step 1: check if any docuemnt with above $cond exists or not
Step 2: then find one document with new status


text:
Q: Center printing PrintDocument I'm using PrintDocument to print out multiple pages that each have one control on. So far I'm able to print them all out on individual sheets as desired, however I'm unable to center the controls in the middle of the pages and it always shows in the top corner of the page. I'll post my code below.
                var dialog = new PrintDialog();
                var queue = GetPrinterQueue(pPrinterId);

                if (queue == null)
                    return;

                dialog.PrintQueue = queue;
                dialog.PrintTicket.PageOrientation = paperOrientation
                    ? PageOrientation.Portrait
                    : PageOrientation.Landscape;

                var document = new FixedDocument();
                var fixedPage = new FixedPage();

                fixedPage.Children.Add(front);
                //fixedPage.Measure(size);
                //fixedPage.Arrange(new Rect());
                //fixedPage.UpdateLayout();

                var pageContent = new PageContent();
                ((IAddChild)pageContent).AddChild(fixedPage);
                document.Pages.Add(pageContent);

                dialog.PrintDocument(document.DocumentPaginator, "Badge");

That is the bare minimum to make it print out a control per sheet, to make it simpler I have taken out the parts that print to different pages, for the sake of this it only needs to print one.
I've tried changing what is passed into .Arrange() and it makes no difference, what am I missing?
Thanks


text:
Q: RackTables setting ownership and permissions I am trying to install RackTables on a Ubuntu Server 13. I have followed all the steps on the documentation. When I get to the step after I connect to the database I cant seem to figure out the ownership settings.
I have set up the database as follows :
mysql -uroot -p

create database racktables;
grant all on racktables.* to root;
grant all on racktables.* to root@localhost;
grant all on racktables.* to rackuser;
grant all on racktables.* to rackuser@localhost;
set password for rackuser@localhost=password('rackpw');
exit

Here is the step that I am stuck on;
 RackTables installation: step 4 of 7

Please set ownership (chown) and/or permissions (chmod) of /var/www/racktables/inc/secret.php on the server filesystem as
  follows:

*

*The file MUST NOT be writable by the httpd process.

*The file MUST be readable by the httpd process.

*The file should not be readable by anyone except the httpd process.

*The file should not be writable by anyone.

  For example, if httpd runs as user "nobody" and group "nogroup",
  commands similar to the following may work (though not guaranteed to,
  please consider only as an example):
chown nobody:nogroup secret.php; chmod 400 secret.php

I have tried the
chown root:rackuser /var/www/racktables/inc/secret.php
chmod 400 /var/www/racktables/inc/secret.php

I cant figure out how to set up the permissions so that they fall into this category

*

*The file MUST NOT be writable by the httpd process.

*The file MUST be readable by the httpd process.

*The file should not be readable by anyone except the httpd process.

*The file should not be writable by anyone.

Please help. Any suggestion is appreciated
Thank you

A: First you have to figure out which user and group your web server (Apache/nginx/etc) are running under.
If you're using Apache, you should be able to check by running:
grep -E '^(User|Group)' /etc/apache2/apache2.conf

In Ubuntu, it's common for both user and group to be www-data.
Once you know that, you should be able to change the file's ownership like:
chown [webserveruser]:[webservergroup] /var/www/racktables/inc/secret.php

Example:
chown www-data:www-data /var/www/racktables/inc/secret.php

Keep the chmod the same as you had before.
This should mean it's readable by the www-data user and only the www-data user, writable by nobody (including www-data), which should mean all four of your conditions.


text:
Q: Using control variables in Difference in Difference method When random experiments are conducted, 'baseline data' are usually used as control variables in order to increase precision.
How about control variables in Difference in Difference method?
What I mean is whether baseline data(Time 1) should be used for it or just control variables at that time(Time 1, Time 2) should be used.

A: You should use control variables that are available in both periods. As long as they are not themselves outcomes of the treatment (so-called bad controls) you can and should include covariates. For a discussion about as to why see here. In this case controls help with identification. If you use information from time 1 only you can support the common pre-treatment trends assumption. But without time 2 information you may over- or underestimate the treatment effect if your control also changes in period 2 (not because of the treatment but because it varies this way) and affects the outcome.
The other reason to include controls is to soak up some of the residual variance such that statistical tests on your treatment effect have more power. Having covariates for both periods helps with this.


text:
Q: Hi all. I started working on a license plate recognition project and I'm new to computer vision. I want to run the code but I get an error I have a trained model.weights on yolov4 for license plate detection. Now I need to recognize the characters on this license plate. I have the code, when I run this "test_img('D:/RTP/car.jpg', config_file, weights,'D:/RTP/')" I get an error
AttributeError                            Traceback (most recent call last)
Cell In [20], line 1
----> 1 test_img('D:/RTP/car.jpg', config_file, weights,'D:/RTP/')

Cell In [18], line 3, in test_img(input, config_file, weights, out_path)
      1 def test_img(input, config_file, weights, out_path):
      2   # Loading darknet network and classes along with the bbox colors.
----> 3   network, class_names, class_colors = darknet.load_network(
      4             config_file,
      5             data_file,
      6             weights,
      7             batch_size= batch_size
      8         )
     10   # Reading the image and performing YOLOv4 detection.
     11   img = cv2.imread(input)

AttributeError: module 'darknet' has no attribute 'load_network'

this is test_img( ) function
def test_img(input, config_file, weights, out_path):
  # Loading darknet network and classes along with the bbox colors.
  network, class_names, class_colors = darknet.load_network(
            config_file,
            data_file,
            weights,
            batch_size= batch_size
        )

  # Reading the image and performing YOLOv4 detection.
  img = cv2.imread(input)
  bboxes, scores, det_time = yolo_det(img, config_file, data_file, batch_size, weights, thresh, out_path, network, class_names, class_colors)

  # Extracting or cropping the license plate and applying the OCR.
  for bbox in bboxes:
    bbox = [bbox[0], bbox[1], bbox[2]- bbox[0], bbox[3] - bbox[1]]
    cr_img = crop(img, bbox)
    result = ocr.ocr(cr_img, cls=False, det=False)
    ocr_res = result[0][0]
    rec_conf = result[0][1]
    print(result)
    # Plotting the predictions using OpenCV.
    (label_width,label_height), baseline = cv2.getTextSize(ocr_res , font, 2, 3)
    top_left = tuple(map(int,[int(bbox[0]),int(bbox[1])-(label_height+baseline)]))
    top_right = tuple(map(int,[int(bbox[0])+label_width,int(bbox[1])]))
    org = tuple(map(int,[int(bbox[0]),int(bbox[1])-baseline]))

    cv2.rectangle(img, (int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3])), blue_color, 2)
    cv2.rectangle(img, top_left, top_right, blue_color,-1)
    cv2.putText(img, ocr_res, org, font, 2, white_color,3)

  # Writing output image.
  file_name = os.path.join(out_path, 'out_' + input.split('/')[-1])
  cv2.imwrite(file_name, img)


text:
Q: How to print the last line of passwd in sections in bash shell I am very new to bash shell scripting and I have an assignment that wants me to read the last line of a copy of my linux installations (that is in the admin folder) passwd file which contains the user name, real name, home directory and login shell. I have tried the read command but it continues to output the entire file rather than just the last line and even so I need to be able to output in in sections, for example: echo $Username would output Admin or echo $Realname wold ouptut the users real name. I have also tried sed but I get a "cant read, no such file or directory error"
Edit: After receiving an email from my professor, I DO have to use the read command to get the information from the passwd file. However your responses have proved useful in helping me understand what I am doing so far. Thank you!
Here is a link to my list of objectives in this script
and here is the code that I have written that returns the entire passwd file:
file="/home/Admin/passwd"

while read -r f1 f2 f3 f4 f5 f6 f7
do
        echo "Username: $f1, Realname: $f2, Homedir: $f3, loginshell: $f4 "
done < "$file"

any help would be greatly appreciated, somehow I feel like I'm reading too much into the instructions but I would like some other opinions, thank you!

A: Welcome to the wonderful world of scripting!
Assignment does not seem to mention to use 'read' command, so, not giving out the solution completely, I would suggest you use redirection methods (try a Google search on Unix redirection, it is quite fun!)
I would also suggest searching on standard and error redirection in Unix. There are some nifty shortcuts quite easy to find.
Hope this helps!

A: you need use IFS to define the field separator, then understand what column is home directory, and login shell.
Understanding fields in /etc/passwd (http://www.cyberciti.biz/faq/understanding-etcpasswd-file-format/)
Here is the fix:
file="/home/Admin/passwd"

while IFS=: read -r f1 f2 f3 f4 f5 f6 f7
do
   echo "Username: $f1, Realname: $f5, Homedir: $f6, loginshell: $f7 "
done  < "$file"


text:
Q: What's a good technique to store a time-dependent metric in Redis? I have some metrics (like counts of logged in users, or SQL queries, or whatever), and I want to gather some time-dependent stats on a regular basis.
For example I want to know how many users were registered in some particular year, month, week, day or even hour.
I thought maybe Redis can be a good fit. But I can't imagine a good strategy for storing such stats. The only idea I have is to store independent counters for days, weeks, etc, and bump them all at once.
How do you do it? I need a good trick. Or maybe Redis isn't any good for my task.

A: If all you need is a count for each period, the multiple counter approach you suggest is a good one. Incrementing 5 counters in a single pipelined transaction is O(1), while set operations are O(log n + m) with potentially large values of n/m.
The set solution Frank suggested does have its place - I use something similar where I need to know which actions happened rather than just how many. Obviously storing details of each action takes more memory than the counters, but with the amount of RAM typically available these days you can store millions of records before that becomes a problem.

A: I would just use a sorted sets where the score is the timestamp in seconds since the epoch (unix time). Say you have a sorted set of logins and you want to see how many logins occured in the year 2010, just convert 20101231 23:59:59  and 20100101 00:00:00 to seconds and use those are the max and min arguments to zcount.
The obviously difficulty here is handling the time conversion yourself, but its actually very easy because it the standard Unix format. You can use the date command with %S (on linux at least) or use the system calls time(), localtime() and mktime(), as well as any of the myriad ways available within specific languages that are built on top of these system calls.
I am sure there is some equivalent paradigm in Windows, but that I don't have any experience there.


text:
Q: Pass URL from clipboard to iframe via js? So I'm trying to get a url I have stored in the clipboard to render in my iframe via url.
Not sure what to make of this code.
<iframe id="showskill" scrolling="yes" height="100%" width ="100%" src=""+ ReturnURL()></iframe>
<script>
function ReturnURL() {
    var el = document.createElement('textarea');
    document.body.appendChild(el);
    el.focus();
    document.execCommand('paste');
    var value = el.value;
    document.body.removeChild(el)
    return value;
}
console.log(getClipboard());
</script>

Suggestions welcome.

*

*Ry3yr

Edit:
This looks like a step in the right direction ?
How to use javascript variable in iframe src
Edit2: New code, same fate...


text:
Q: Matlab find x of weighted average How to find the weighted average x? From graphing x(y) it looks to be around x=0.45?
y = [0.1 0.1 0.2 0.5 0.4 0.2]
x = [0.1 0.2 0.3 0.4 0.5 0.6]

One way to perhaps compute it would to find x where the area under the curve y(x) is half of the area under the whole curve. But how to write that in matlab?

A: Assuming you intend y to be the weights, and you want to compute the weighted average of x, then the weighted average is simply
sum(x.*y) / sum(y)


text:
Q: Why won't the specified image get deleted onclick when trying to iterate over a list of images? I'm calling an API that contains images.  My goal's to delete any image I want onclick but it doesn't seem to be working.  In my non-working below, I get an error that says: Uncaught TypeError: Cannot set property 'display' of undefinedat HTMLImageElement.<anonymous> (index.js:39)
However, in my working-code, I can successfully delete the first image only onclick (obviously because of the [0].
How would I be able to iterate through the list of images and onclick, delete the image?
Here's my non-working code:
var img = document.querySelectorAll(".the-img");

for(var i = 0; i < img.length; i++) {
    img[i].addEventListener("click", function () {
    img.style.display = "none";
    })
}

Here's my working-code:
var img = document.getElementsByClassName("the-img")[0];

img.addEventListener("click", function () {
    img.style.display = "none";
})

A: Inside your event handler, in the non-working code, you should use this.style.display = "none" so that this refers to the object clicked.
Doing otherwise, especially by indexing img array won't work.

A: document.querySelectorAll('.the-img').forEach(function(elem){
 elem.addEventListener('click', function(event){
  this.style.display = 'none';
 });
});


text:
Q: Dataset Designer functionality in Asp.Net I am developing an Asp.Net WebForms website. I am used from my prior project to the "dataset designer", it was my main worksite, I had there all my tables and also hundreds of queries which I could easily call from code like this: "this.InventoryTableAdapter.MyQuery('parameters'), it was great, but I can't find such a thing in Asp.Net, am I missing something. how do you access your special queries in code. do you have to write cumbersome ADO.Net code for each small thing, can someone enlighten me please.

A: You can still add a database designer to your .NET application.  Today's standard ORM for .NET is Entity Framework, although many other good options exist.  One thing to research is Entity Framework Database First.  Here's how to get started...

*

*In your project, choose to Add New Item.  In the Add New Item dialog choose the Data items and then select ADO.NET Entity Data Model. Click Add.

*In the Entity Data Model Wizard, select EF Designer from database.

*If you have database connections defined within your development environment, you may see one of these connections pre-selected. Or, you can create a new connection to your database.

*After setting up your connection, select the tables you want to generate models for.  These will be the tables available in your database designer.
This is a very high level how to.  You can read more about this approach here:  https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/database-first-development/creating-the-web-application
Another ORM option is LinqToSql.  You can read more about creating a database designer ".dbml" file using LinqToSql here: https://msdn.microsoft.com/en-us/library/bb384428.aspx
I hope this helps.