text:
Q: java iterate list and addFirst at the same time When I try to do
ListIterator<Integer> iter = list.listIterator(list.size());

for (int i = 0; i < size; i++) {
     iter.hasPrevious();
     list.addFirst(iter.previous());
}

I get ConcurrentModificationException. I know what that means, but how can I add first element to a List and iterate it at the same time? Execution time and memory limit are crucial.

A: Well, since you know the size of the list and therefore the first index to copy - you can either get the subList clone and use addAll(0,..) or use get(index++) and addFirst(..)
methods.
Note that iterating on sublist directly while adding might lead to the same issue since subList returns only view of original list. See  http://docs.oracle.com/javase/7/docs/api/java/util/List.html#subList(int,%20int)
However, it's OK to modify the original list as long as the changes are not structural to the subList view (do not affect size or iteration ability).


text:
Q: Extend /var partition on Centos Stream 8 During the installation of my centos stream 8 OS I gave /var a size of 10GB thinking it would be more than enough, but after I started using docker I found of that it takes too much space on the /var partition as it is shown by the df command:
[root@compute-07 ~]# df -h
Filesystem           Size  Used Avail Use% Mounted on
devtmpfs              28G     0   28G   0% /dev
tmpfs                 28G     0   28G   0% /dev/shm
tmpfs                 28G  179M   28G   1% /run
tmpfs                 28G     0   28G   0% /sys/fs/cgroup
/dev/mapper/cs-root  371G  8.2G  363G   3% /
/dev/mapper/cs-home  100G  2.0G   98G   2% /home
/dev/mapper/cs-var    10G  9.0G  1.1G  90% /var
/dev/sda2            2.0G  412M  1.6G  21% /boot
/dev/sda1            2.0G  7.3M  2.0G   1% /boot/efi
/dev/mapper/cs-tmp    10G  105M  9.9G   2% /tmp
tmpfs                5.5G   16K  5.5G   1% /run/user/42
overlay               10G  9.0G  1.1G  90%

/var/lib/docker/overlay2/77f74478297ca61595f0003d35c7323ec627adb44d94cef92c2b4a3c97319a66/merged
overlay               10G  9.0G  1.1G  90% /var/lib/docker/overlay2/5eeb399ce4a3c0d8065d63123985269a359fa66f4d20a8486326e466a48a0128/merged
overlay               10G  9.0G  1.1G  90% /var/lib/docker/overlay2/08d42ca66e3a5974bc305b502bca2aa4d22aa7ddcab6ea14c6af300b3abb3a70/merged
overlay               10G  9.0G  1.1G  90% /var/lib/docker/overlay2/1a45cb32b127fdf8f5c1483385139a865fdc69260ec20f3dcd4c56ad6890f909/merged
overlay               10G  9.0G  1.1G  90% /var/lib/docker/overlay2/ebb9af8edee824a4013dcd526e33e22272283bdee508fd43208fade557def728/merged
overlay               10G  9.0G  1.1G  90% /var/lib/docker/overlay2/41d55822108d04c85f348dc134fe6929b0e67f6b3bd7e0af147633bfd3a252c1/merged
overlay               10G  9.0G  1.1G  90% /var/lib/docker/overlay2/5cf3e8e06e9b4c2e6ed65164d91aed19f63d55e91524d6563e9f16b6709d29be/merged
overlay               10G  9.0G  1.1G  90% /var/lib/docker/overlay2/1d1eda94e68596b00d0cabcc75a7c91999a1c845ebd02c733bb9f00ac66a26f0/merged
overlay               10G  9.0G  1.1G  90% /var/lib/docker/overlay2/bc9e9a28c6761ad89a9457110642156ebd2b4d77de841f2a3ac9ffbaa90e4b63/merged

tmpfs                5.5G     0  5.5G   0% /run/user/0

This is the output of lsblk command, as /var is in a separate parition then / and /home I couldn't find a way to resize it or create another partition then link it to /var
[root@compute-07 ~]# lsblk
NAME        MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
sda           8:0    0 558.4G  0 disk
├─sda1        8:1    0     2G  0 part /boot/efi
├─sda2        8:2    0     2G  0 part /boot
└─sda3        8:3    0 554.4G  0 part
  ├─cs-root 253:0    0 370.4G  0 lvm  /
  ├─cs-swap 253:1    0    64G  0 lvm  [SWAP]
  ├─cs-tmp  253:2    0    10G  0 lvm  /tmp
  ├─cs-home 253:3    0   100G  0 lvm  /home
  └─cs-var  253:4    0    10G  0 lvm  /var
sr0          11:0    1  1024M  0 rom

Is there any way I could resize this partition without having to lose any data.

A: No. Actually, most of the space in the system is always used by /var where normally variable data lives — databases, Docker, logs, and so on, while Linux's /, rarely uses more than 10 GiB of space, when the system is properly managed.
Not only your LVM is suboptimal: I'd fit the whole Debian installation with some services into the space you wasted in your ESP and /boot. (I had a habit of creating VMs with 4GiB allocated for the system. More than enough.)
So well, the best solution would be to reduce your oversized root file system, but that couldn't be done online. You need to boot some rescue media, activate your VG and then reduce the file system and the logical volume and that could consume substantial time, considering the size of the partition. Also it is possible to mess things. If you're in hurry, you can make a twist: make some directory in root, move the Docker data into it and bind-mount it back into where Docker data live in var. You need to stop Docker and all containers for the time being. Something like this:
systemctl stop docker.service
mkdir /var-lib-docker
mv /var/lib/docker/* /var-lib-docker
mount --bind /var-lib-docker /var/lib/docker
systemctl start docker.service

That way, the Docker will use the space on the oversized root file system, while being available at the usual location. In the /etc/fstab you need to add the following entry, so this configuration will survive reboot:
/var-lib-docker /var/lib/docker none bind 0 0

But remember this is quite ugly hack which can buy you some time but also bring some problems, so look for the opportunity to reclaim space from the root and allocating it to /var properly.
And let this be the lesson: never allocate all avaliable space from the beginning. Leave some (most) of it unallocated. You can always easily add the space and do that online, while it is very hard, time consuming and error prone to reclaim it, and that requires downtime. It is best to manage the space so you never need to reclaim it.

A: As an alternative to this answer
Your system is using LVM  logical volumes.
There may be some unused space left in the volume group that you can assign to extend var.
In  case there isn't any unused space left, or too little, you can reduce or remove the swap LVM and take the space that gets freed up by that to extend /var.
That would leave your system intact and can typically even be done online.
The approach for that would be something along the lines of (commands untested, so don't copy them outright  but the principle should be sound)

*

*Create a temporary or permanent swap file on your oversized root file system as replacement while you take the swap partition offline.

*

*dd if=/dev/zero of=/swap-file count=65536 bs=1M

*mkswap /swap-file

*swapon /swap-file

*swapoff /dev/mapper/cs-swap  to disable the swap partition

*lvreduce cs-swap  followed by formatting  the remaining LVM swap partition again with mkswap and re-activating the smaller  swap space with swapon

*or delete it ouright with lvremove
Use the newly created free LVM space to extend the /var LVM volume and extend the file system system
lvextend -l +100%FREE --resizefs /dev/mapper/cs-var

A: Your df and lsblk don't tell us what their filesystems are. To shrink a volume (partition or LV), the filesystem on it must be shrunk first. A common choice for rootfs, ext4, can be shrunk offline. The default FS choice for CentOS (and RHEL-like distros), however, is XFS, and cannot be shrunk at present.
As others have pointed out in their answers, your rootfs usage 8.2 GB is not difficult to back up. So depending on your rootfs filesystem type, you have the following options:
If it's ext4, you can shrink it in-place:

*

*Reboot to another system, like an ArchISO, as ext4 can only be shrunk offline.

*Make sure lvs shows your partition, then e2fsck -f /dev/mapper/cs-root

*resize2fs -M -p /dev/mapper/cs-root

*

*Alternatively, if you know your desired rootfs size, you can specify it instead of using -M:
resize2fs -p /dev/mapper/cs-root 15G
Note that it's a better idea to leave some space for shrinking the underlying volume.

*Reclaim space from the LV lvreduce -L 16G cs/root

*Resize the filesystem back to the volume size: resize2fs -p /dev/mapper/cs-root

*Now the free space can be handed out to /var: lvextend -l +100%FREE cs/var
If it's XFS, however, your best bet is to backup your rootfs and recreate it:

*

*Boot up an ArchISO like above.

*rsync -avHAXx /your-rootfs /somewhere (Make sure /somewhere is on another volume - it's easy to find 8.2 GB of spare space - your swap volume is very likely oversized)

*lvremove the root volume and recreate it with an appropriate size. I recommend formatting to ext4 this time.

*rsync -avHAXx /somewhere /your-rootfs to copy things back.

*Update your GRUB configuration if needed - AFAICT the LV ID is often written into grub.cfg as a hint, but I'm not familiar with CentOS (on Debian it'd be simply update-grub).

*Assign free space in the VG as above.

Other notes I'd like to point out:

*

*Your EFI system partition (ESP) is too large. For a typical Linux server, 256 MB should be more than enough (I use 128 MB on my Ubuntu server). It only needs to hold the GRUB binary and a very basic version of grub.cfg.

*/boot doesn't have to live on its own volume. GRUB can read LVM and your rootfs filesystem just fine.

*Depending on your server design, your /root is likely oversized as well (I use 16 GB for my Proxmox VE server - I'm not planning to put data on the host).

*Do you really need 64 GB of swap space? Normally I'm fine with just 8 GB.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Capture the text of a LABEL to be used in QUERY I have reorganized everything then.
I want to capture the text that is contained in a label I have in a form in order
to be used as the input for the WHERE criteria.
The query is the next called qry_A:
SELECT
tbl_R.ID_R,
tbl_C.Cuenta,
tbl_C.Nombre,
IIf(tbl_RD.Deb Is Null,0,tbl_RD.Deb) AS Deb,
IIf(tbl_RD.Cre Is Null,0,tbl_RD.Cre) AS Cre,
tbl_R.NIT,
tbl_R.Fecha,
tbl_R.Com,
tbl_F.ID_F,
tbl_R.ID_U

FROM
(tbl_F INNER JOIN tbl_R ON tbl_F.ID_F = tbl_R.Fideicomiso)
INNER JOIN (tbl_C RIGHT JOIN tbl_RD ON tbl_C.Cuenta = tbl_RD.Cuenta) ON tbl_R.ID_R = tbl_RD.ID_R

WHERE ((tbl_R.ID_U)=[Forms]![frm_qry_A]![lbl_Usuario]);

I've checked the name of the label and the name of the form. Not sure if this is possible to do with a label, I've checked and tried with a Text Field in the form and it works, I mean, if I capture the text of a  Text Field of another form that I have it goes, this is the line added to the query in order to illustrate what I did:
WHERE ((tbl_R.ID_U)=[Forms]![frm_B]![txt_Usuario]);

With that I capture the criteria or text declared in the Form called form_B as this:
Private Sub Form_Load()
    Me.lbl_Usuario.Caption = LCase(UsuarioLogeado)
    Me.txt_Usuario = UsuarioLogeado
End Sub

A: You forget to type Parameters collection name:
'Associate parameter
tomarConsulta.Parameters!capturarUsuario = txt_Usuario

or better:
'Associate parameter
tomarConsulta.Parameters("capturarUsuario").Value = txt_Usuario

A: The label's Caption property contains the text which the label displays.  So reference Caption explicitly when you reference the label in the SQL statement.
WHERE tbl_R.ID_U=[Forms]![frm_B]![lbl_Usuario].Caption


text:
Q: CoreBluetooth Fire a method when other device is asking to pair? I am new to Corebluetooth.framework, I want to fire a simple method when other device
wants to connect to ios device.
Any guidance will be appreciated.

A: You cannot intercept the connection event, nor the service discovery. The first time you even "hear" about a central being connected to your device (acting as the peripheral) is when the central is trying to read, write dynamic characteristics or subscribes for notifications.
If you have a scenario in mind where the central lets know the peripheral that it is there and the peripheral can start doing something with this info, then you need to implement this in a proprietary way using any of the read, write or subscribe events.
Additional note: you cannot force a central to disconnect from your peripheral. The only way to do this is the deallocation of the CBPeripheralManager. But even in that case, iOS will decide when to really close the connection.


text:
Q: How to display validation error near textbox I have this form in index.php
<form action="result.php" method="post">
<input type="text" name="word" class="tbox">
<input type="submit" name="submit" value="Generate Now">
</form>

In result.php i am checking whether the input matches all validation condition and generating the output. Now, if it doesnt match, i ve to throw an error near my text box. Is that possible through php?

A: Using PHP, you may try like below
<input type="text" name="word" class="tbox"> <?php if(isset($_POST['word']) && $_POST['word'] == ''){ echo 'YOUR ERROR MESSAGE'; } ?>

A: a few things, one you can just post against the page itself not great to have DB functions and the like in user reachable areas so check out includes and use them to reference the single page.
Then make a simple variable and slide it into your form as such
<? echo $error ?>

and set error to something via the php script imported from result.php, or you may want to learn about sessions and get variables if combining the files via include isn't on the table.
Once its working then say make a div box as such
<? if (isset($error)){?>
<? echo $error?>
<? }?>


text:
Q: How to make grub as a Default(Primary) bootloader in a Legacy BIOS system(MBR) I have removed windows Entirely and installed Ubuntu 20.04 only, by using the option "Erase Disk and Install Ubuntu". The installation gets completed Successfully but after the Restart Blank Screen with "_" Blinking will come.
My laptop have Legacy BIOS.
Before I had a dual boot (Windows and Ubuntu) in which I used Easy BCD in Windows to create a boot menu entry for ubuntu, so by using that with the first boot menu if I use to select Ubuntu it use to redirect to Grub bootloader. As far I understood as there are no boot menu entry for primary bootloader nothing comes.
Is there any why I can get Grub as my Default bootloader without having Windows.

A: try booting to a rescue disc (or any live linux usb) and running:
grub2-install /dev/sda

(replace /dev/sda with your boot drive device if it is not sda)


text:
Q: jQuery datatable export to Excel customization - Make first row bold I have a datatable with export to excel button I am trying to customize.
I looked around to see how to customize and found a few but still having problem with this.
When you export to excel the first row seems to be page title. I am trying to make this row bold; and if possible replace the text with something else other than the page title.
Here is what I saw and tried to modify to achieve what I need:
buttons: [
{
    extend: 'excelHtml5',
    customize: function ( xlsx ){
        var sheet = xlsx.xl.worksheets['sheet1.xml'];

        // jQuery selector to add a border
        //$('row c[r*="0"]', sheet).attr( 's', '25' );
        //$('row c[r^="C"]', sheet).attr( 's', '2' ); // third column is bold

        // Trying to make first row bold, this makes last row bold
        $('row c[r*="0"]', sheet).attr( 's', '2' );
        $(sheet.body)
            .css('font-size', '10pt');

        $(sheet.body).find('table')
            .addClass('compact')
            .css('font-size', 'inherit');
    },
    exportOptions: {
        columns: [0, 1, 2]
    },
},

Also, when applying formatting it seems we use 'attr' with first parameter 's' and a number. How do I find out that 25 implies border and 2 implies bold?
I don't understand how to manipulate the following to effect styling changes:
    $('row c[r*="0"]', sheet).attr( 's', '2' );
    $('row c[r^="C"]', sheet).attr( 's', '25' );

A: Assuming you have the buttons extension installed, then the following will print a custom title in the first row of the spreadsheet, and it will make that title bold:
$(document).ready(function() {

  $('#myTable').DataTable( {
    dom: 'Bfrtip',
    buttons: [
        {
          extend: 'excel',
          customize: function ( xlsx ) {
            var sheet = xlsx.xl.worksheets['sheet1.xml'];
            $('c[r=A1] t', sheet).text( 'Custom Heading in First Row' );
            $('row:first c', sheet).attr( 's', '2' ); // first row is bold
          }
        }
    ]
  } );

});

Example:

Regarding the pre-defined formats you mentioned, you can see a list of them here.
0 - Normal text
1 - White text
2 - Bold
3 - Italic
4 - Underline
etc...

The custom commands to manipulate the exported data are also summarized in the same page. But you would need to refer to SheetJS for more details, I think.


text:
Q: Sorting input radio boxes alphabetically I am trying to sort this items alphabetically but it is not sorting all items as it should be. Can you give me some ideas why it is not working ?
Here is my fiddle example.
jsFiddle Link

handleAlphaOrder = function() {
    var fieldItem = $('.field_item');
    var sorted = $(fieldItem.toArray().sort(function(a, b) {
        return $(a).find('label').text() > $(b).find('label').text()
    }));

    fieldItem.each(function(i) {
        $(this).after(sorted.eq(i));
    });
};

    <input type="radio" name="category" value="1" id="productspage-category-women">
    Women

    <input type="radio" name="category" value="1-2" id="productspage-category-womenbags">
    Women's bags

    <input type="radio" name="category" value="1-4" id="productspage-category-jewellery">
    Jewellery

    <input type="radio" name="category" value="2" id="productspage-category-men">
    Men

    <input type="radio" name="category" value="2-2" id="productspage-category-menbags">
    Men's bags

    <input type="radio" name="category" value="2-4" id="productspage-category-menshoes">
    Men's shoes

    <input type="radio" name="category" value="3-1" id="productspage-category-baby">
    Baby

    <input type="radio" name="category" value="3-3" id="productspage-category-girl">
    Girl

    <input type="radio" name="category" value="4" id="productspage-category-home">
    Home

    <input type="radio" name="category" value="4-2" id="productspage-category-bed">
    Bed

    <input type="radio" name="category" value="4-5" id="productspage-category-kitchen">
    Kitchen

    <input type="radio" name="category" value="4-7" id="productspage-category-lighting">
    Lighting

    <input type="radio" name="category" value="4-10" id="productspage-category-outdoor">
    Outdoor

    <input type="radio" name="category" value="5-1" id="productspage-category-haircare">
    Hair care

    <input type="radio" name="category" value="5-3" id="productspage-category-mengrooming">
    Men's grooming

    <input type="radio" name="category" value="5-6" id="productspage-category-skincare">
    Skincare

    <input type="radio" name="category" value="6" id="productspage-category-lifestyle">
    Lifestyle

    <input type="radio" name="category" value="6-4" id="productspage-category-foodsupplements">
    Food supplements

    <input type="radio" name="category" value="6-5" id="productspage-category-treatments">
    Treatments

    <input type="radio" name="category" value="6-6" id="productspage-category-electronics">
    Electronics

    <input type="radio" name="category" value="" id="productspage-category-all">
    All

    <input type="radio" name="category" value="1-1" id="productspage-category-womenaccessories">
    Women's accessories

    <input type="radio" name="category" value="1-3" id="productspage-category-womenclothing">
    Women's clothing

    <input type="radio" name="category" value="1-5" id="productspage-category-womenshoes">
    Women's shoes

    <input type="radio" name="category" value="2-1" id="productspage-category-menaccessories">
    Men's accessories

    <input type="radio" name="category" value="2-3" id="productspage-category-menclothing">
    Men's clothing

    <input type="radio" name="category" value="3" id="productspage-category-kids">
    Kids

    <input type="radio" name="category" value="3-2" id="productspage-category-boy">
    Boy

    <input type="radio" name="category" value="3-4" id="productspage-category-toys">
    Toys

    <input type="radio" name="category" value="4-1" id="productspage-category-bath">
    Bath

    <input type="radio" name="category" value="4-3" id="productspage-category-childrenhome">
    Children's home

    <input type="radio" name="category" value="4-6" id="productspage-category-furniture">
    Furniture

    <input type="radio" name="category" value="4-11" id="productspage-category-decor">
    Decor

    <input type="radio" name="category" value="5" id="productspage-category-beauty">
    Beauty

    <input type="radio" name="category" value="5-2" id="productspage-category-makeup">
    Makeup

    <input type="radio" name="category" value="5-5" id="productspage-category-perfume">
    Perfume

    <input type="radio" name="category" value="5-8" id="productspage-category-healthbody">
    Health & body

    <input type="radio" name="category" value="6-1" id="productspage-category-fooddrinks">
    Food & drinks

    <input type="radio" name="category" value="6-2" id="productspage-category-yoga">
    Yoga

    <input type="radio" name="category" value="6-3" id="productspage-category-gadgets">
    Gadgets

    <input type="radio" name="category" value="6-7" id="productspage-category-fitness">
    Fitness

A: Problem is that you never call handleAlphaOrder, only declare it.

handleAlphaOrder = function() {
  var fieldItem = $('.field_item');
  var sorted = $(fieldItem.toArray().sort(function(a, b) {
    return $(a).find('label').text() > $(b).find('label').text()
  }));

  fieldItem.each(function(i) {
    $(this).after(sorted.eq(i));
  });
};
handleAlphaOrder(); // Call function now

  <input type="radio" name="category" value="1" id="productspage-category-women">
  Women

  <input type="radio" name="category" value="1-2" id="productspage-category-womenbags">
  Women's bags

  <input type="radio" name="category" value="1-4" id="productspage-category-jewellery">
  Jewellery

  <input type="radio" name="category" value="2" id="productspage-category-men">
  Men

  <input type="radio" name="category" value="2-2" id="productspage-category-menbags">
  Men's bags

  <input type="radio" name="category" value="2-4" id="productspage-category-menshoes">
  Men's shoes

  <input type="radio" name="category" value="3-1" id="productspage-category-baby">
  Baby

  <input type="radio" name="category" value="3-3" id="productspage-category-girl">
  Girl

  <input type="radio" name="category" value="4" id="productspage-category-home">
  Home

  <input type="radio" name="category" value="4-2" id="productspage-category-bed">
  Bed

  <input type="radio" name="category" value="4-5" id="productspage-category-kitchen">
  Kitchen

  <input type="radio" name="category" value="4-7" id="productspage-category-lighting">
  Lighting

  <input type="radio" name="category" value="4-10" id="productspage-category-outdoor">
  Outdoor

  <input type="radio" name="category" value="5-1" id="productspage-category-haircare">
  Hair care

  <input type="radio" name="category" value="5-3" id="productspage-category-mengrooming">
  Men's grooming

  <input type="radio" name="category" value="5-6" id="productspage-category-skincare">
  Skincare

  <input type="radio" name="category" value="6" id="productspage-category-lifestyle">
  Lifestyle

  <input type="radio" name="category" value="6-4" id="productspage-category-foodsupplements">
  Food supplements

  <input type="radio" name="category" value="6-5" id="productspage-category-treatments">
  Treatments

  <input type="radio" name="category" value="6-6" id="productspage-category-electronics">
  Electronics

  <input type="radio" name="category" value="" id="productspage-category-all">
  All

  <input type="radio" name="category" value="1-1" id="productspage-category-womenaccessories">
  Women's accessories

  <input type="radio" name="category" value="1-3" id="productspage-category-womenclothing">
  Women's clothing

  <input type="radio" name="category" value="1-5" id="productspage-category-womenshoes">
  Women's shoes

  <input type="radio" name="category" value="2-1" id="productspage-category-menaccessories">
  Men's accessories

  <input type="radio" name="category" value="2-3" id="productspage-category-menclothing">
  Men's clothing

  <input type="radio" name="category" value="3" id="productspage-category-kids">
  Kids

  <input type="radio" name="category" value="3-2" id="productspage-category-boy">
  Boy

  <input type="radio" name="category" value="3-4" id="productspage-category-toys">
  Toys

  <input type="radio" name="category" value="4-1" id="productspage-category-bath">
  Bath

  <input type="radio" name="category" value="4-3" id="productspage-category-childrenhome">
  Children's home

  <input type="radio" name="category" value="4-6" id="productspage-category-furniture">
  Furniture

  <input type="radio" name="category" value="4-11" id="productspage-category-decor">
  Decor

  <input type="radio" name="category" value="5" id="productspage-category-beauty">
  Beauty

  <input type="radio" name="category" value="5-2" id="productspage-category-makeup">
  Makeup

  <input type="radio" name="category" value="5-5" id="productspage-category-perfume">
  Perfume

  <input type="radio" name="category" value="5-8" id="productspage-category-healthbody">
  Health & body

  <input type="radio" name="category" value="6-1" id="productspage-category-fooddrinks">
  Food & drinks

  <input type="radio" name="category" value="6-2" id="productspage-category-yoga">
  Yoga

  <input type="radio" name="category" value="6-3" id="productspage-category-gadgets">
  Gadgets

  <input type="radio" name="category" value="6-7" id="productspage-category-fitness">
  Fitness

A: Your sort is working, but you are not seeing the results because you are incorrectly appending your field-items back to your DOM. Try adding a wrapper around all of your field-item divs (radioGroup in the example below) and then append to it instead of trying to overlay the existing divs. Overlaying them is what is causing you problems.
Also, you should probably use localeCompare when comparing text instead of > or <. String.prototype.localeCompare()
Give this a try:

handleAlphaOrder = function() {
  var fieldItem = $('.field_item');
  var sorted = $(fieldItem.toArray().sort(function(a, b) {
    //return $(a).find('label').text() > $(b).find('label').text()
    return $(a).find('label').text().localeCompare($(b).find('label').text());
  }));

  fieldItem.each(function(i) {
    //$(this).after(sorted.eq(i));
    $('#radioGroup').append(sorted.eq(i));
  });
};

handleAlphaOrder();

        <input type="radio" name="category" value="1" id="productspage-category-women">
        Women

        <input type="radio" name="category" value="1-2" id="productspage-category-womenbags">
        Women's bags

        <input type="radio" name="category" value="1-4" id="productspage-category-jewellery">
        Jewellery

        <input type="radio" name="category" value="2" id="productspage-category-men">
        Men

        <input type="radio" name="category" value="2-2" id="productspage-category-menbags">
        Men's bags

        <input type="radio" name="category" value="2-4" id="productspage-category-menshoes">
        Men's shoes

        <input type="radio" name="category" value="3-1" id="productspage-category-baby">
        Baby

        <input type="radio" name="category" value="3-3" id="productspage-category-girl">
        Girl

        <input type="radio" name="category" value="4" id="productspage-category-home">
        Home

        <input type="radio" name="category" value="4-2" id="productspage-category-bed">
        Bed

        <input type="radio" name="category" value="4-5" id="productspage-category-kitchen">
        Kitchen

        <input type="radio" name="category" value="4-7" id="productspage-category-lighting">
        Lighting

        <input type="radio" name="category" value="4-10" id="productspage-category-outdoor">
        Outdoor

        <input type="radio" name="category" value="5-1" id="productspage-category-haircare">
        Hair care

        <input type="radio" name="category" value="5-3" id="productspage-category-mengrooming">
        Men's grooming

        <input type="radio" name="category" value="5-6" id="productspage-category-skincare">
        Skincare

        <input type="radio" name="category" value="6" id="productspage-category-lifestyle">
        Lifestyle

        <input type="radio" name="category" value="6-4" id="productspage-category-foodsupplements">
        Food supplements

        <input type="radio" name="category" value="6-5" id="productspage-category-treatments">
        Treatments

        <input type="radio" name="category" value="6-6" id="productspage-category-electronics">
        Electronics

        <input type="radio" name="category" value="" id="productspage-category-all">
        All

        <input type="radio" name="category" value="1-1" id="productspage-category-womenaccessories">
        Women's accessories

        <input type="radio" name="category" value="1-3" id="productspage-category-womenclothing">
        Women's clothing

        <input type="radio" name="category" value="1-5" id="productspage-category-womenshoes">
        Women's shoes

        <input type="radio" name="category" value="2-1" id="productspage-category-menaccessories">
        Men's accessories

        <input type="radio" name="category" value="2-3" id="productspage-category-menclothing">
        Men's clothing

        <input type="radio" name="category" value="3" id="productspage-category-kids">
        Kids

        <input type="radio" name="category" value="3-2" id="productspage-category-boy">
        Boy

        <input type="radio" name="category" value="3-4" id="productspage-category-toys">
        Toys

        <input type="radio" name="category" value="4-1" id="productspage-category-bath">
        Bath

        <input type="radio" name="category" value="4-3" id="productspage-category-childrenhome">
        Children's home

        <input type="radio" name="category" value="4-6" id="productspage-category-furniture">
        Furniture

        <input type="radio" name="category" value="4-11" id="productspage-category-decor">
        Decor

        <input type="radio" name="category" value="5" id="productspage-category-beauty">
        Beauty

        <input type="radio" name="category" value="5-2" id="productspage-category-makeup">
        Makeup

        <input type="radio" name="category" value="5-5" id="productspage-category-perfume">
        Perfume

        <input type="radio" name="category" value="5-8" id="productspage-category-healthbody">
        Health & body

        <input type="radio" name="category" value="6-1" id="productspage-category-fooddrinks">
        Food & drinks

        <input type="radio" name="category" value="6-2" id="productspage-category-yoga">
        Yoga

        <input type="radio" name="category" value="6-3" id="productspage-category-gadgets">
        Gadgets

        <input type="radio" name="category" value="6-7" id="productspage-category-fitness">
        Fitness


text:
Q: Placing image over an image with buttons I currently have a canvas with a background image and buttons on top of it.  I am trying to get it so that when a certain button is clicked, a new image will be laid over the top of the background image and buttons.  What I have right now is this:
import tkinter as tk
from xlrd import *
from PIL import Image, ImageTk

#GLOBAL VARIABLES

WIDTH = 720
HEIGHT = 960

#create window
window = tk.Tk()
window.title("NFL")
window.geometry("960x720")

#create canvas
canvas = tk.Canvas(window, width = WIDTH*2, height = HEIGHT*2)
canvas.pack()

#use NFL logo as background
nfl_logo_image = Image.open('nfl.jpg')
nfl_logo_image = nfl_logo_image.resize((HEIGHT, WIDTH), Image.ANTIALIAS)
nfl_logo = ImageTk.PhotoImage(nfl_logo_image)
canvas.create_image(0, 0, image = nfl_logo, anchor = 'nw')

#CAR button
def press_car_button():
    canvas2 = tk.Canvas(window, width = WIDTH*2, height = HEIGHT*2)
    canvas2.pack()
    big_car_logo = Image.open('car.png')
    big_car_logo = big_car_logo.resize((WIDTH, WIDTH), Image.ANTIALIAS)
    big_car_image = ImageTk.PhotoImage(big_car_logo)
    canvas2.create_image(0, 0, image = big_car_image, anchor = 'nw')

car_logo = Image.open('car.png')
car_logo = car_logo.resize((70,70), Image.ANTIALIAS)
car_image = ImageTk.PhotoImage(car_logo)
car_button = tk.Button(window, image = car_image, height = 70, width = 70, command = press_car_button)
car_button_window = canvas.create_window(720, 195, anchor = 'nw', window = car_button)

#run GUI
window.mainloop()

When I run this, the background image and button both come up fine, but when I click on the button, nothing happens.
Thanks in advance for any help!

A: You are forcing the window to be a specific size. Then, you use pack without any options which means the new canvas is packed to the top of the available space. That means that it's packed below the other canvas, which means it won't be visible since the first canvas is twice the window height.
There are many solutions, all dependent on exactly what you want to happen. For one, instead of creating a new canvas you can simply re-use the existing canvas by adding a new image. Or, you can use a new canvas after first hiding the old with place_forget. Or, you can use grid or place to insure that both canvases are put on the window at the same location.


text:
Q: Setting the background color of persp() plots Is there any way to set the background color of plots constructed using the base R function persp()?
bg="black" is ignored either when supplied to persp() or previously to par().

A: I'm not sure what you mean by "ignored" here. A reproducible example would be helpful, something like this:
 par(bg = "black");persp(volcano)


text:
Q: selenium python can't perform click event I need to click each of variation in this page.
My code clicking on first element but I am getting error when it trying to click on second element. Here is my code:
from selenium import webdriver
import time
url = 'https://www.zzounds.com/item--RNESEVENTYTWOMK2?siid=320037'
driver = webdriver.Chrome()
driver.get(url)

click = driver.find_elements_by_css_selector(".product-button")
for i in click:
    text = i.text
    print(text)
    i.click()
    time.sleep(3)

error which I am getting when trying to click on second element:
selenium.common.exceptions.WebDriverException: Message: target frame detached
  (Session info: chrome=102.0.5005.62)


text:
Q: Programming a button press in one view controller, to load and save a cell in a different table view controller In my application I have a number of view controllers, all of which have a favorite button on. When the favorite button is pressed, I want some information about the view controller to be saved in a separate table view in a different table view controller.
This is my first IOs app, and even after reading about Core Data, I'm at a bit of a loss as to how to go forwards.
How would I go about implementing such a feature?
Thanks for helping a novice out!
Cheers.

A: To store information locally you can use the NSUserDefaults class.
On the favorite button action method, save the viewcontroller name in an NSMutableArray using NSUserDefaults
    -(IBAction)btnFavouriteClick:(id)sender {

      NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

      //Get favorited views array (new array will be created if it doesn't  exist)
      NSMutableArray *favoriteviews = [defaults mutableArrayValueForKey:@"favorite_views_key"];

      //Add current view name to the array
      [favoriteviews addObject:@"viewcontroller_name"];

      //Add the array back in NSUserDefaults
      [defaults setObject:favoriteviews forKey:@"favorite_views_key"];

      //Save NSUserDefaults
      [defaults synchronize];
    }

You can retrieve the values using favorite_views_key and show them in the UITableView
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    //Get favorited views array
    NSMutableArray *favoriteviews = [defaults mutableArrayValueForKey:@"favorite_views_key"];

favoriteviews is array of all the favorited views.


text:
Q: $\omega$ a continuous $m$-form in $M$, $\dim M=m$, $M$ is orientable $\iff \omega \neq 0$ Let $M$ a surface, $\dim M=m$, and let $\omega$  a continuous $m-$form in $M$. I want to prove that $M$ is orientable $\iff \omega(x)\neq 0\; \forall x\in M$.
The $(\Leftarrow)$ part is ok to me, since I say this post. However, I don't know exactly how to prove the $(\Rightarrow) $ part, even if it looks  kind of obvious.
I tried to taking two parametrizations $\phi,\psi$ of $x\in M$ in an orientation of $M$ and work with writting $\omega$ in each basis, but I don't know exactly how to proceed.
Any tips?

A: The statement as written is false. On any manifold (orientable or otherwise), there exists a continuous $m$-form that is equal to zero everywhere. That is a trivial counterexample.
I think the statement should say, if $M$ is orientable then there exists a continuous $m$-form $\omega$ such that $\omega(x) \neq 0$ for all $x \in M$.
To construct this $m$-form, I suggest you take a positively-oriented atlas, and construct positive-valued $m$-forms locally in each coordinate chart. Then multiply these local $m$-forms by a partition of unity (so that they can be extended continuously to the entire manifold), and add them together. Use the fact that the Jacobian determinants are positive (since the charts are positively-oriented with respect to each other) to conclude that the sum of the local $m$-forms is also positive in each chart.


text:
Q: How to address (hidden) volume for vssadmin I have a volume named like this
\\?\Volume{fc3a230-ef05-d9875-c2fa-3aacteb234}\

How can I address this in the following command
vssadmin resize shadowstorage /for=\\?\Volume{fc3a230-ef05-d9875-c2fa-3aacteb234}\ /On=C: /MaxSize=UNBOUNDED

I get errors like invalid option or the given volume shadow copy association was not found. Or do I don't have access to it?

A: I get errors like invalid option or the given volume shadow copy association was not found.
vssadmin resize shadowstorage ... requires a drive specification. For example:
vssadmin resize shadowstorage /for=C: /on=C: /maxsize=50GB

Where:
/for=C: /on=C:

Tells Windows that the VSS storage is on the C drive, change the letter to match your environment.

Further Reading

*

*An A-Z Index of the Windows CMD command line

*A categorized list of Windows CMD commands

*vssadmin - Display the current volume shadow copy backups and all installed shadow copy writers and providers.


text:
Q: What Laravel cache do I need to clear to remove error about missing migration file? I've got a couple of migrations for tables within my app. The tables are:

*

*people

*skills

*media

*notes

There is a one to many relationship between people and each of the other tables.
// The people table definition

Schema::create('people', function (Blueprint $table) {
    $table->uuid('id');
    $table->primary('id');
    ...
    $table->timestamps();
});

// the skill table definition with the foreign key constraint referencing people

Schema::create('skills', function (Blueprint $table) {
    $table->uuid('id');
    $table->primary('id');
    $table->uuid('person_id');
    $table->foreign('person_id')
            ->references('id')->on('people')
            ->onDelete('cascade');
    ...
    $table->timestamps();
});

When I was creating the migrations via artisan I accidentally created the skills migration file before the people migration.
This caused a problem because when you run php artisan migrate, the files are fired in timestamp order and if a primary key is not established before a foreign key constraint is defined you get an error, e.g.
The file:
2016_02_24_174227_create_people_table.php

Will fire after the file:
2016_02_24_174221_create_skills_table.php

Because the skills file has a smaller timestamp prefix in the name (17:42:21 comes before 17:42:27). This means the foreign key constraint in skills is looking for a primary key in people that doesn't exist yet.
So to fix that, I renamed the file 2016_02_24_174227_create_people_table.php to 2016_02_24_170000_create_people_table.php.
This fix worked, but now whenever I php artisan migrate:refresh my tables, I get an error saying that artisan is somehow still looking for the old people file:

I tried clearing the application cache with php artisan cache:clear, but I still get the error.
Is there a particular cache I need to clear to remove the reference to the original migration file?

A: Rollback your migration and check
migrate:rollback

A: It's not a cache issue. You just have to run composer again:
composer dump-autoload


text:
Q: How can I install Ubuntu without using the Wubi installer? I have read a Danish book about Ubuntu. It seemed quite "easy" so I have decided that I want to erase windows 7 (actually windows 8 consumer preview) completely and install Ubuntu.
The problem is that I only could find Wubi installers on the webpage. What to do?

A: This should give you all the information you need
https://help.ubuntu.com/community/GraphicalInstall
If you download from a torrent there should be no need to check that the download is good prior to burning.
Torrent download options can be found on the same page as the other Ubuntu download options - http://releases.ubuntu.com/precise/

A: Nothing to worry, just download the latest Ubuntu release from here and write it in a CD/DVD and boot with CD/DVD drive afterwards.
http://www.ubuntu.com/download/desktop

A: There is nothing different for ubuntu when it comes to installing an operating system.You follow the exact same procedure as you would do with any other OS,like Windows or Mac.
Of course you can use the wubi installer if you are unfamiliar with the installing procedures,but ubuntu will not be installed in another partition of your hard drive, just "nested" inside your already running windows/mac partition.
The ubuntu help page provides lots of useful information on how to install ubuntu:
First of all,what you have to do is download the .iso file containing ubuntu from the related ubuntu page.Then you can burn the .iso file into a USB drive and boot from there, which you can achieve using the cross-platform tool named Unetbootin.
You may also burn the .iso in a CD, following this  Microsoft Windows tutorial.
Last but not least, you can buy a CD with Ubuntu 12.04 pre-installed from the Official Canonical Store.
Good luck!

A: I keep repeating the error - somehow when creating a boot USB disk I am getting the wrong version and no dialogue comes up for options to select 'replace windows'. I cannot seem to distinguish the correct series of links on the website to the correct download... At least I think that is my error, or is it further along in the process where I could be going wrong?
I installed using WUBI but did not realise until the restart that it was nested. Perhaps it is appropriate to note for newbs exctly what WUBI is before we download. I will now dig deep into the links to find an ISO that is not partition installed within windows.
Part of my reason for putting Ubuntu on one of my machines instead of windows is that it is now 10 years old, and post service pack 3, it is just dysfunctional. I wanted a clean install.
Anyhows Ububtu runs far slicker on the machine than windows did, I like the UI, reminds me a bit of apple 20 years ago. That is a complement btw.

A: There is also Pendrive Linux.  Download the Ubuntu ISO image from the download section of Ubuntu.com and then use this guide to get the ISO image on the USB flashdrive: http://www.pendrivelinux.com/universal-usb-installer-easy-as-1-2-3/.


text:
Q: Show that $(-1)^{N_{t}}$ has independent increments, where $(N_{t})_{t>0}$ is a standard Poisson process. I am working on an exercise in the stochastic process:

Show that $X_{t}:=(-1)^{N_{t}}$ is a Markov Process, where $(N_{t})_{t>0}$ is a standard Poisson process.

I was nearly done, by reading this post: If $N_t$ is a Poisson process and $Y\in\{-1,1\}$, then $X_t = Y(-1)^{N_t}$ is a Markov process
However, I have two questions about the proof in this post.
$(1)$ Why does the fact $(N_{t})$ has independent increments implies $(-1)^{N_{t}}$ has independent increments?
$(2)$ In one step, he used
\begin{align*}
\mathbb{P}\Big((-1)^{N_{t}}=m, (-1)^{N_{t_{k}}}=m_{k},\cdots&, (-1)^{N_{t_{1}}}=m_{1}\Big)\\
&=\mathbb{P}\Big((-1)^{N_{t}-N_{t_{k}}}=\frac{m}{m_{k}}, \cdots, (-1)^{N_{t_{2}}-N_{t_{1}}}=\frac{m_{2}}{m_{1}}, (-1)^{N_{t_{1}}}=m_{1}\Big)
\end{align*}
what is the reason behind this equality? stationary?
Thank you!

A:
Observation 1: If $f: \mathbb{R} \to \mathbb{R} \backslash \{0\}$ is a measurable function and $X_1,\ldots,X_n$ any real-valued random variables, then \begin{align*} &\mathbb{P}(f(X_1)=c_1,\ldots,f(X_n)=c_n) \\ &= \mathbb{P} \left( f(X_1)=c_1, \frac{f(X_2)}{f(X_1)} =\frac{c_2}{c_1},\ldots,\frac{f(X_n)}{f(X_{n-1})} = \frac{c_n}{c_{n-1}} \right)\end{align*} for any constants $c_1,\ldots,c_n \in \mathbb{R} \backslash \{0\}$.

Applying this for $f(x)=(-1)^x$ and $X_i = N_{t_i}$ answers your second question.
For the proof of the identity, take $\omega \in A:=\bigcap_{j=1}^n \{f(X_j)=c_j\}$. Then clearly
$$\frac{f(X_j(\omega))}{f(X_{j-1}(\omega))} = \frac{c_j}{c_{j-1}}$$
for all $j=2,\ldots,n$ and so $$\omega \in B:=\{f(X_1)=c_1\} \cap \bigcap_{j=2}^n \left\{\frac{f(X_j)}{f(X_{j-1})} = \frac{c_j}{c_{j-1}} \right\}.$$ Hence, $A \subseteq B$. On the other hand, if $\omega \in B$, then
$$f(X_2(\omega)) = \frac{f(X_2(\omega))}{f(X_1(\omega))} f(X_1(\omega)) = \frac{c_2}{c_1} c_1 = c_2.$$ Iterating the procedure, we get $f(X_k(\omega)) =c_k$ for all $k=3,\ldots,n$, and so $B \subseteq A$. In conclusion, $B=A$ and, in particular, $\mathbb{P}(B)=\mathbb{P}(A)$.

Observation 2: If $X_1,\ldots,X_n$ are indepndent random variables and $f$ a measurable function, then $f(X_1),\ldots,f(X_n)$ are independent.

This is a well-known fact from probability theory. Since the Poisson process $(N_t)_{t \geq 0}$ has independent increments, it follows that $f(N_{t_1}),f(N_{t_2}-N_{t_1}),\ldots,f(N_{t_n}-N_{t_{n-1}})$ are independent for any $0<t_1<\ldots<t_n$. If we choose $f(x)=(-1)^x$ this gives that $(-1)^{N_{t_n}-N_{t_{n-1}}},\ldots,(-1)^{N_{t_2}-N_{t_1}},(-1)^{N_{t_1}}$ are independent. (Note that the linked proof does neither use nor claim that $(-1)^{N_t}$ has independent increments.)


text:
Q: Unable to map SQL Query Response to C# variables I have this SQL Query Script which I am trying to invoke through ADO.Net code.
DECLARE
  @Error NVARCHAR(MAX)
DECLARE
  @Errors TABLE
  (
    [Column_Name] VARCHAR(MAX),
    [Message] VARCHAR(MAX)
  )

IF NOT EXISTS(...)
BEGIN
  INSERT INTO @Errors
  SELECT
    'Col1',
    'value does not exist.'
END

IF NOT EXISTS(...)
BEGIN
  INSERT INTO @Errors
  SELECT
    'Col2',
    'value does not exist.'
END

IF EXISTS (SELECT * FROM @Errors)
BEGIN
  SET @Error = (
    SELECT
      [Column_Name],
      [Message]
    FROM
      @Errors
    FOR JSON PATH, INCLUDE_NULL_VALUES
  );

  SELECT @Error AS 'Error_Message'
END
ELSE
BEGIN
    SELECT TOP(1) Id
    FROM dbo.table
END

This is the C# code
using (var conn = await _connectionFactory.OpenConnectionAsync(database: "dbName", readOnly: true))
{
    using (var cmd = conn.CreateCommandFromSqlFile(path, "test.sql"))
    {
        string errors = string.Empty;
        Guid id;

        using (DataReader reader = await cmd.ExecuteReaderAsync(ct))
        {
            if (reader.HasRows)
            {
                while (await reader.ReadAsync(ct))
                {
                    errors = reader.GetString("Error_Message");
                    id = reader.GetGuid("Id");
                }
            }
        }
    }
}

The SQL Script always returns either, Error_Message or Id based on the condition. If @Errors table is populated, it returns Error_Message and if there are no errors then it returns the Id.
I am trying to get these values in the c# code but it throws an exception in the while block, since one of the values, either Error_Message or Id will not be present.
I need help in getting these values gracefully to my C# code. Is there a way to do it?

A: You can use the GetName function of the SqlDataReader
using (SqlDataReader reader = await cmd.ExecuteReaderAsync(ct))
{
    if (reader.HasRows)
    {
        while (await reader.ReadAsync(ct))
        {
            var colName = reader.GetName(0);
            if (colName.Equals("Error_Message")
                errors = reader.GetString("Error_Message");
            else
                id = reader.GetGuid("Id");
        }
    }
}

https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqldatareader.getname?view=dotnet-plat-ext-3.1#System_Data_SqlClient_SqlDataReader_GetName_System_Int32_

A: I don't think there is a "graceful" way to do it the way you're structuring it IMHO

*

*you could use a c# try catch, to catch the exception that occurs when error is not present, but exception handling is slooow and shouldn't be used as a normal flow of control device

*you could change your queries so that they both return the same column names so there aren't any more exceptions, and the id is represented as a string and you either have another column to direct you as to whether the string is a GUId or an error so you can parse or report it appropriately, or you try and parse it and see if it works

*you could change your queries so they always have two columns- a string and a GUId and one is always null, and use the null to determine which type of thing you have

*you could always select both your errors and your ids and leverage the fact that sql server allows you to have multiple result sets open

But realistically I think I'd stop trying to return SQL errors as resultsets and just throw them as exceptions, and catch them in c#. Adopt a pattern of having a string that starts off blank, check for col1 and if it's not there append "col1 doesn't exist" to the string, check for col2 and maybe append "col2 doesn't exist".. then if the string isn't blank THROW it, otherwise return your resultset. C# will experience an exception with a useful error message (and you can provide a variable code if you want to handle it differently rather than just report to the user)


text:
Q: Query string is not coming in fiddler? In the fiddler i choose the inspectors>webforms to see the query string for the request. But instead it is coming blank. Do i need to enable anything in order to get that? Or any other way. Please help me out.

A: The session selected in your screenshot is a JavaScript file that is used by the page in question. Its URL does not contain a query string. Instead, you should select the Session that represents the web page that includes this JS file.


text:
Q: Can't print variable or assign variable in an if statement I'm learning python and am doing a simple calculator. I can get and store the numbers and the operator, but can't print out the result. I tried declaring answr outside of the if statement, printing it outside the if statement but it still doesn't work.
import operator

possibleOperators = [
    "Addition",
    "Subtraction",
    "Division",
    "Multiplication",
    ]

num1 = input("Input a number:\n")
if num1.isdigit():
    pass
else:
    print(f"\n'{num1}' is not a number")
    num1 = input("\nInput a number:\n")

op = input("\nPlease choose an operator:\nAddition\nSubtraction\nMultiplication\nDivision\n\n")
if op.title() not in possibleOperators:
    print(f"\n'{op}' is an invalid operator")
    op = input("\nPlease choose an operator:\nAddition\nSubtraction\nMultiplication\nDivision\n\n")

num2 = input("\nInput a second number:\n")
if num2.isdigit():
    pass
else:
    print(f"\n'{num2}' is not a number")
    num2 = input("\nInput a number:\n")

if op == possibleOperators[0]:
    answr = operator.add(num1, num2)
    print(answr)
elif op == possibleOperators[1]:
    answr = operator.sub(num1, num2)
    print(answr)
elif op == possibleOperators[2]:
    answr = operator.truediv(num1, num2)
    print(answr)
elif op == possibleOperators[3]:
    answr = operator.mul(num1, num2)
    print(answr)

Thanks in advance.

A: This problem is because you are not changing the num2 and num2 to int.
import operator

possibleOperators = [
    "Addition",
    "Subtraction",
    "Division",
    "Multiplication",
    ]

num1 = input("Input a number:\n")
if num1.isdigit():
    num1 = int(num1)
else:
    print(f"\n'{num1}' is not a number")
    num1 = int(input("\nInput a number:\n"))

op = input("\nPlease choose an operator:\nAddition\nSubtraction\nMultiplication\nDivision\n\n")
if op.title() not in possibleOperators:
    print(f"\n'{op}' is an invalid operator")
    op = input("\nPlease choose an operator:\nAddition\nSubtraction\nMultiplication\nDivision\n\n")

num2 = input("\nInput a second number:\n")
if num2.isdigit():
    num2 = int(num2)
else:
    print(f"\n'{num2}' is not a number")
    num2 = int(input("\nInput a number:\n"))

if op == possibleOperators[0]:
    answr = operator.add(num1, num2)
    print(answr)
elif op == possibleOperators[1]:
    answr = operator.sub(num1, num2)
    print(answr)
elif op == possibleOperators[2]:
    answr = operator.truediv(num1, num2)
    print(answr)
elif op == possibleOperators[3]:
    answr = operator.mul(num1, num2)
    print(answr)

You can also use this code.
import operator

possibleOperators = {
    "Addition":operator.add,
    "Subtraction":operator.sub,
    "Division":operator.truediv,
    "Multiplication":operator.mul
    }

while True:
    num1 = input("Input first number:\n")
    if num1.isdigit():
        num1 = int(num1)
        break
    print(f"{num} is not integer")

while True:
    op = input("\nPlease choose an operator:\nAddition\nSubtraction\nMultiplication\nDivision\n\n").title()
    if op in possibleOperators:
        break
    print(f"\n'{op}' is an invalid operator")

while True:
    num2 = input("Input second number:\n")
    if num2.isdigit():
        num2 = int(num2)
        break
    print(f"{num} is not integer")

ans = possibleOperators[op](num1,num2)
print(ans)

There is another way but it is complicated.
import operator

possibleOperators = {
    "Addition":operator.add,
    "Subtraction":operator.sub,
    "Division":operator.truediv,
    "Multiplication":operator.mul
    }

def func(string,isoperator=False):

    while True:
        result = input(string)
        if isoperator:
            if result.title() in possibleOperators:
                result = result.title()
                break
        else:
            if result.isdigit():
                result = int(result)
                break
        print(f"\n'{result}' is an invalid operator")

    return result

num1 = func(string="Input first number:\n")
op = func(string="\nPlease choose an operator:\nAddition\nSubtraction\nMultiplication\nDivision\n\n",isoperator=True)
num2 = func(string="Input second number:\n")
ans = possibleOperators[op](num1,num2)
print(f"\nThe answer is {ans}")


text:
Q: magento custom admin url redirects to homepage We just moved to another server, we are using Nginx as webservice
and we are using custom admin url for magento 1.9 like admin.domain.com
I can access magento admin through this url: https://admin.domain.com/index.php/admin
so is there anyway I can access it using this url only admin.domain.com
here it's my nginx config
server {
listen      888.888.888.888:80;
server_name domain.com *.domain.com www.domain.com;
root        /home/admin/web/domain.com/public_html;
index       index.php index.html index.htm;
access_log  /var/log/nginx/domains/domain.com.log combined;
access_log  /var/log/nginx/domains/domain.com.bytes bytes;
error_log   /var/log/nginx/domains/domain.com.error.log error;

location / {
    try_files $uri $uri/ @handler;
    expires 30d;
}
location /app/                       { deny all; }
location /includes/                  { deny all; }
location /lib/                       { deny all; }
location /media/downloadable/        { deny all; }
location /pkginfo/                   { deny all; }
location /report/config.xml          { deny all; }
location /var/                       { deny all; }

location /var/export/ {
    auth_basic              "Restricted";
    auth_basic_user_file    htpasswd;
    autoindex               on;
}
location  /. {
    return 404;
}

location @handler {
    rewrite / /index.php;
}

location ~ .php/ {
    rewrite ^(.*.php)/ $1 last;
}

location ~ \.php$ {
    try_files $uri =404;
    expires off;
    fastcgi_read_timeout 900s;
    fastcgi_index index.php;
    fastcgi_pass 127.0.0.1:9002;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include /etc/nginx/fastcgi_params;
}
rewrite ^/minify/([0-9]+)(/.*.(js|css))$ /lib/minify/m.php?f=$2&d=$1 last;
rewrite ^/skin/m/([0-9]+)(/.*.(js|css))$ /lib/minify/m.php?f=$2&d=$1 last;

location /lib/minify/ {
    allow all;
}
gzip on;
gzip_comp_level 6;
gzip_min_length  256;
gzip_proxied any;
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/vnd.ms-fontobject application/x-font-ttf font/opentype image/svg+xml image/x-icon;

error_page  403 /error/404.html;
error_page  404 /error/404.html;
error_page  500 502 503 504 /error/50x.html;

location /error/ {
    alias   /home/admin/web/domain.com/document_errors/;
}

location ~* "/\.(htaccess|htpasswd)$" {
    deny    all;
    return  404;
}

location /vstats/ {
    alias   /home/admin/web/domain.com/stats/;
    include /home/admin/web/domain.com/stats/auth.conf*;
}

include     /etc/nginx/conf.d/phpmyadmin.inc*;
include     /etc/nginx/conf.d/phppgadmin.inc*;
include     /etc/nginx/conf.d/webmail.inc*;

include     /home/admin/conf/web/nginx.domain.com.conf*;
}

A: Here is what you need to do:

*

*Create two exact servers

*

*Make sure that your files are sync'd (root
  /var/www/vhosts/example.com;)

*Your admin server will become your master and you can use Lsync to
  make sure they are always sync'd

*Domain admin.example.com will have one IP and your production server
  will have another Ip address

*You nginx config files can be identical.

*In Magento you will choose custom url for admin and point that URL
  To your new admin server

*Any files changes and uploads will go to Admin and will get sync'd
  to your slave server via the Lsync process.

*You can run Redis through ElastiCache or simply run it on the admin
  server

*You should use RDS for your database server
  Store sessions and cache in REDIS

*DO NOT SYNC YOUR VAR FOLDER


text:
Q: Saving a deleted row in a datatable to be deleted later in a database Sorry if the title is a bit vague, but I'm trying to think of a good way to do this right now. We are using .NET 3.5, by the way.
Example code:
if (ExistsInDB(dt.Rows.Find(rowID)))
     dt.Rows.Find(rowID).Delete();
else
     dt.Rows.Remove(dt.Rows.Find(rowID));

If the row exists in the database, mark it for deletion. Otherwise, remove it from the datatable.
Now, if I go ahead and change the DataRow's RowState property to Deleted via the DataRow.Delete() method, that works fine except I can't access information I would need to delete the row from the database when the user hits "Save Changes".
I don't want to store the rows in another datatable because I already have a lot of other data tables and I don't want to add more complexity to the object. I would put another column on the datatable with the name "ToBeDeleted" or something, but the tables get displayed in the program via a grid.
Essentially, I want to be able to flag a DataRow in a DataTable for deletion in the database later without resorting to throwing the DataRow into a List or adding another column to it. Is this possible?

A: You can get the deleted row's data by writing
row["ColumnName", DataRowVersion.Original]

A: Why not use DataAdapter for this? You can learn how to do this at http://msdn.microsoft.com/en-us/library/xzb1zw3x%28v=VS.90%29.aspx
Thanks,
Vamyip


text:
Q: how to calculate location different from distance i am new in gis. I am working in JavaScript.
suppose there is center latlong. another point is target(latlong) in n miters far from center.  how to calculate this location difference(center - latlong) from center and n in miter.
guys please help me.
lets consider earth is properly spherical.

A:   function distance(lat1, lon1, lat2, lon2) {
    var radius = 6371e3; // meters
    var dLon = gis.toRad(lon2 - lon1),
        lat1 = gis.toRad(lat1),
        lat2 = gis.toRad(lat2),
        distance = Math.acos(Math.sin(lat1) * Math.sin(lat2) +
            Math.cos(lat1) * Math.cos(lat2) * Math.cos(dLon)) * radius;
    return distance;
  }

above javascript function is for calculating distance,
function(lat, long, distance){
  //can i calculate lat_difference, long difference
}

A: here is your code:-
<script>

Math.radians = function(degrees) {
  return degrees * Math.PI / 180;
};

function calculateDistance(lat,lon,lat_center,lon_center){

var distance = ( 6371 * Math.acos( Math.cos( Math.radians(lat) ) * Math.cos( Math.radians( lat_center ) )
                        * Math.cos( Math.radians( lon_center ) - Math.radians(lon) ) + Math.sin( Math.radians(lat) ) * Math.sin(Math.radians(lat_center)) ) )*1000;
console.log(distance+"  meter");
return distance;
}

var lat = '38.898556';
var lon = '-77.037852';

var lat_center = '38.897147';
var lon_center = '-77.043934';

calculateDistance(lat,lon,lat_center,lon_center);//will return 549 meter

//for getting lat and lon from a distance from a given point

//lat1 = latitude of start point in degrees

//long1 = longitude of start point in degrees

//d = distance in KM

//angle = bearing in degrees

function get_gps_distance(lat1,long1,d,angle)
{
    //# Earth Radious in KM
    var R = 6378.14;

    //# Degree to Radian
    var latitude1 = lat1 * (Math.PI/180);
    var longitude1 = long1 * (Math.PI/180);
    brng = angle * (Math.PI/180);

    latitude2 = Math.asin(Math.sin(latitude1)*Math.cos(d/R) + Math.cos(latitude1)*Math.sin(d/R)*Math.cos(brng));
    longitude2 = longitude1 + Math.atan2(Math.sin(brng)*Math.sin(d/R)*Math.cos(latitude1),Math.cos(d/R)-Math.sin(latitude1)*Math.sin(latitude2));

   // # back to degrees
    latitude2 = latitude2 * (180/Math.PI);
    longitude2 = longitude2 * (180/Math.PI);

   // # 6 decimal for Leaflet and other system compatibility
   lat2 = latitude2;
   long2 =longitude2;
var tab = {};
   // Push in array and get back
   tab[0] = lat2;
   tab[1] = long2;
   return tab;
 }

 get_gps_distance('38.898556','-77.037852',.549,90);

</script>


text:
Q: Movement is dependent to frame-rate. How can i make it independent from frame-rate i am pretty new to coding. till now i searched lots of things yet i still couldn't solve my problem. I am trying to make a gameObject follow a line/graph. i tried to give him a negative-Y velocity and adding small numbers(something like; update{mybody.velocity += 0.005}) each update to make it move. but i encountered a problem which is at low frame-rate my object is taking a super wide path and at higher frame-rate it take super tight path. how can i make my movement independent.
private float curve = 0;
private float curvemax = 2.3f;
[SerializeField]
private float curveupdate = 0.05f;
if (tracking.found && !hareketeBaşlandı)
        {
            curve = -(curvemax);
            triggered1 = true;
            hareketeBaşlandı = true;
            print(curve);

        }
        if (transform.position.y != y1-curvemax && tracking.found)
        {
            curve += curveupdate;

            print(curve+"Curving");

        }

        if (curve >= (curvemax))
        {

            curve = 0;
            y2 = transform.position.y;
            transform.position = new Vector3(transform.position.x, y1, transform.position.z);
            tracking.found = false;
            tracking.shouldsearch = false;
            StartCoroutine("trackCD");
            print("track off");
            myBody.velocity = new Vector2(myBody.velocity.x, curve);
            hareketeBaşlandı = false;

        }

A: Note that using DateTime.Now and TimeSpan calculations as in this answer are quite expensive ... especially if you use it every frame just to calculate a delta in seconds.
This is actually exactly what Unity already provides in Time.deltaTime the time in seconds passed since last few was rendered .. so why calculate it complicated if we already know the value ;)
curve += curveupdate * Time.deltaTime;

In simple words multiplication by Time.deltaTime converts any value from "value per frame" into a frame-rate independent "value per second"

A: Instead of thinking about "rate of change," you must think about "rate of change per unit of time".
For example, you seem to be updating curve based on curveupdate = 0.05f;, which has a rate of change of 0.05f. You need to be thinking about how much rate of change per second. Assuming you currently get 0.05f change per frame, and let's say 10 frames per second, that means your rate of change per second is 0.5f (ten times higher) per second.
You then apply this amount multiplied by the number of seconds elapsed. Here's how to do it.
First when you kick off the animation, you need to remember when it started:
var lastUpdateTime = DateTime.Now;

Then change this:
curve += curveupdate;

To this:
DateTime currentTime = DateTime.Now;
float secondsElapsed = (float)(currentTime - lastUpdateTime).TotalMilliseconds / 1000F;
curve += (curveupdate * secondsElaped);
lastUpdateTime = currentTime;

This way, the amount of change scales depending on how much time has passed. If no time has passed, it will scale all the way down to 0, and if hours have passed, it will end up very very large. To an end user, the rate of change should seem consistent over time as a result.


text:
Q: converting files with FFMPEG ... NO MOOV ATOM at the end of the file I'm doing the following:

*

*I use FFMPEG into a Delphi XE2 program to convert any file that I receive into a mp4 file.

*I also use qr-faststart to move the atom to the begin of the file after converting.

The problem is after the conversion of some files (not always) the qr-faststart give the following error:

*

*"encountered non-QT top-level atom (is this a QuickTime file?)"

*"last atom in the file vas not a moov atom"

The command line for FFMPEG is : -i "sourceFile" -sameq "destinationFile"
The command line for qt-faststart is "sourceFile" "destFile"
Here is the full code of both function:
function TfrmMain.ConvertFile(aVideoFile: String; var aNewFile: String): Boolean;
var SEInfo: TShellExecuteInfo;
    ExitCode: DWORD;
    ExecuteFile, ParamString, StartInString: string;
    tmpVideoFile : String;
    logCommand   : String;
begin
  logMain.WriteFeedBackMessage(Format('enter ConvertFile %S ...', [aVideoFile]), '', EVENTLOG_INFORMATION_TYPE, False);
  Result := False;
  StartInString := edConverterPath.Text;
  tmpVideoFile  := ExtractFileName(aVideoFile);
  aNewFile      := ChangeFileExt(tmpVideoFile, '.mp4');
  if tmpVideoFile = aNewFile then begin
    logMain.WriteFeedBackMessage('the file is already converted ...', '', EVENTLOG_INFORMATION_TYPE, False);
    if OptimizeFastStart(aVideoFile) then begin
      Result := True;
    end;
    Exit;
  end;
  aNewFile := ExtractFilePath(aVideoFile) + aNewFile;
  if FileExists(aNewFile) then begin
    DeleteFile(aNewFile);
  end;
  logCommand := '';
  if ckLog.Checked then begin
    logCommand := ' -loglevel verbose -report';
  end;
  ParamString := '-i "' + aVideoFile + '" -sameq "' + aNewFile + '" ' + logCommand;
  logMain.WriteFeedBackMessage(Format('ParamString %S', [ParamString]), '', EVENTLOG_INFORMATION_TYPE, False);
  ExecuteFile := IncludeTrailingBackslash(StartInString) + 'ffmpeg.exe';
  if FileExists(ExecuteFile) then begin
    FillChar(SEInfo, SizeOf(SEInfo), 0) ;
    SEInfo.cbSize := SizeOf(TShellExecuteInfo) ;
    with SEInfo do begin
      fMask := SEE_MASK_NOCLOSEPROCESS;
      Wnd := Application.Handle;
      lpFile := PChar(ExecuteFile) ;
      //ParamString can contain the application parameters.
      lpParameters := PChar(ParamString) ;
      //  StartInString specifies the  name of the working directory. If ommited, the current directory is used.
      lpDirectory := PChar(StartInString) ;
      nShow := SW_SHOWNORMAL;
    end;
    if ShellExecuteEx(@SEInfo) then begin
      repeat
        Application.ProcessMessages;
        GetExitCodeProcess(SEInfo.hProcess, ExitCode) ;
      until (ExitCode <> STILL_ACTIVE) or Application.Terminated;
    end;
    if FileExists(aNewFile) then begin
      logMain.WriteFeedBackMessage(Format('Converting Video %S succesfull!', [aVideoFile]), Format('File %S was created.', [aNewFile]), EVENTLOG_INFORMATION_TYPE, True, False, False);
      if OptimizeFastStart(aNewFile) then begin
        Result := True;
      end;
    end;
  end else begin
    logMain.WriteFeedBackMessage(Format('File %S does not exist on the server!', [ExecuteFile]), 'The converter cannot be located on the disk!' + #13#10 + ExecuteFile, EVENTLOG_ERROR_TYPE, True, False, False);
  end;
end;

the fast start is here
function TfrmMain.OptimizeFastStart(aVideoFile: String): Boolean;
var SEInfo: TShellExecuteInfo;
    ExitCode: DWORD;
    ExecuteFile, ParamString, StartInString: string;
    strVideoFile : String;
    newVideoFile : String;
    startCommand : String;
begin
  // you need fast start utility
  logMain.WriteFeedBackMessage(Format('enter OptimizeFastStart %S ...', [aVideoFile]), '', EVENTLOG_INFORMATION_TYPE, False);
  Result := False;
  StartInString := edConverterPath.Text;
  strVideoFile  := ExtractFileName(aVideoFile);
  newVideoFile  := 'TMP_' + strVideoFile;
  if strVideoFile = aVideoFile then begin
    strVideoFile  := StartInString + strVideoFile;
    newVideoFile  := StartInString + newVideoFile;
  end;
  if not FileExists(strVideoFile) then begin
    logMain.WriteFeedBackMessage(Format('file %S dont exist...', [strVideoFile]), '', EVENTLOG_INFORMATION_TYPE, False);
    Exit;
  end;
  if FileExists(newVideoFile) then begin
    DeleteFile(newVideoFile);
  end;

  ParamString := Format('"%S" "%S"', [strVideoFile, newVideoFile]);
  ExecuteFile := IncludeTrailingBackslash(StartInString) + 'qt-faststart.exe';
  if FileExists(ExecuteFile) then begin
    logMain.WriteFeedBackMessage(Format('source %S destination %S', [strVideoFile, newVideoFile]), '', EVENTLOG_INFORMATION_TYPE, False);
    FillChar(SEInfo, SizeOf(SEInfo), 0) ;
    SEInfo.cbSize := SizeOf(TShellExecuteInfo);
    with SEInfo do begin
      fMask := SEE_MASK_NOCLOSEPROCESS;
      Wnd := Application.Handle;
      lpFile := PChar(ExecuteFile) ;
      lpParameters := PChar(ParamString);
      lpDirectory  := PChar(StartInString);
      nShow        := SW_SHOWNORMAL;
    end;
    if ShellExecuteEx(@SEInfo) then begin
      repeat
        Application.ProcessMessages;
        GetExitCodeProcess(SEInfo.hProcess, ExitCode) ;
      until (ExitCode <> STILL_ACTIVE) or Application.Terminated;
    end;
    logMain.WriteFeedBackMessage(Format('after file executed...', [strVideoFile]), '', EVENTLOG_INFORMATION_TYPE, False);
    sleep(500);
    Application.ProcessMessages;
    if FileExists(newVideoFile) then begin
      DeleteFile(strVideoFile);
      Application.ProcessMessages;
      sleep(500);
      Application.ProcessMessages;
      logMain.WriteFeedBackMessage(Format('before rename file...', [strVideoFile]), '', EVENTLOG_INFORMATION_TYPE, False);
      if RenameFile(newVideoFile, strVideoFile) then begin
        logMain.WriteFeedBackMessage(Format('rename file OK...', [strVideoFile]), '', EVENTLOG_INFORMATION_TYPE, False);
        Result := True;
        logMain.WriteFeedBackMessage(Format('Processing Video %S for WEB succesfull!', [strVideoFile]), '', EVENTLOG_INFORMATION_TYPE, True);
      end;
    end else begin
      logMain.WriteFeedBackMessage(Format('file %S does not exist!...', [newVideoFile]), '', EVENTLOG_INFORMATION_TYPE, True);
    end;
  end else begin
    logMain.WriteFeedBackMessage('Cannot find the qt-faststart.exe converter on the disk!', ExecuteFile, EVENTLOG_ERROR_TYPE, True);
  end;
end;

Can anyone advice me how to fix this problem.

A: Remove -sameq option, It does not mean same quality. Also, what version of FFMpeg do you have? If you do not have the latest, update. That should fix your problem. Can you post your complete command line output?


text:
Q: Virtual development environment. Is it feasible? Found many similar questions, they mostly 2-3yo and software/hardware moved forward.
I develop with Microsoft technologies. Enviroment consist of IIS, SQL Server, Visual Studio 2010, etc, etc. I also develop for Android so I have JAVA, Android SDK, slow-starting emulators, USB debugging, etc.
Right now it's Wind7 but I may move to Windows 8 soon.
I keep all files on server, source code check ins, etc. However, just to restore my environment I need couple days.
Currently I have Lenovo W510 with i7-820 CPU, 10G RAM, SSD and this system does OK for development. Now it broke and I'm out of commission for 3 days until I get them to fix it. Rebuilding my setup on different hardware will take long too..
My questions is:
Can I have same level of performance on stronger desktop hardware running virtual? Ideally I want faster system. I work with XAML a lot and I'm not sure how this graphics stuff will work in virtual environment.
Anybody does similar development on virtual setup? Any suggestions? Gotchas?
Right now I'm thinking about something like this:

*

*Powerful desktop - like Xeon, quad-core, 16Gb and 2 SSD in RAID0 (Since I can take backups of image)

*Keep my laptop if I need to be mobile - just copy image over(I need to travel rarely so it's necessary to be mobile with my setup)

Will I get better system this way?
EDIT:
I do lot of XAML development, is that going to work?
From what I just found seems like it might be a problem...
Is WPF development feasible under VM?

A: If your ultimate goal is to reduce downtime by doing all of your development work in a virtual machine that's backed up and easily restored, go for it.  No matter what, you will experience some performance loss, but with today's hardware I haven't really had any issues.
We have the advantage of having an environment in which almost every server is virtualized, so the next thing I'm about to say is supported in our infrastructure, but may not be in yours:
We have our IT staff set up virtual development machines on our VM Hosts, and simply connect to them via RDP (Remote Desktop Protocol) from our workstations (when we're at work) our laptops (when on the road) and our home computers (when at home, and a late-night support call comes in).  If you have an environment where you can do so securely (including multi-factor authentication, encryption over the wire, and all other security concerns) that may be an option.
Another option may be to use a hosted PC.  Plenty of providers now offer virtual desktop hosting, which allows you the benefits I enjoy in my environment without having to deal with the overhead.  But it's not free.
I found a bunch of them by searching Google for "hosted windows desktops".
For me, personally, I've hosed up my development PC more times than I can count, but not at all in the last two years.  Over time, I've learned what types of things can hose it up. (3rd party installs, etc) and have adopted a policy of setting up and using a virtual PC to test anything risky.
I use my normal development PC for most things, and avoid risky behaviors, and reserve virtual machines for when I am about to do something risky.


text:
Q: Raw textures don't work at all! OpenGL Here is my load code:
GLuint Utils::loadTextureRAW(const char *filename, int width, int height) {
GLuint texture;
char *data;
fstream file(filename, ios::binary | ios::in);
if (!file.good())
    return 0;

// allocate buffer
data = static_cast<char*>(malloc(width * height * 4));

// read texture data
file.read(data, width * height * 4);

file.close();

int i;
for (i = 0; i < width * height * 4; ++i) {
    cout << static_cast<int>(data[i]) << "|";
}

// allocate a texture name
glGenTextures(1, &texture);

// select our current texture
glBindTexture(GL_TEXTURE_2D, texture);

// select modulate to mix texture with color for shading
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_DECAL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_DECAL);

// when texture area is small, bilinear filter the closest mipmap
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
// when texture area is large, bilinear filter the first mipmap
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

// texture should tile
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

// build our texture mipmaps
gluBuild2DMipmaps(GL_TEXTURE_2D, 4, width, height, GL_RGBA, GL_UNSIGNED_BYTE, data);

// free buffer
delete data;

return texture; }

Here is my using code:
int Object::redraw() {
const float sizex = 0.5f;
const float sizey = 0.5f;
const float sizez = 0.5f;

glTranslatef(-px, -py, -pz);

glMatrixMode(GL_MODELVIEW);
glEnable(GL_TEXTURE_2D);
glPushMatrix();

//поворачиваем будущий объект объект
//rotating next object
glRotatef(rx, 1.0, 0.0, 0.0);
glRotatef(ry, 0.0, 1.0, 0.0);
glRotatef(rz, 0.0, 0.0, 1.0);

//рисуем
//drawing
glBegin(GL_QUADS);
// FRONT
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-sizex, -sizey, sizez);

glTexCoord2f(sizex , 0.0f);
glVertex3f(sizex, -sizey, sizez);

glTexCoord2f(sizex, sizey);
glVertex3f(sizex, sizey, sizez);

glTexCoord2f(0.0f, sizey);
glVertex3f(-sizex, sizey, sizez);
// BACK
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-sizex, -sizey, -sizez);

glTexCoord2f(sizex, 0.0f);
glVertex3f(-sizex, sizey, -sizez);

glTexCoord2f(sizex, sizey);
glVertex3f(sizex, sizey, -sizez);

glTexCoord2f(0.0f, sizey);
glVertex3f(sizex, -sizey, -sizez);
// LEFT
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-sizex, -sizey, sizez);

glTexCoord2f(sizex, 0.0f);
glVertex3f(-sizex, sizey, sizez);

glTexCoord2f(sizex, sizey);
glVertex3f(-sizex, sizey, -sizez);

glTexCoord2f(0.0f, sizey);
glVertex3f(-sizex, -sizey, -sizez);
// RIGHT
glTexCoord2f(0.0f, 0.0f);
glVertex3f(sizex, -sizey, -sizez);

glTexCoord2f(sizex, 0.0f);
glVertex3f(sizex, sizey, -sizez);

glTexCoord2f(sizex, sizey);
glVertex3f(sizex, sizey, sizez);

glTexCoord2f(0.0f, sizey);
glVertex3f(sizex, -sizey, sizez);
// TOP
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-sizex, sizey, sizez);

glTexCoord2f(sizex, 0.0f);
glVertex3f(sizex, sizey, sizez);

glTexCoord2f(sizex, sizey);
glVertex3f(sizex, sizey, -sizez);

glTexCoord2f(0.0f, sizey);
glVertex3f(-sizex, sizey, -sizez);
// BOTTOM
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-sizex, -sizey, sizez);

glTexCoord2f(sizex, 0.0f);
glVertex3f(-sizex, -sizey, -sizez);

glTexCoord2f(sizex, sizey);
glVertex3f(sizex, -sizey, -sizez);

glTexCoord2f(0.0f, sizey);
glVertex3f(sizex, -sizey, sizez);

glEnd();
glPopMatrix();
glDisable(GL_TEXTURE_2D); }

Here is texture:
[encoded data, 8192 characters]

EDITED:
Detected one other problem - for (i = 0; i < width * height * 4; ++i) outputs this:
1|0|0|0|0|0|0|0|5|0|0|0|0|0|0|0|-128|63|59|20|1|0|0|0|64|9|-108|2|1|0|0|0|1|0|0|0|1|0|0|0|1|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|-64|27|-78|0|2|0|0|0|1|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|-128|63|0|0|-128|63|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|-98|70|41|-127|-1|127|0|0|99|-51|56|0|2|0|0|0|0|0|0|0|2|0|0|0|0|-16|117|0|1|0|0|0|0|0|0|0|0|0|0|0|-104|123|115|0|1|0|0|0|0|-16|117|0|1|0|0|0|0|0|0|0|0|0|0|0|64|0|-97|65|0|0|0|0|64|7|-86|34|0|0|0|0|-80|-15|-65|95|-1|127|0|0|-128|117|9|0|2|0|0|0|0|0|0|0|0|0|0|0|-80|52|-108|2|1|0|0|0|0|0|0|0|0|0|0|0|-128|-14|-65|95|-1|127|0|0|-32|-15|-65|95|-1|127|0|0|0|0|0|0|0|0|0|0|32|0|0|0|0|0|0|0|32|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|64|7|0|0|0|0|0|0|-96|110|118|0|1|0|0|0|64|7|0|0|0|0|0|0|-96|110|118|0|1|0|0|0|32|0|0|0|0|0|0|0|80|-13|-65|95|-1|127|0|0|-128|47|8|0|2|0|0|0|-32|-15|-65|95|-1|127|0|0|32|0|0|0|0|0|0|0|-128|-14|-65|95|-1|127|0|0|32|-12|-65|95|-1|127|0|0|64|7|-86|34|0|0|0|0|0|0|0|0|0|0|0|0|-16|28|-108|2|1|0|0|0|2|2|-17|-66|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|3|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|1|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|96|0|-97|65|0|0|0|0|0|0|0|0|42|0|0|0|-80|52|-108|2|1|0|0|0|-80|-10|-65|95|0|1|0|0|64|0|0|0|1|0|0|0|-64|45|-63|95|-1|127|0|0|-48|-13|-65|95|-1|127|0|0|3|0|0|0|-1|127|0|0|112|-12|-65|95|-1|127|0|0|73|86|-55|2|1|0|0|0|0|116|17|0|1|0|0|0|105|86|-55|2|1|0|0|0|-72|91|-55|2|1|0|0|0|48|-12|-65|95|-1|127|0|0|6|0|0|0|0|0|0|0|73|86|-55|2|1|0|0|0|-96|-12|-65|95|-1|127|0|0|16|0|0|0|-1|127|0|0|73|86|-55|2|1|0|0|0|5|0|0|0|0|0|0|0|-96|-10|-65|95|-1|127|0|0|64|-13|119|0|1|0|0|0|0|-120|-127|1|1|0|0|0|19|-74|36|92|32|-66|35|74|-96|110|118|0|1|0|0|0|45|0|0|0|0|0|0|0|-112|-11|-65|95|-1|127|0|0|112|-9|-65|95|-1|127|0|0|-64|-43|29|112|-1|127|0|0|-80|-10|-65|95|-1|127|0|0|-128|-11|-65|95|-1|127|0|0|-41|10|45|-127|-1|127|0|0|-78|-10|-65|95|-1|127|0|0|-112|-15|119|0|42|0|0|0|8|2|-1|-1|1|0|0|0|-80|-10|-65|95|-1|127|0|0|44|0|0|0|1|0|0|0|-128|-15|119|0|1|0|0|0|-16|-11|-65|95|-1|127|0|0|0|48|111|0|1|0|0|0|0|-16|117|0|1|0|0|0|0|-16|117|0|1|0|0|0|-16|-11|-65|95|-1|127|0|0|96|120|-108|2|1|0|0|0|16|-12|-65|95|-1|127|0|0|48|-12|-65|95|-1|127|0|0|0|0|0|0|0|0|0|0|16|-128|-108|2|1|0|0|0|0|48|111|0|1|0|0|0|16|-114|114|0|1|0|0|0|64|-10|-65|95|-1|127|0|0|-19|111|8|0|2|0|0|0|0|0|0|0|0|0|0|0|4|0|0|0|0|0|1|0|0|0|0|0|0|0|0|0|-89|-85|-86|50|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|

But if I correctly understand half of it must be zeros and half must be 255. WTF or I'm doing something wrong?
EDITED:
Tried to do this:
data[0] = 0;
data[1] = 0;
data[2] = 0;
data[3] = 255;
data[4] = 0;
data[5] = 0;
data[6] = 0;
data[7] = 255;
data[8] = 0;
data[9] = 0;
data[10] = 0;
data[11] = 255;
data[12] = 0;
data[13] = 0;
data[14] = 0;
data[15] = 255;

And texture is all black(http://cl.ly/7KJd), changed zeros to 255 and texure is white. So the problem is in file loading!
************
PROBLEM WAS SOLVED!

A: In OpenGL, white textures show up when the texture is incomplete or in error.
Most of the time, it's related to missing mipmaps, but as you use gluBuild2DMipmaps it may not be directly related.
You should try to call glGetError to try to narrow down your problem : as mentionned in the comments, you make a lot of improper GL calls in the code you posted.


text:
Q: Basic jQuery AJAX performance Inquiry When doing ajax requests using jQuery's ajax() function I never use any parameters other than "data" in the success callback:
$.ajax({
    url: 'script.php',
    type: 'post',
    data: $(this).serialize(),
    dataType: 'json',
    success: function(data) {
        alert(data);
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.log(jqXHR);
    }
});

But I was wondering if keeping the other 2 parameters (textStatus, jqXHR) in that function will have any performance impact:
success: function(data, textStatus, jqXHR) {
    alert(data);
}

I am not doing anything with "textStatus" and "jqXHR", but if I kept them there will there be any performance decrease (even a little)?

A: Maybe a little bit, but nothing noticeable considering you're not referencing them - no memory lookups will have to be performed.
If you're doing millions of AJAX calls a second, you might see a delay, but how on Earth you can do a million AJAX requests a second I don't know.


text:
Q: How do I build and run api-platform image to a production docker container? I have followed the api-platform tutorial and successfully built and started the application using Docker on my localhost machine.
I have a production server running Ubuntu 16.04.5 LTS, and a newly installed  Docker version 18.06.1-ce.
How would I build this code on my local machine and run it on the Docker server?
I have also looked at the Deploying API Platform Applications documentation but I am not sure how to use this.
I am struggling to understand how to build api-platform from my localhost to the server

A: this is docker-compose.yml file try this please docker-compose up -d
version: '3.4'
services:
  php:
    image: ${CONTAINER_REGISTRY_BASE}/php
    build:
      context: ./api
      target: api_platform_php
      cache_from:
        - ${CONTAINER_REGISTRY_BASE}/php
        - ${CONTAINER_REGISTRY_BASE}/nginx
        - ${CONTAINER_REGISTRY_BASE}/varnish
    depends_on:
      - db
    # Comment out these volumes in production
    volumes:
      - ./api:/srv/api:rw,cached
      # If you develop on Linux, uncomment the following line to use a bind-mounted host directory instead
      # - ./api/var:/srv/api/var:rw

  api:
    image: ${CONTAINER_REGISTRY_BASE}/nginx
    build:
      context: ./api
      target: api_platform_nginx
      cache_from:
        - ${CONTAINER_REGISTRY_BASE}/php
        - ${CONTAINER_REGISTRY_BASE}/nginx
        - ${CONTAINER_REGISTRY_BASE}/varnish
    depends_on:
      - php
    # Comment out this volume in production
    volumes:
      - ./api/public:/srv/api/public:ro
    ports:
      - "8080:80"

  cache-proxy:
    image: ${CONTAINER_REGISTRY_BASE}/varnish
    build:
      context: ./api
      target: api_platform_varnish
      cache_from:
        - ${CONTAINER_REGISTRY_BASE}/php
        - ${CONTAINER_REGISTRY_BASE}/nginx
        - ${CONTAINER_REGISTRY_BASE}/varnish
    depends_on:
      - api
    volumes:
      - ./api/docker/varnish/conf:/usr/local/etc/varnish:ro
    tmpfs:
      - /usr/local/var/varnish:exec
    ports:
      - "8081:80"

  db:
    # In production, you may want to use a managed database service
    image: postgres:10-alpine
    environment:
      - POSTGRES_DB=api
      - POSTGRES_USER=api-platform
      # You should definitely change the password in production
      - POSTGRES_PASSWORD=!ChangeMe!
    volumes:
      - db-data:/var/lib/postgresql/data:rw
      # You may use a bind-mounted host directory instead, so that it is harder to accidentally remove the volume and lose all your data!
      # - ./docker/db/data:/var/lib/postgresql/data:rw
    ports:
      - "5432:5432"

  client:
    # Use a static website hosting service in production
    # See https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#deployment
    image: ${CONTAINER_REGISTRY_BASE}/client
    build:
      context: ./client
      cache_from:
        - ${CONTAINER_REGISTRY_BASE}/client
    env_file:
      - ./client/.env
    volumes:
      - ./client:/usr/src/client:rw,cached
      - /usr/src/client/node_modules
    ports:
      - "80:3000"

  admin:
    # Use a static website hosting service in production
    # See https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#deployment
    image: ${CONTAINER_REGISTRY_BASE}/admin
    build:
      context: ./admin
      cache_from:
        - ${CONTAINER_REGISTRY_BASE}/admin
    volumes:
      - ./admin:/usr/src/admin:rw,cached
      - /usr/src/admin/node_modules
    ports:
      - "81:3000"

  h2-proxy:
    # Don't use this proxy in prod
    build:
      context: ./h2-proxy
    depends_on:
      - client
      - admin
      - api
      - cache-proxy
    ports:
      - "443:443"
      - "444:444"
      - "8443:8443"
      - "8444:8444"

volumes:
  db-data: {}


text:
Q: Form fields not binding inside apex repeat I have a generic component that works for all objects. The object name is passed as a parameter to the component. I am iterating through a list to display a component for each object. Here is the code:
<apex:repeat value="{!objectNameList} var="obj">
    <c:SobjectComp objectName="{!obj}" />
<apex:repeat>

The component has a form that displays fields of the object that are included in the object's fieldset. But when I submit the form, the values are not binding.
However, the same code works without apex:repeat. The following works:
<c:SobjectComp objectName="Custom_Object1__c"/>
<c:SobjectComp objectName="Custom_Object2__c"/>
<c:SobjectComp objectName="Custom_Object3__c"/>...

The form values bind to controller when using the above code. It is the same component but does not work with apex:repeat.
Please help.


text: Q: Display Ubuntu terminal output I am writing a memoir in latex. I have lot of output from Ubuntu terminal and I have tried to put in verbatim, but this is really not pretty. I was wandering if there is a latex tip to put Linux terminal output in latex and make it pretty.


text:
Q: GIF image does not animate I am printing a .gif image through my printer, but it does not move like on my screen. it looks like I a jpeg format image.
What am I doing wrong?

A: I would suggest printing each individual frame of the animated GIF on a single piece of paper.
By flipping through them from the first page till the last, it would indeed appear like the animated GIF on your computer.

A: I'll make the assumption that this question is a joke.
You cannot print *.gif images in an animated fashion with a printer.


text:
Q: Reading array data from to element Alright so I am trying to achieve something but I am not sure how to do it. I am basically trying to read From-To array. Basically lets say that this is my array
$arr = array("a","b","c","d","e","f");

    foreach($arr as $a) {
        echo $a;
    }

I want to be able to read stuff from B to E. How do I achieve that?
Also I'd want to be able to reverse that, so for example I read from F to C (it would then show F,E,D,C)
I googled a bit but couldnt find any matching results for this.
EDIT: I am not trying to ask how to print all values from an array, I am asking how to reverse them, so I can for example read from 9th element to 1st element of the array

A: demo here
if you want to output the upper char use strtoupper() function and array_map() function.
<?php
$arr = array("a","b","c","d","e","f");
array_walk(array_slice($arr, 1, count($arr)-2), function($value){echo $value."\n";});
array_walk(array_slice(array_reverse($arr), 0, count($arr)-2), function($value){echo $value."\n";});


text:
Q: Create a temporary directory for multiple gradle tasks I am working with gradle in a windows environment. I wish for my gradle script to create a temporary directory, different tasks to perform operations on it in various orders, and then delete it upon completion (optional). How can I create this temporary dir in the gradle script?
My initial thought was Task.temporaryDir, however that directory only persists for the duration of the task.
Apologies if this is obvious, I am new to working on Windows and just picked up gradle yesterday.

A: If you need to create a temporary directory outside of project structure it can be done with adding:
def tempDir = File.createTempDir()
tempDir.deleteOnExit() // use with care, might be problematic with when daemon mode is used

e.g. somewhere at the beginning of the script.
Then the folder created can be used as an output directory elsewhere.

A: If you need some task output to persist beyond the execution of the task then best to create a subfolder in the project build directory.
task myTask << {
    file("${buildDir}/foo").mkdirs()
}


text:
Q: javascript setting attribute of prototype to attribute of object To begin with, I don't fully understand the prototypal structure of Javascript so this may not be possible.
If I have ...
var vector = function( x, y ) {
    this.x = x || 0;
    this.y = y || 0;
}

var obj = function() {
    this.position = new vector( 0, 0, 0 );
}

var cube = new obj();

... how can I add a property x to obj such that calling cube.x is equivalent to cube.position.x. I think it should be possible to make properties of each reference the same value, but I'm just not sure of the syntax. Something like obj.prototype.x = obj.position.x doesn't work because obj.position is undefined.
I would like the following behaviour to be possible
alert(cube.position.x); // 0
alert(cube.x); // 0

cube.position.x = 2;
alert(cube.position.x); // 2
alert(cube.x); // 2

cube.x = 4;
alert(cube.position.x); // 4
alert(cube.x); // 4

Is this possible?
I should probably mention that I'm working with Three.js so rewriting the objects isn't an option, just adding to them and their prototypes.

A: To get cube.x to return whatever cube.position.x contains, you'd need to define accessors and mutators for obj.prototype.x. Accessors and mutators are a relatively newer feature in JavaScript, and are not supported in most versions of IE.
var vector = function( x, y ) {
    this.x = x || 0;
    this.y = y || 0;
}

var obj = function() {
    this.position = new vector( 0, 0, 0 );
}
obj.prototype = {
    ...your prorotype methods here...
};
Object.defineProperty(obj.prototype, 'x', {
    get: function () {
        return this.position.x;
    },
    set: function (val) {
        this.position.x = val;
    }
});

//alternatively:
obj.prototype = {
    get x() {
        return this.position.x;
    },
    set x(val) {
        this.position.x = val;
    }
};

var cube = new obj();
cube.x; //0
cube.x = 10;
cube.position.x; //10


text:
Q: $R = \mathbb{Z}/m\mathbb{Z}$, and consider $R^n$ for any $n,m$. For what values of $m$ is $R$ a semisimple $R$-module? Let $R = \mathbb{Z}/m\mathbb{Z}$, and consider $R^n$ for any $n,m$. For what values of $m$ is $R$ a semisimple $R$-module?
$\textbf{Context:}$ I am interested for what $m$ would the image of an endomorphism of $R^n$ be a direct summand.

A: $R=\mathbb Z/m\mathbb Z$ is a semisimple $R$ module iff $m$ is a (nonzero) square-free integer.  This is well-known because a commutative semisimple ring cannot have nonzero nilpotents, and this is exactly the condition to ensure that.
$R^n$ is a semisimple $R$ module iff $R$ is.
So the answer to your 'context' question is that if $m$ is squarefree, the image will always be a summand, but if it is not squarefree, it will only sometimes be a summand.


text:
Q: making sure jquery .load content is finished loading i'm loading some html content dynamically through jquery .load.  I'm having a hard time making sure ALL of the content is loaded.  The dynamic loading of the text seems to work fine, it's the loading of the html content that I'm having trouble with.
this is the page, if you click on the blue shield, bottom left image you can see it not animating down to the full height http://www.klossal.com/ but if you look here you can see how it's suppose to load and it works cause it's not dynamically loaded http://www.klossal.com/index_backup.html
This is the part of the script that loads the html
$('#images').load(id +".html", function() {

console.log('Loaded'); //Testing Purposes Only
IMG=1; // Loaded
animate_section(); // Attempt Animation

});

and this is the script in total:
var a1, a2, a3, a4, IMG;

$(".thumb_container_site").click(function() {

a1=0; //Reset the Loading Variables
a2=0;
a3=0;
a4=0;
IMG=0;

var id = $(this).attr('id');

$('#images').load(id +".html", function() {

console.log('Loaded'); //Testing Purposes Only
IMG=1; // Loaded
animate_section(); // Attempt Animation

});

$("#info_header").load(id +"_header.txt", function() {

console.log('Loaded'); //Testing Purposes Only
a1=1; // Loaded
animate_section(); // Attempt Animation

});

$("#content_1").load(id +"_1.txt", function() {

console.log('Loaded'); //Testing Purposes Only
a2=1; // Loaded
animate_section(); // Attempt Animation

});

$("#content_2").load(id +"_2.txt", function() {

console.log('Loaded'); //Testing Purposes Only
a3=1; // Loaded
animate_section(); // Attempt Animation

});

$("#content_3").load(id +"_3.txt", function() {

console.log('Loaded'); //Testing Purposes Only
a4=1; // Loaded
animate_section(); // Attempt Animation

});

});

any help I can get on this would be great, thank you.
here is the animation function
function animate_section() {

if((a1===1) && (a2===1) && (a3===1) && (a4===1) && (IMG===1)){ //Animate if all thre divs are loaded

$("#top_section").animate({
    height: $("#load_container").outerHeight(true) + 30
}, 300);
$("#grid").animate({
    marginTop: $("#load_container").outerHeight(true) + 300,
    paddingBottom: 300
}, 300);
}
}

there is also a second function for a slightly different loading structure, but I don't think this should break anything.  This function loads the top left thumbnail content, and that loads totally right,
$(".thumb_container_img").click(function() {

a1=0; //Reset the Loading Variables
a2=0;
a3=0;
a4=0;
IMG=0;

var id = $(this).attr('id');

$('#images').empty();

$("<img>", { src: 'http://www.klossal.com/' + id + ".png" }).load(function () {
$(this).prependTo("#images"), IMG=1 });

$("#info_header").load(id +"_header.txt", function() {

console.log('Loaded'); //Testing Purposes Only
a1=1; // Loaded
animate_section(); // Attempt Animation

});

$("#content_1").load(id +"_1.txt", function() {

console.log('Loaded'); //Testing Purposes Only
a2=1; // Loaded
animate_section(); // Attempt Animation

});

$("#content_2").load(id +"_2.txt", function() {

console.log('Loaded'); //Testing Purposes Only
a3=1; // Loaded
animate_section(); // Attempt Animation

});

$("#content_3").load(id +"_3.txt", function() {

console.log('Loaded'); //Testing Purposes Only
a4=1; // Loaded
animate_section(); // Attempt Animation

});

});

A: Looks to me like what is happening is that your load callback is being triggered when the text file is loaded, not when the image itself is loaded. Therefore, your call to outerHeight() is getting the incorrect value because the container element has a height equal to the loaded portion of the image at the time. You should investigate putting an
$('#load_container img').on('load', function(){
   //callback or emit an event that will listen and then respond with your callback
});