text:
Q: Fix mouse direction of a draggable div inside a rotated parent Please take a look at my jsfiddle to understand my problem:
The yellow is the parent div that you can rotate by using the red circle, it's also draggable, inside this div there is another div with a black border that we could consider as a containment to the blue circle.
The blue circle is draggable within the containment boundaries, the y coordinate only is required nothing more, the problem happens if you rotate the yellow div ex; 90 degrees or more, the mouse coordinates are not matching the expected dragging position, I've tried to solve the issue by using trigonometry and reversing the axis but it in-vain, I hope someone could solve this and leave a jsfiddle for a working sample is highly appreciated. 'please don't direct me to other posts as I think I have read everything related to this issue'
HTML

CSS
#container{width:100px;
       height:140px;
       background:#FFEB3B;
       position:absolute;
       top:50%;
       bottom:50%;
       margin-top:-70px;
       margin-right:-50px}

.ui-rotatable-handle {
        height: 30px;
        width: 30px;
        cursor: pointer;
        background:#ff0000;
        border-radius:50%;
        right: -15px;
        bottom: -15px;
        position:absolute;
        z-index:1}

#containment{width:30px;
         height:190px;
         position:absolute;
         bottom:70px;
         left:35px;
         border:solid 1px #000}

#circle{width:30px;
         height:30px;
         position:absolute;
         top:0;
         left:0;
         border-radius:50%;
         background:#3F51B5}

JavaScript
$(function(){
            $('#container').draggable().rotatable();
            $('#circle').draggable({containment: $('#containment')
            });
          });

A: Only way I found it's to add "fake" rectangle and show it on needed degrees. I added only 1 fake rectangle for 45deg+ but you can also add other 2 by same logic for 90deg+ and 115deg+. See solution there.
HTML

CSS
#container {
  width: 100px;
  height: 140px;
  background: #FFEB3B;
  position: absolute;
  top: 50%;
  bottom: 50%;
  margin-top: -70px;
  margin-right: -50px;
}

.ui-rotatable-handle {
  height: 30px;
  width: 30px;
  cursor: pointer;
  background: #ff0000;
  border-radius: 50%;
  right: -15px;
  bottom: -15px;
  position: absolute;
  z-index: 1;
}

#containment,
#containment2 {
  width: 30px;
  height: 190px;
  position: absolute;
  bottom: 70px;
  left: 35px;
  border: solid 1px #000
}

#containment2 {
  width: 190px;
  height: 30px;
  left: 51px;
  bottom: 54px;
  transform: rotate(-90deg);
  border: solid 1px green;
  transform-origin: left;
  display: none;
}

.circle {
  width: 30px;
  height: 30px;
  position: absolute;
  top: 0;
  left: 0;
  border-radius: 50%;
  background: #3F51B5;
  z-index: 10;
}

#circle2 {
  left: calc(100% - 30px);
  display: none;
}

#wrapper {
  width: 100%;
  height: 100%;
  outline: 1px solid red;
}

JavaScript
$(function() {
  var Pi = 3.14;
  $('#container').draggable({}).rotatable({
    rotate: function(event, ui) {
      let deg = ui.angle.current * 180 / Pi;
      $("#containment").show();
      $("#containment2").hide();
      $("#circle").show();
      $("#circle2").hide();
      if (deg > 45) {
        $("#containment").hide();
        $("#containment2").show();
        $("#circle").hide();
        $("#circle2").show();
      }
    },
  });

  $('#circle').draggable({
    stop: function(event, ui) {
        console.log(ui.position.top);
        $("#circle2").css("inset", ui.position.left + "px auto auto " + (160 - ui.position.top) + "px");
    },
    containment: $('#containment')
  });
  $('#circle2').draggable({
    stop: function(event, ui) {
        $("#circle").css("inset", 160 - ui.position.left + "px auto auto " + ui.position.top + "px");
    },
    containment: $('#containment2')
  });

});

A: I had some similar issues with JQuery, inside an rtl application. the reason was that since the orientation of the layout uses left css positioning - the right was missing and the calculations went wrong.
Adding them while creating the element solved it.


text:
Q: Add context menu items to specific file extensions I think the title says all I want: I want to add context menu items for a specific file type like the yellow marked ones in the screenshot. Which registry changes do I have to make? In my case I want to assign ir.exe to .rb files.

A: There is a great answer on Stackoverflow:

1) Identify the file type (ProgID) for .jpg files
This can be done by checking the default value of
  HKEY_CLASSES_ROOT\.jpg. It could be anything based on what you've
  installed, but for the purposes of this example, we'll call it
  jpegfile, a common default.
2) Set the context menu item (verb) properties for that file type
You can set per-user context menu items in
  HKEY_CURRENT_USER\Software\Classes\jpegfile\shell. This key has a
  list of verbs for the file type. There is a similar key in
  HKEY_LOCAL_MACHINE\Software\Classes\jpegfile\shell, and these are
  the system defaults for the file type. You can put a verb key there
  too, but if the same key exists in HKCU, it will be overridden, so be
  advised.
3) Set the command value
The bare minimum key value that needs to be set to get it to work is
  the default value of the command subkey. You need to set that with
  the path to your application, like so:
  HKEY_CURRENT_USER\Software\Classes\jpegfile\shell\open_with_myapp\command would be set to "c:\path\to\myapp.exe" "%1". Now a context menu for
  .jpg files will have a "open_with_myapp" item which will launch your
  app when clicked, and pass the file name of the selected file as a
  parameter. Of course, how your application processes parameters is up
  to you, so you'd need to set the parameter string to something your
  app can process.
4) Set other verb properties
I'd imagine you're probably going to want the context menu item to
  read something a little more friendly than the key name. You can have
  the context menu display whatever label you want for your item by
  setting the default value of that key (open_with_myapp).
That's your basic overview. Definitely check out my answer to this
  question about associating a file, which has a similar answer:

*

*Create registry entry to associate file extension with application in C++

A: There's a freeware (portable) which does this registry edit, and that function at least seems to work on Windows 10:
https://defaultprogramseditor.com/

redpajama_set_name: RedPajamaStackExchange


text:
Q: segmentation fault when using su or sudo example of the problem:
$ su
Segmentation fault
$ sudo ls
Segmentation fault

I tried to compile sqlite3 from source earlier. I don't know what libraries it installed. This may be the reason why this is happening.
I tried strace su and it ends with the following:
...
fstat64(6, {st_mode=S_IFREG|0644, st_size=17964, ...}) = 0
mmap2(NULL, 20788, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 6, 0) = 0xb7295000
mmap2(0xb7299000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 6, 0x3) = 0xb7299000
close(6)                                = 0
mprotect(0xb7299000, 4096, PROT_READ)   = 0
mprotect(0xb72f9000, 4096, PROT_READ)   = 0
set_tid_address(0xb758a728)             = 11144
--- SIGSEGV (Segmentation fault) @ 0 (0) ---
+++ killed by SIGSEGV (core dumped) +++
Segmentation fault (core dumped)

When I try gdb su and try to run, it gives me Cannot find new threads: generic error. I looked online for a solution to the problem, encountered this thread, and then tried running LD_PRELOAD=/lib/i386-linux-gnu/libpthread.so.0 gdb su (as suggested in the thread). When I then tried to run it again, it gave me the same error.
Based on the strace, I think there is some problem with how it's threading, but I have no idea how to fix this. Is there some way to reinstall the basic bash utilities?
Here's more information about my system:
$ uname -a
myhost 3.2.0-37-generic-pae #58-Ubuntu SMP Thu Jan 24 15:51:02 UTC 2013 i686 i686 i386 GNU/Linux

(I'm pretty sure the hardware is 64bit)

A: Use aptdcon, which communicates with apt-daemon via dbus so it doesn't need su or sudo, to reinstall the damaged packages. Probably your best chance is to reinstall ALL the packages.
First, make sure there is no broken install pending a fix:
aptdcon --fix-install

Also make sure there is free space available on your disk:
df -h

Then, get your currently installed package list:
echo \"$(dpkg --get-selections | grep install | cut -f 1)\"

Save that for later, on a text editor of something. Then, call aptdcon like this, using the full package list:
aptdcon --reinstall "package1 package2 package3..."

I'm telling you this way because aptdcon won't be able to reinstall some packages for various reasons, so you will have to strip them out if aptdcon cries about that, and try again, probably more than once.

A: I saw this problem, but the root cause was slightly different. I had been testing Kerberos and had something misconfigured in my /etc/krb5.conf. I discovered via strace that sudo was segfaulting shortly after reading that file so I figured there was an issue with my configuration file. I didn't track down a specific variable but one thing that stood out was that I had the default_domain variable empty in the krb5.conf like so
[libdefaults]
   default_realm =

This may have cause some sloppy code in sudo to make a zero length string and mishandle it somehow causing the SIGSEGV. I didn't try to debug it any further since this wasn't the correct setting. I simply deleted my /etc/krb5.conf.

A: There is a chance that a pam module from samba is causing this.
If that's the case, then this should fix it:

*

*Reboot the machine and choose to boot to the recovery mode. If you can't see the recovery mode, then you first need to choose the 'Advanced options for' option.

*Choose "drop into root shell" from the recovery menu

*Execute the command: dpkg --purge libpam-smbpass

*Execute the command: dpkg --purge libpam-winbind

Then you should be able to use 'su' and 'sudo' again.
You then may want or need to do a

*

*sudo apt-get -f install

to help fix any remaining broken packages.
If you need the libpam-smbpass and/or libpam-winbind package, or have a broken 'samba' package, you may find that you have to delete or rename /var/lib/samba/secrets.tdb:

*

*sudo mv /var/lib/samba/secrets.tdb /var/lib/samba/secrets.tdb.old

Source/Related: https://bugs.launchpad.net/ubuntu/+source/samba/+bug/260687

A: If you have the problem as the OP encountered, you cannot do what Jorge Suárez de Lis suggested, as it will throw a dependencies error.
So,
aptdcon --reinstall "libsqlite3-0"

and
aptdcon --install "libsqlite3-0"

returns the error message:
ERROR: org.debian.apt.TransactionFailed - error-cache-broken: The following packages have unmet dependencies:
While doing THIS:
aptdcon --fix-depends

will fix it, and su and sudo will work again.


text:
Q: Sort Excel table (ListObject) on protected sheet using Excel Interop Sorting Excel tables (ListObjects) is not allowed on protected sheets. You'll see  the following error message:

I spent weeks looking for a solution with no success.  Everything out there is outdated with Excel 2007 code samples. There are no tutorials or guides on how circumvent this limitation.
Here's how I was able to finally overcome..

A: There is no trappable event when sorting from the Excel's filter drop-down menu of a table.  You can, however, trap the events when an ascending, descending or sort dialog commands are invoked from the Ribbon's Home and Data tabs.
Using Excel 2016 Interop (document-level customization), Visual Studio 2015 and C#:

*

*Right-click on your project -> Add -> New Item -> Ribbon (XML)

*On your Ribbon.xml:

<?xml version="1.0" encoding="UTF-8"?>
<customUI xmlns="http://schemas.microsoft.com/office/2009/07/customui" onLoad="Ribbon_Load">
  <commands>
    <command idMso="SortAscendingExcel" onAction="SortNoAlerts" />
    <command idMso="SortDescendingExcel" onAction="SortNoAlerts" />
    <command idMso="SortCustomExcel" onAction="SortDialogNoAlerts" /><!--TabHome-->
    <command idMso="SortDialog" onAction="SortDialogNoAlerts" /><!--TabData-->
  </commands>
</customUI>

Next, add the events' callback functions. SortNoAlerts unprotects the sheet for ascending / descending button clicks. But if the user chooses 'Custom Sort' (Home tab) - or - 'Sort' (Data tab), a dialog will appear, sure it will unprotect the sheet and protect it right back if OK is pressed, but if the user Cancels, ThisWorkbook_SheetCalculate will never trigger leaving the sheet unprotected.  So we add the SortDialogNoAlerts which unprotects the sheet but also starts a timer that uses p/Invoke FindWindow to look for the Sort dialog window.  When the Window is no longer found, it protects it if not already protected.

*On your Ribbon.cs callbacks:

    public void SortNoAlerts(Office.IRibbonControl control, ref bool cancelDefault)
    {
        Excel.Worksheet ws = null;
        try
        {
            ws = (Excel.Worksheet)Globals.ThisWorkbook.ActiveSheet;
            ws.Unprotect("your password");
            cancelDefault = false;
        }
        catch (Exception) { }
        finally
        {
            if (ws != null) Marshal.ReleaseComObject(ws); ws = null;
        }
    }

    public void SortDialogNoAlerts(Office.IRibbonControl control, ref bool cancelDefault)
    {
        Excel.Worksheet ws = null;
        try
        {
            ws = (Excel.Worksheet)Globals.ThisWorkbook.ActiveSheet;
            ws.Unprotect("your password");
            Globals.ThisWorkbook._myActionPane.tmrWaitSortWinClose.Enabled = true;
            cancelDefault = false;
        }
        catch (Exception) {
            Globals.ThisWorkbook._myActionPane.tmrWaitSortWinClose.Enabled = false;
        }
        finally
        {
            if (ws != null) Marshal.ReleaseComObject(ws); ws = null;
        }
    }

*On ThisWorkbook.cs -> InternalStartup() add this:

this.SheetCalculate += new Excel.WorkbookEvents_SheetCalculateEventHandler(ThisWorkbook_SheetCalculate);

*On ThisWorkbook.cs -> add this:

public bool sortDialogVisible;

private void ThisWorkbook_SheetCalculate(object sh)
{
  Excel.Worksheet ws = (Excel.Worksheet)sh;
  ws.EnableOutlining = true;
  ws.Protect("your password", true, Type.Missing, Type.Missing, true, true, true, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, true, true, true, Type.Missing);
  Marshal.ReleaseComObject(ws); ws = null;
}

*Add a timer named tmrWaitSortWinClose and set Interval = 750:

private void tmrWaitSortWinClose_Tick(object sender, EventArgs e)
{
    Globals.ThisWorkbook.sortDialogVisible = Native.FindWindow("NUIDialog", "Sort") == IntPtr.Zero;

    if (Globals.ThisWorkbook.sortDialogVisible)
    {
        Excel.Worksheet ws = null;
        try
        {
            ws = (Excel.Worksheet)Globals.ThisWorkbook.ActiveSheet;

            if (!ws.ProtectContents)
            {
               ws.Protect("your password", true, Type.Missing, Type.Missing, true, true, true, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, true, true, true, Type.Missing);
            }
            tmrWaitSortWinClose.Enabled = false;
        }
        catch (Exception) { tmrWaitSortWinClose.Enabled = false; }
        finally
        {
            if (ws != null) Marshal.ReleaseComObject(ws); ws = null;
        }
    }
}

*Add a class named Native.cs:

public class Native
{
    [DllImport("user32.dll", SetLastError = true)]
    public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
}

That will allow sorting tables on protected sheets.  Don't be confused, the AllowSort option of worksheet.Protect() it's only for the cells of the sheet that are not part of a table (ListObject).


text:
Q: MVC Automapper update i tried to update my database table some fields
[HttpPost]
    [ValidateAntiForgeryToken]

    public ActionResult Edit(MemberTasks membertaskdetails)
    {
        if (ModelState.IsValid)
        {

            MemberTasks Mtasks = db.MemberTask.Find(membertaskdetails.id);
            Mtasks.Taskid = membertaskdetails.Taskid;
            Mtasks.status = membertaskdetails.status;
            AutoMapper.Mapper.Map(membertaskdetails,Mtasks);
           db.SaveChanges();
           return RedirectToAction("Index");
        }
        return View(membertaskdetails);
    }

ViewModel
 public class MemberTasks
{
    [Key]
    [Display(Name = "ID")]
    public int id { get; set; }
    [Display(Name = "Task ID")]
    public int Taskid { get; set; }
    [Display(Name = "Status")]
    public int status { get; set; }
    [Display(Name = "Created By")]
    public string createdby { get; set; }
    [Display(Name = "Team Lead")]
    public string TeamLead { get; set; }
    [Display(Name = "Note")]
    public string Note { get; set; }
    [Display(Name = "Members")]
    public string Membersid { get; set; }

}

Code is executed successfully but the problem is remaining fields also updated with null value i have 6 columns i want to update 2 columns only.
Any help ?

A: Your source and destination object used in AutoMapper are of the same type (MemberTasks). That's not how AutoMapper is supposed to be used. AutoMapper is used to map between domain models and view models.
So you must have a view model containing the properties passed from the view:
public class MemberTasksViewModel
{
    public int Id { get; set; }
    public int Taskid { get; set; }
    public int Status { get; set; }
}

and then:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(MemberTasksViewModel viewModel)
{
    if (ModelState.IsValid)
    {
        MemberTasks domainModel = db.MemberTask.Find(viewModel.Id);
        Mapper.Map(viewModel, domainModel);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(viewModel);
}


text:
Q: reading files in R I've been searching for a solution for my problem in many topics but i couldn't find the answere. I have a dozen of files i'm trying to read from directory but nothing seems to work.
I tried this in a first place:
files <- list.files(path="../..")
files1 <- lapply(files, read.table, header=TRUE, sep="", skip=5)

and this:
files <- list.files(path="../..")
for (i in 1:length(files)) {
files1 <- read.table(files[i], header=TRUE, sep="",skip=5)
}

it says error file(file, "rt") can't open such file or directory, though when i do >files, it lists all the files.
where's the mistake? tx

A: list.files gives you the file names, where as you need the whole path name.
One option is to paste the full path to the files list: paste("path/to/files/", files, sep="/")
The other option, as @BenBarnes points out, is to use the full.names argument in list.files()

A: I prefer to use the plyr package for this type of thing. Depending on how you plan on using the files, you may need to use a different l*ply function:
require(plyr)
files <- dir("../..", full= TRUE)
data <- llply(files, read.table, header= T, sep= "", skip= 5)

This would give you a list of 12 (or however many) datasets.


text:
Q: Grub doesn't load Ubuntu 10.10 after update I recently installed a lot of updates for Ubuntu 10.10, since 11.04 didn't work on my system (Lenovo x201).
Today after the update, grub still exists and lists all OS on boot-up. Starting Windows 7 is no problem but starting Ubuntu just does not work. When starting Ubuntu the system comes to the loading screen, but it shows no HDD activity (no HDD-activity light). It just stays that way.
I really need to get the system running ASAP.
I already tried this HowTo but it didnt worked.

fdisk -l
Disk identifier: 0x8bd47c21

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1               1       21624   173688832    7  HPFS/NTFS
Partition 1 does not end on cylinder boundary.
/dev/sda2   *       30739       38914    65659904    7  HPFS/NTFS
Partition 2 does not end on cylinder boundary.
/dev/sda3           21624       30739    73219073    5  Extended
/dev/sda5           21624       30134    68358144   83  Linux
/dev/sda6           30134       30739     4859904   82  Linux swap / Solaris

Partition table entries are not in disk order

Disk /dev/sdb: 32.1 GB, 32128368640 bytes
14 heads, 11 sectors/track, 407472 cylinders
Units = cylinders of 154 * 512 = 78848 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000d4beb

   Device Boot      Start         End      Blocks   Id  System
/dev/sdb1   *          54      407473    31371264    c  W95 FAT32 (LBA)

A: there was a bug in ubuntu, where after an update, the UUIDs of the hard-drive partitions have changed. Try to tell grub to boot from /dev/sda5 - instead of the UUID that it is probably trying to.


text:
Q: Geocoding Geopandas Hey guys im running into an issue with geocoding. I have a address.csv with hundreds of addresses. I am using the geopandas.tools.geocode and my provider is bing to get zipcodes for all these addresses, but I am unsure on how to extract just the zipcode.
This is my current output.
geometry                                            address
0  POINT (-112.13369 33.84443)  39508 N Daisy Mountain Dr, Anthem, AZ 85086, U...
1  POINT (-112.13671 33.86698)  3640 W Anthem Way, Anthem, AZ 85086, United St...

I just want to extract the zipcode from the address field, and add it into my address.csv file.

A: One way of doing this it the following:
import pandas as pd
df = pd.read_csv("adresses.csv", sep=";")
print(df)

                geometry  \
0  POINT (-112.13369 33.84443)
1  POINT (-112.13671 33.86698)

                                             address
0  39508 N Daisy Mountain Dr, Anthem, AZ 85086, U...
1  3640 W Anthem Way, Anthem, AZ 85086, United St...

and split the column you want by delimiters:
adresses = df['address']
df[['street','town', 'zip', 'other']] =  adresses.str.split(",", n=4, expand=True)
df

which return:
                   geometry  \
0  POINT (-112.13369 33.84443)
1  POINT (-112.13671 33.86698)

                                             address  \
0  39508 N Daisy Mountain Dr, Anthem, AZ 85086, U...
1  3640 W Anthem Way, Anthem, AZ 85086, United St...

                      street     town        zip           other
0  39508 N Daisy Mountain Dr   Anthem   AZ 85086   United States
1          3640 W Anthem Way   Anthem   AZ 85086   United States

I don't really know how zip-codes work, but if you do not want the AZ (Arizona) you can repeat this by

df[['State','code']]= df.zip.str.split(expand=True,)

Which gives:
                   geometry  \
0  POINT (-112.13369 33.84443)
1  POINT (-112.13671 33.86698)

                                             address  \
0  39508 N Daisy Mountain Dr, Anthem, AZ 85086, U...
1  3640 W Anthem Way, Anthem, AZ 85086, United St...

                      street     town        zip           other State   code
0  39508 N Daisy Mountain Dr   Anthem   AZ 85086   United States    AZ  85086
1          3640 W Anthem Way   Anthem   AZ 85086   United States    AZ  85086


text:
Q: How To Connect Two Monitors To Lenovo 320 ideapad I want to connect two monitors to my lenovo ideapad 320 laptop. It has one HDMI port, 2 USB 2.0 and one USB-C port. Is there any way where I can connect two monitors to it along with keyboard and mouse? Also the display should be in extended mode and not duplicate so that each display should be independent of the other.

A: propably you need to use a external adapter, sth like this: https://m.newegg.ca/products/N82E16812400524

A: In the user manual, on page 7, it reads:

Type-C port support:

*

*USB 3.1 Gen1

That means your USB-C port does not support DisplayPort display connections but only USB data connections.
Unlike DisplayPort, HDMI only supports a single display.
This leaves the following options for the second external display:

*

*A USB graphics solution, like Artur Ludwik linked to in his answer ("DisplayLink")

*A Matrix DualHead2Go for use with DVI (doesn't support all of HDMI, but should be sufficient)

When considering a USB graphics solution, look for USB 3.0 (USB 3.1 Gen1 is USB 3.0) for ideal performance. However, be very careful: You probably won't find one with USB-C that isn't dependent on DisplayPort Alt Mode. Instead, you may have to get an additional USB-C-USB-A adapter.
And then, of course, there's also USB hubs, if you need more ports.

A: As Daniel B has clarified, you can't just plug in any monitor into your USB-C port, as it doesn't support Display Port.
There are however some screens that will work through any USB 3.0 connector using a vendor-specific driver. One of them is the Asus ZenScreen, which will even connect to a USB-A 3.0 port:

[The Zen Screen] only requires a single USB connection for both power and video transmission from your host device. It features an innovative hybrid-signal solution with native support for USB Type-C™ (USB-C™) connections, and uses an installed driver to support USB Type-A connectors for full compatibility.

So you probably can even connect some USB-Hub to your USB-C port, attach the Zen screen to that and gain some free ports for other peripherals.
There might be other devices on the market that work in a similar way Be sure to contact the OEM before buying, to make sure the product is compatible with your device.
FULL DISCLOSURE: I own an Asus Zen Screen. I don't have any business association whatever with Asus, nor do I own stock or any other interest in that company. This answer is not meant in any way to recommend a spicific product over any other possible product, but only to give the OP a possible solution to his question.

A: There's a splitter you can buy. So, you can connect your both monitors in it and the output in the laptop.
Check this one
HDMI Male to Dual HDMI Female 1 to 2 Way HDMI Splitter Adapter Cable with USB Power Cable for HDTV


text:
Q: IE10 text-overflow ellipsis not working I have an  tag in html, and I want it to be ellipsis. But when I add a
 inside the  tag, 'text-overflow' doesn't work.
HTML:

text-overflow Attribute Sample

      Each box (div element) below contains the following text:

CSS:
div.boxed {
    width: 200px;
    height: 200px;
    border: 1px solid blue;
    font: 14px Times New Roman, serif;
    overflow:hidden;
    'position:relative;
}
a.caption {
    overflow:hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    display:block;
    text-decoration:none;
    float:left;
    text-align:left;
}

http://jsfiddle.net/nPzsy/
After removing the
, the 'text-overflow' works again.

A: First of all, div is a block level element and a is an inline level element, so you cannot use a div inside an anchor tag b...so you should use any other inline tag (like small , span etc)
Secondly, if you have to use a div inside div, you can wrap your text in another tag like this ....

text-overflow Attribute Sample

         Each box (div element) below contains the following text:

and css of class textTrunc:
.textTrunc{
    overflow:hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    display:block;
}


text:
Q: SQL order rows in a table by value in another table I am running this query to select rows from admin table where display_on_website value is 1 in admin_meta table.
SELECT
                a.sequence as sequence,
                CONCAT(a.forename, ' ', a.surname) as name,
                a.position as position
            FROM
                admin a, admin_meta am
            WHERE
                a.disabled = '' AND
                a.sequence = am.user AND
                am.field = 'display_on_website' AND
                am.value = '1'

I have a row in admin_meta table for each user that is website_order - how can i order by this value?

A: You need to join with the admin_meta table twice, once to get the display_on_website value, and again to get the website_order value to order by.
SELECT a.sequence, CONCAT(a.forename, ' ', a.surname) AS name, a.position
FROM admin AS a
JOIN admin_meta AS m1 on a.sequence = m1.user
JOIN admin_meta AS m2 ON a.sequence = m2.user
WHERE a.disabled = ''
AND am1.field = 'display_on_website' AND am1.value = '1'
AND am2.field = 'website_order'
ORDER BY CAST(am2.value AS DECIMAL)


text:
Q: Disabling CSRF on a specific action CakePHP 3 So, I have a table that is auto-generated using DataTables. An action in my CakePHP grabs the data for that table, and formats it into JSON for datatables to use, this is the formatted JSON:
<?php
$data = array();
if (!empty($results)) {
    foreach ($results as $result) {
        $data[] = [
          'name' => $result->name,
          'cad' => $this->Number->currency($result->CAD, 'USD'),
          'usd' => $this->Number->currency($result->USD, 'USD'),
          'edit' => 'Url->build(['controller' => 'Portfolios', 'action' => 'edit', $result->id]) .
    '">',
          'delete' => '<input type="checkbox" class="delete" value="' . $result->id . '">'
        ];
    }
}

echo json_encode(compact('data'));

As you can see, I have a 'delete' option in there that outputs a checkbox with the value of the id of the corresponding element. When that checkbox is checked, a delete button is showing which sends this ajax request:
$('a#delete').on('click', function(e) {
    e.preventDefault();
    var checkedValues = [];
    $('input.delete:checked').each(function() {
        checkedValues.push($(this).val());
    });
    $.ajax({
        url: $(this).attr('href'),
        type: 'POST',
        data: checkedValues
    });
})

This ajax post goes to my controller action delete(). The problem I'm having is that I'm getting an error that states "Invalid Csrf Token". I know why this is happening, I'm submitting a form with Csrf protection on, that has no Csrf token added to it.
I can't figure out how to manually create a Csrf token for this situation (where the input values are generated after the page has loaded). Nor can I figure out how to disable Csrf protection. I read this, but the code is placed in the beforeFilter function, and as far as I understand it, that means it's run on every action, not just this one, and that's not what I want. Plus, to be completely honest, I would prefer a solution where I don't deactivate security functions.
Is there anyway to disable Csrf for this specific action, or is there a better way to do this?

A: Above answer does not work in Cakephp 3.6 or later.
Cakephp add object of CsrfProtectionMiddleware in src/Application.php.
If you have to remove CSRF protection  for specific controller or action then you can use following work around:
public function middleware($middlewareQueue)
{
    $middlewareQueue = $middlewareQueue
        // Catch any exceptions in the lower layers,
        // and make an error page/response
        ->add(ErrorHandlerMiddleware::class)

        // Handle plugin/theme assets like CakePHP normally does.
        ->add(AssetMiddleware::class)

        // Add routing middleware.
        // Routes collection cache enabled by default, to disable route caching
        // pass null as cacheConfig, example: `new RoutingMiddleware($this)`
        // you might want to disable this cache in case your routing is extremely simple
        ->add(new RoutingMiddleware($this, '_cake_routes_'));
        /*
        // Add csrf middleware.
        $middlewareQueue->add(new CsrfProtectionMiddleware([
            'httpOnly' => true
        ]));
        */
    //CSRF has been removed for AbcQutes controller
    if(strpos($_SERVER['REQUEST_URI'], 'abc-quotes')===false){
        $middlewareQueue->add(new CsrfProtectionMiddleware([
            'httpOnly' => true
        ]));
    }
    return $middlewareQueue;
}

A: So i needed a fix for cakephp 3.7 and using $_SERVER['REQUEST_URI'] is realllly not the way to go here. So here is how you are supposed to do it after reading through some documentation.
In src/Application.php add this function
public function routes($routes)
{
    $options = ['httpOnly' => true];
    $routes->registerMiddleware('csrf', new CsrfProtectionMiddleware($options));
    parent::routes($routes);
}

Comment out the existing CsrfProtectionMiddleware
public function middleware($middlewareQueue)
{
  ...
  //            $middlewareQueue->add(new CsrfProtectionMiddleware([
  //                'httpOnly' => true
  //            ]));
}

Open your config/routes.php add $routes->applyMiddleware('csrf'); where you do want it
Router::prefix('api', function ($routes)
{
  $routes->connect('/', ['controller' => 'Pages', 'action' => 'index']);
  $routes->fallbacks(DashedRoute::class);
});

Router::scope('/', function (RouteBuilder $routes)
{
  $routes->applyMiddleware('csrf');
  $routes->connect('/', ['controller' => 'Pages', 'action' => 'dashboard']);
  $routes->fallbacks(DashedRoute::class);
});

Note that my api user now has no csrf protection while the basic calls do have it.
If you have more prefixes don't forgot to add the function there aswell.

A: in Application.php this worked for me....
    $csrf = new CsrfProtectionMiddleware();

    // Token check will be skipped when callback returns `true`.
    $csrf->whitelistCallback(function ($request) {
    // Skip token check for API URLs.
      if ($request->getParam('controller') === 'Api') {
          return true;
      }

    });

A: read all about the CSRF component here
http://book.cakephp.org/3.0/en/controllers/components/csrf.html
you can disable for a specific action here:
http://book.cakephp.org/3.0/en/controllers/components/csrf.html#disabling-the-csrf-component-for-specific-actions
 public function beforeFilter(Event $event) {
     if (in_array($this->request->action, ['actions_you want to disable'])) {
         $this->eventManager()->off($this->Csrf);
     }
 }


text: Q: gb4e: set font size The problem is simple. I use 14pt font size document-wide (\documentclass[a4paper,14pt]{article}). But gb4e overrides this and uses (apparently) 12pt font in examples. How do I get gb4e to use the font size I want?


text:
Q: django test / python syntax I'm new Django and also to modern web-development . i had a doubt the testing of app.
The confusion may be because of my less python knowledge . I was a Java programmer so i got a doubt with the code below. Here's my code:
def test_was_published_recently_with_old_poll(self):
    """
    was_published_recently() should return False for polls whose pub_date
    is older than 1 day
    """
    old_poll = Poll(pub_date=timezone.now() - datetime.timedelta(days=30))
    self.assertEqual(old_poll.was_published_recently(), False)

This my code in test.py of my app. What's actually happening at Poll(pub_date=timezone.now() - datetime.timedelta(days=30))...
    My question is (Poll is a class defined in models.py) what's actually happening here?
    Can anyone please explain in details ?
Thanks in advance.

A: Since you say your experience is in Java, I have no idea why you are having a problem here. This syntax is almost exactly the same as Java's: you create a Poll instance whose pub_date field is set to a certain value, ie the date as of 30 days ago.

A: At '$' Poll(pub_date=timezone.now() - datetime.timedelta(days=30)) you create a class with field pub_date set to timezone.now() - datetime.timedelta(days=30).
For example, now is 2012-07-31 11:19:42.897000+00:00. The Poll constructor will create class with pub_date set to 2012-07-01 11:19:42.897000+00:00

A: This is a unit test that's making sure the was_published_recently method of the Poll object is working as expected. It creates an instance of Poll, passing it a datetime 30 days in the past… and because this wasn't 'recent' calling the was_published_recently method is expected to return False. You're then using self.assertEqual() to test for the expected behaviour.


text:
Q: 411 Length Required .Net Core Api hosted on IIS and ESP8266 I'm building .net core Api for my ESP8266 sensors.
Sensors sending update in JSON.
I'm getting 411 HTTP Error, but Content-Length is provided in request.
I think problem is in multiple Hypertext Transfer Protocol - see in wireshark screenshot - but how to solve this?
Api SourceCode
ESP8266 HTTP library adding Content-Length header here: SourceCode #L673
Request in Wireshark:


text:
Q: How to get the ID of the newly created record How to get the ID that was created in a custom object
Below is my scenario, I'm creating a new record in the Work_Order__c object using the APEX class:
// object instance with memory allocation.
    Work_Order__c wo = new Work_Order__c();
    wo.Est_Hours__c = 89;
    wo.Instructions__c = 'this is a test';
    insert wo;

and it successfully created and I have looked at the system.debug log and this is what I'm getting in the log:

USER_DEBUG|[14]|DEBUG|Work_Order__c:{Instructions__c=this is a test,
  Est_Hours__c=89, Id=a0j1a000000cbuFAAQ}

My question is there a way I can hold that newly created ID and update to a different object ?

A: There are 2 ways to get that.
One as mentioned by Keith, the ID field of the variable wo will be assigned the value.
Other than that you can get the value in After Trigger as well.
for(Your_Object__c  i:trigger.new) {
     ID id = i.Id;
}


text:
Q: Найдите все блюда, которые отмечены как вегетарианские (Vegetarian), но в ингредиентах содержится мясо индейки (Turkey). Вывести: Name SELECT Name
FROM dishes
WHERE name LIKE 'Turkey_%'
мой способ решение
Запрос составлен верно
#сайт принимает
#но выдает ошибку снизу!
Число возвращенных строк разное. Количество: 1. Ожидается: 0


text:
Q: In C++ are elements of an array of pointer type by default guaranteed to be initialized to nullptr? If I have code like so
class Node {
public:
    Node *subnodes[10];
};
Node x = Node();

is it guaranteed after that code runs that x->subnodes[0] == nullptr?
I'm no expert at C++, and I find C++ specs daunting. This works out in practice, but is it guaranteed by the spec that nullptr is put in each element of the array in this case (as opposed to, say, potentially garbage)? I haven't convinced myself by finding authoritative spec language to that effect so far, and out in the wild I see lots of examples of code seeming not to trust that this is true. So, after some time failing to come up with the answer, I turn to you, stackoverflow. Thanks in advance.

A: Yes, it is guaranteed.
Node() constructs a temporary object and performs value initialization. As the result, all the elements of the member array subnodes are zero-initialized as null pointer. x is copy-initialized from the temporary object and its members get the same initialization result too. (Because of copy elision x might be value-initialized directly, anyway the result won't change.)

if T is a class type with a default constructor that is neither user-provided nor deleted (that is, it may be a class with an implicitly-defined or defaulted default constructor), the object is zero-initialized and then it is default-initialized if it has a non-trivial default constructor;

and

The effects of zero initialization are:

*

*If T is a scalar type, the object's initial value is the integral constant zero explicitly converted to T.

*If T is an non-union class type, all base classes and non-static data members are zero-initialized, and all padding is initialized to
zero bits. The constructors, if any, are ignored.

*...

*If T is array type, each element is zero-initialized.

*...

BTW: For default initialization like Node x;, the elements of the member array would be initialized to indeterminate values.

A: While it is guaranteed to intialize it to nullptr, I would not recommend relying on the default intializing in c++. Sometimes the Default intialization does some weird things, for example, if you did not intialize an integer it intializes it with the next available memory address, which makes zero sense.


text:
Q: What is the dialog box called after clicking  on iOS Safari? I'm trying to figure out how to determin

*

*the onClose of this dialog.

*the onOpen of Photo Library or Take Photo or Video or Browse (which I think can just be solved by having a visibility listener on the document.


text:
Q: Listview for ArrayList>with multiple Button for each Item row I'm a bit new to android, but I am trying to come up with a list view from ArrayList<HashMap<String, String>> with button, likes and comments for a chat appI have been able to create a custom listview for each item as displayed
My question is on how to get the update button in my custom listview for each item to be clickable in order to add comments and also maybe how to create a dialog to show comments that exist when clicked.
Please help me for I have been stuck on how to do so for over one week
my code for fragment that holds the list view
   public class MinetCommunityInMinetCommunityFragment extends Fragment {
    private SessionHandler session;

    static final String TAG = MinetCommunityInMinetCommunityFragment.class.getSimpleName();

    private ListView lvChat;
    private static final String KEY_EMPTY = "";

    private static final int PICK_PHOTO = 1958;
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    private static final String KEY_ID_MINET_COMMUNITY = "idminetcommunity";
    private static final String KEY_CONTENTS = "Contents";
    private static final String KEY_DATE_POSTED = "DatePosted";
    private static final String KEY_ADDED_BY = "AddedBy";
    private static final String KEY_POST_TYPE = "PostType";
    private static final String KEY_POST_ID = "PostID";

    private static final String KEY_FIRST_NAME = "F_Name";
    private static final String KEY_LAST_NAME = "L_Name";

    private ProgressBar spinnerAllChats;

    ArrayList<HashMap<String, String>> allChatsList;
    private TextView noDataChats;

    private EditText etMessage;
    private Button btSend;
    private Button btnAttachMinetCommunityImage;
    private TextView tvImageName;
    private ImageView imageViewMinetCommunity;

    private String filePath;

    private String stringContents;
    private String stringImageName;

    private Button btnUpdateChat;

    //for deleting later// TEST PURPOSES
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventModel event) throws ClassNotFoundException {
        if (event.isTagMatchWith("response")) {
            String responseMessage = "Response from Server:\n" + event.getMessage();
            //responseTextView.setText(responseMessage);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        final View view = inflater.inflate(R.layout.fragment_minet_community_in_minet_community_fragment, container, false);
        session = new SessionHandler(getActivity().getApplicationContext());

        //HttpsTrustManager.allowMINETSSL();
        etMessage = (EditText) view.findViewById(R.id.etMessage);
        btSend = (Button) view.findViewById(R.id.btSend);
        btnAttachMinetCommunityImage = (Button) view.findViewById(R.id.btnAttachMinetCommunityImage);
        tvImageName = (TextView) view.findViewById(R.id.tvImageName);
        imageViewMinetCommunity = view.findViewById(R.id.imageViewMinetCommunity);
        lvChat = (ListView) view.findViewById(R.id.lvChat);

        allChatsList = new ArrayList<>();
        verifyStoragePermissions(getActivity());

        noDataChats = view.findViewById(R.id.MinetCommunityNoData);

        spinnerAllChats =(ProgressBar)view.findViewById(R.id.progressBarMinetCommunity);
        spinnerAllChats.setVisibility(View.VISIBLE);

        new GetAllChats().execute();

        btnAttachMinetCommunityImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new   Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, PICK_PHOTO);

            }
        });

        btSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (validateInputs()) {
                    uploadButtonClicked();

                    Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            // Do something after 5s = 5000ms
                            allChatsList.clear(); // clear the list view
                            // Update list view
                            new GetAllChats().execute();
                        }
                    }, 2000);
                }
            }
        });

        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK ){
            if(requestCode == PICK_PHOTO ) {
                Uri imageUri = data.getData();
                filePath = getPath(imageUri);
                imageViewMinetCommunity.setImageURI(imageUri);
                //imageView.setImageURI(imageUri);
                Toast.makeText(getActivity(), filePath, Toast.LENGTH_SHORT).show();
                tvImageName.setText(filePath);
                // uploadButton.setVisibility(View.VISIBLE);

            }

        }
    }

    private String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    public void uploadButtonClicked() {
        User user = session.getUserDetails();
        String pricipal = user.getUserId();
        stringContents = etMessage.getText().toString();
        stringImageName = tvImageName.getText().toString();

        if(stringImageName.equals(KEY_EMPTY)) {

            String type = "addCommunityComment";

            BackGroundWorker backGroundWorker = new BackGroundWorker(getActivity());
            backGroundWorker.execute(type,pricipal,stringContents);

            etMessage.getText().clear();
        } else {
            NetworkCall.fileUpload(filePath, new ImageSenderInfo( pricipal,stringContents));

            etMessage.getText().clear();
            tvImageName.setText(" ");//filepath
            imageViewMinetCommunity.setImageURI(null);
        }
    }

    private class GetAllChats extends AsyncTask<Void, Void, Void> {
        User user = session.getUserDetails();
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Toast.makeText(getActivity(),"Json Data is downloading",Toast.LENGTH_LONG).show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {

            HttpHandler sh = new HttpHandler();

            //Toast.makeText(getActivity(), user.getUserId(), Toast.LENGTH_SHORT).show();
            String url = "http://10.0.2.2/WellnessMinet/viewMinetCommunity.php";
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);
            if(allChatsList.isEmpty()) {
                if (jsonStr != null) {
                    try {
                        JSONObject jsonObj = new JSONObject(jsonStr);

                        // Getting JSON Array node
                        JSONArray upload_files = jsonObj.getJSONArray("minetcommunity");

                        // looping through All Contacts
                        for (int i = 0; i < upload_files.length(); i++) {

                            JSONObject c = upload_files.getJSONObject(i);

                            // String policy_id = c.getString("");
                            String ID = c.getString(KEY_ID_MINET_COMMUNITY);
                            String contents = c.getString(KEY_CONTENTS);
                            String datePosted = c.getString(KEY_DATE_POSTED);
                            String addedBy = c.getString(KEY_ADDED_BY);
                            String postType = c.getString(KEY_POST_TYPE);

                            String firstName = c.getString(KEY_FIRST_NAME);
                            String lastName = c.getString(KEY_LAST_NAME);

                            // tmp hash map for single upload_file
                            HashMap<String, String> upload_file = new HashMap<>();

                            // adding each child node to HashMap key => value
                            upload_file.put(KEY_ID_MINET_COMMUNITY,  ID);
                            upload_file.put(KEY_CONTENTS, contents);
                            upload_file.put(KEY_DATE_POSTED, datePosted);
                            upload_file.put(KEY_ADDED_BY, addedBy);
                            upload_file.put(KEY_POST_TYPE, postType);

                            upload_file.put(KEY_FIRST_NAME, firstName);
                            upload_file.put(KEY_LAST_NAME, lastName);

                            if (c.getString(KEY_POST_TYPE).equalsIgnoreCase("Posts")) {
                                allChatsList.add(upload_file);
                            }
                        }
                    } catch (final JSONException e) {
                        Log.e(TAG, "Json parsing error: " + e.getMessage());
                        requireActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity().getApplicationContext(),
                                        "Json parsing error: " + e.getMessage(),
                                        Toast.LENGTH_LONG).show();
                            }
                        });

                    }

                } else {
                    Log.e(TAG, "Couldn't get json from server.");
                    requireActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity().getApplicationContext(),
                                    "Couldn't get json from server. Check LogCat for possible errors!",
                                    Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            //Toast.makeText(getActivity(), user.getUserId(), Toast.LENGTH_SHORT).show();

            if (getActivity() != null) {
                // Code goes here.

                    ListAdapter adapter = new SimpleAdapter(getActivity(), allChatsList,
                            R.layout.list_chats, new String[]{KEY_DATE_POSTED, KEY_CONTENTS, KEY_FIRST_NAME, KEY_LAST_NAME},
                            new int[]{
                                    R.id.PostDateChat,
                                    R.id.tvPostChat,
                                    R.id.tvFnameChat,
                                    R.id.tvLnameChat
                            });
                    lvChat.setAdapter(adapter);

            }

            //set height to see all items - hack because of listview in scrollable view
            Utility.setListViewHeightBasedOnChildren(lvChat);
            //ListUtils.setDynamicHeight(lvChat);
            if (allChatsList.isEmpty()){
                noDataChats.setVisibility(View.VISIBLE);
            }
            spinnerAllChats.setVisibility(View.GONE);

            lvChat.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                    Toast.makeText(getActivity(), "this row clicked", Toast.LENGTH_SHORT).show();

                    btnUpdateChat = view.findViewById(R.id.btnUpdateChat);
                    btnUpdateChat.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            Toast.makeText(getActivity(), "this row clicked", Toast.LENGTH_SHORT).show();
                        }
                    });

                }
            });

        }
    }

    public static class Utility {
        public static void setListViewHeightBasedOnChildren(ListView listView) {
            ListAdapter listAdapter = listView.getAdapter();
            if (listAdapter == null) {
                // pre-condition
                return;
            }

            int totalHeight = 0;
            int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.AT_MOST);
            for (int i = 0; i < listAdapter.getCount(); i++) {
                View listItem = listAdapter.getView(i, null, listView);
                listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
                totalHeight += listItem.getMeasuredHeight();
            }
            //I added this to try to fix half hidden row
            totalHeight++;

            ViewGroup.LayoutParams params = listView.getLayoutParams();
            params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
            listView.setLayoutParams(params);
            listView.requestLayout();
        }
    }

    /**
     * Checks if the app has permission to write to device storage
     *
     * If the app does not has permission then the user will be prompted to grant permissions
     */
    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    activity,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
    }

    /**
     * Validates inputs and shows error if any
     * @return
     */
    private boolean validateInputs() {

        if (KEY_EMPTY.equals(stringContents)) {
            etMessage.setError("Message post cannot be empty");
            etMessage.requestFocus();
            return false;
        }
        return true;
    }

}

Code for the custom Listview for each listview Item
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TableLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingLeft="10dp"
            android:paddingRight="10dp">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <TableRow android:padding="5dp"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content">

                    <de.hdodenhof.circleimageview.CircleImageView
                        android:id="@+id/profile_image_chat"
                        android:layout_width="96dp"
                        android:layout_height="74dp"
                        android:layout_gravity="center"
                        android:contentDescription="@string/nav_header_desc"
                        android:paddingTop="@dimen/nav_header_vertical_spacing"
                        android:src="@drawable/profile"
                        app:civ_border_color="#DAD8D8"
                        app:civ_border_width="2dp" />

                    <LinearLayout
                        android:layout_width="300dp"
                        android:layout_height="wrap_content"
                        android:orientation="vertical">

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:orientation="horizontal">

                            <TextView
                                android:id="@+id/tvFnameChat"
                                android:padding="1dp"
                                android:textSize="16dp"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:textStyle="bold"
                                android:textColor="#03A9F4"/>

                            <TextView
                                android:id="@+id/tvLnameChat"
                                android:padding="1dp"
                                android:textSize="14dp"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:textStyle="bold"
                                android:textColor="#03A9F4"/>

                        </LinearLayout>

                        <TextView
                            android:id="@+id/PostDateChat"
                            android:textSize="10sp"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:textStyle="bold"
                            android:textColor="#9E9A94"/>

                    </LinearLayout>

                </TableRow>

                <TextView
                    android:id="@+id/tvPostChat"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"/>

                <ImageView
                    android:id="@+id/imageViewChat"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/profile" />

                <LinearLayout
                    android:weightSum="4"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">

                    <TextView
                        android:id="@+id/idDeleteChat"
                        android:layout_width="wrap_content"
                        android:layout_height="match_parent"
                        android:layout_weight="2"
                        android:drawableStart="@drawable/ic_delete"
                        android:padding="10dp"
                        android:text="Delete"
                        android:textStyle="bold"
                        android:visibility="invisible"/>
                    <TextView
                        android:id="@+id/tvLikesChat"
                        android:drawableStart="@drawable/ic_thumb_up"
                        android:textStyle="bold"
                        android:layout_weight="2"
                        android:padding="10dp"
                        android:text="Like (0)"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"/>

                    <TextView
                        android:layout_weight="2"
                        android:padding="10dp"
                        android:layout_width="50dp"
                        android:layout_height="wrap_content"/>

                    <TextView
                        android:id="@+id/tvCommentsByCommunityChat"
                        android:text="Comments (1)"
                        android:textStyle="bold"
                        android:drawableStart="@drawable/ic_insert_comment"
                        android:layout_weight="2"
                        android:padding="10dp"
                        android:background="@drawable/backborder"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"/>

                </LinearLayout>

                <LinearLayout
                    android:layout_marginTop="10dp"
                    android:orientation="horizontal"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <EditText
                        android:id="@+id/etResponseChat"
                        android:layout_width="290dp"
                        android:layout_marginRight="10dp"
                        android:layout_height="wrap_content"
                        android:padding="10dp"
                        android:hint="Response"
                        android:background="@drawable/backborder"/>
                    <Button
                        android:id="@+id/btnUpdateChat"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:background="@drawable/buttonrectanglegreenchat"
                        android:text="Update"
                        android:textColor="@color/white"
                        android:textAllCaps="false"/>

                </LinearLayout>

            </LinearLayout>

        </TableLayout>

    </LinearLayout>

</LinearLayout>


text:
Q: Printing a list which has elements other lists (same struct) recursively This is how i recursively print a list:
if (mylist_ptr == NULL) {
        return ;
    }

    printf("%s: ", mylist_ptr->str);
    report(mylist_ptr->next);

    return ;

Now i want to print a list which has elements other lists,same way(recursively).
This is how my list looks like.
       |-->    `Link0`      `Link1`      `Link2`      `Link3`
       |     list1        list2        list3        list4
       |    next         next         next          NULL

newlist-|
and each sublist after the last link ,and the final link is linked with NULL.Also the structs:
struct link {
    char value[20] ;
    struct link* next ;
} ;

typedef struct link Link;
typedef Link * List;

struct lstlst{
    List list;
    struct lstlst*next;
} ;
typedef struct lstlst Listoflists;

I wrote 5 more lines but they got lost after i refreshed cause i deleted my post so im going to be a little bit more short if thats ok.

A: One function for struct link to print it recursively. Then we go up in the hierarchy, create a recursive function for printing struct lstlst which calls recursive function for printing struct link.
#include <stdio.h>

struct link_s {
    char value[20];
    struct link_s *next;
};

struct lstlst_s {
    struct link_s list;
    struct lstlst_s *next;
};

static void link_print(const struct link_s *elem) {
    printf("%s\n", elem->value);
}
static void link_print_recursively(const struct link_s *head)
{
    if (head == NULL) return;
    link_print(head);
    link_print_recursively(head->next);
}
static void lstlst_print(const struct lstlst_s *elem)
{
    link_print_recursively(&elem->list);
}
static void lstlst_print_recursively(const struct lstlst_s *head) {
    if (head == NULL) return;
    lstlst_print(head);
    lstlst_print_recursively(head->next);
}

// C11 _Generic can support both struct types
#define generic_print_recursively(head)  _Generic((head), \
        const struct lstlst_s *: lstlst_print_recursively, \
        const struct link_s *: link_print_recursively)(head)

int main()
{
    const struct lstlst_s lstlst_head = {
        .list = {
            .value = "1 1",
            .next = &(struct link_s){
                .value = "1 2",
                NULL,
            }
        },
        .next = &(struct lstlst_s){
            .list = {
                "2 1",
                &(struct link_s){
                    "2 2",
                    NULL,
                }
            },
        }
    };
    const struct link_s link_head = {
        "3 1",
        &(struct link_s){
            .value = "3 2",
            NULL,
        }
    };

    printf("One\n");
    lstlst_print_recursively(&lstlst_head);
    link_print_recursively(&link_head);
    printf("Two\n");
    generic_print_recursively(&lstlst_head);
    generic_print_recursively(&link_head);

    return 0;
}

@edit: I have shortened the example structure and added a simple _Generic macro for function overloading on list/structure type.


text:
Q: Sturm-Liouville Eigenvalues Consider Sturm-Liouville endpoint problems of the form $y''+\lambda y=0$ with the usual endpoint conditions.  $c_1y(a)+c_2y'(a)=0$, $d_1y(b)+d_2y'(b)=0$. Here $(c_1,c_2) \neq \vec{0}$ and $(d_1,d_2) \neq \vec{0}$.  We know that the eigenvalues form a discrete sequence tending to infinity.
My question is, can we arrange the boundary conditions $a,b,c's,d's$ to get an arbitrary number of negative eigenvalues?  For example, can we arrange to get precisely two negative eigenvalues?
If I want eigenvalues $\lambda=-2,-1$, can I arrange for this?


text:
Q: How to use looping to create and return 5 rows dataframe I was requested to create a JSON dataframe using looping only, with specific headers: headers = {'User-agent': 'CS6400'} in request.get(). In addition, dataframe with 5 rows (one for each of the top 25 posts).
Since I only can use looping, not able to use "read_json" or "json_normalize". I was stuck for several hours, support needed and much appreciated.
Here is my buggy codes:(error message :ERROR! Session/line number was not unique in database. History logging moved to new session 122 )
import urllib, json
import requests
import  gzip
import json
url = "http://www.reddit.com/r/popular/top.json"
headers = {'User-agent': 'DS6001'}
response = requests.get(url,headers=headers)
data = response.read().decode("utf-8")
data = json.dumps(response)
dataframe = pd.DataFrame.from_dict(data, orient="index")
dataframe


text:
Q: Android newbie problem: restarting an application I have an Android app that works fine the first time you run it.
However, when you press HOME (so it pauses), and restart it from the home screen all I get is the music restarted.
I've not yet got to the stage of saving/restoring states yet (will do soon!).
It seems that the main update thread is not resuming.
It calls onRestart() fine...
I'm new to Java/Android so I apologize if this is a basic schoolboy error!
TIA for any advice
John

A: Programming applications for Android is a bit different then programming for conventional operating systems. Android stops your application when it looses focus. You'll have to read about activity lifecycle. If you're creating some kind of music player you should consider using a background service with a worker thread.


text:
Q: Can flexbox be used to "pack" items in a list? Using flexbox, and based on the following markup, is it possible to get the last item in the list to visually move up and "pack" itself into the available space?
I know this could be accomplished with different markup (3 columns and items within each column), using either floats or flexbox, but I am curious if this is something flexbox can do with this markup.

html,
body {
 height: 100%;
}

html {
 box-sizing: border-box;
}

*,
*:before,
*:after {
 box-sizing: inherit;
}

ul {
 list-style: none;
 margin: 0;
 padding: 0;
}

.layout {
 background-color: yellow;
 display: flex;
 flex-flow: row wrap;
 align-items: flex-start;
}

.layout__item {
 background-color: red;
 width: 33.33%;
 padding-right: 15px;
}

/* Every 3rd item. */
.layout__item:nth-child(3n) {
 padding-right: 0;
}

/* Every item after the first 3. */
.layout__item:nth-child(n+4) {
 padding-top: 15px;
}

.layout__item-content {
 background-color: green;
 height: 100%;
}

.layout__item-img {
 background-color: blue;
 height: 100%;
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odio quos voluptates impedit optio id, fugit, nobis assumenda eveniet, veniam deserunt eum magni. Voluptates quam, deserunt sit pariatur ducimus omnis eligendi!

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolores, saepe!

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Officia placeat quidem, illum cumque nisi repellat excepturi iusto aperiam tempore quam.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas natus odio quae nam officia libero.

Lorem ipsum dolor sit amet.

A: The answer to this question is quite simply no.
A good explanation as to why is available on a similar question: Horizontal masonry layout with flexbox CSS only


text:
Q: xcode executable can't access .txt file that's a part of the project I've created an Xcode console application that uses a .txt file within the project to populate a dictionary (it's a map - but that's besides the point).
This program runs fine when I run the project through Xcode, and populates the dictionary with the contents of the file correctly. I use a relative path inside of the program, based on the file's location in the project folder.
When I create the executable, and access it separately from Xcode in terminal, it does not find the file (program runs without issue - just doesn't have a dictionary).
I believe this has to do with the Build Phases setup in Xcode, because it isn't copying over the .txt file when it builds the executable, but I'm having trouble finding sufficient documentation to make this work correctly.
Can one of you kind souls please point me in the right direction? I've been searching for hours.  I'm sorry.

A: Writing out the full path name in Xcode when accessing the file resulted in the executable being created with the file information in it. This solved the probem.
More information/thoughts:
This is counter-intuitive to me, as I had imagined that Xcode would include the file without needing the full path in code, since it was able to find the file with relative path when running the program through Xcode, to begin with.
To restate:

*

*Xcode runs the program without issue when running internally, through Xcode, regardless of how the file path is specified.

*The executable will only work with the file when I change the .cpp code to list the file as a full path.
I have a feeling that this is a sloppy way to resolve the file inclusion into the executable (it broadcasts my directories on my home computer, for anyone reading the code on GitHub).
I will not be marking this as an accepted answer for now, as I am hoping that someone else will be able to figure out a smarter way around this by the time I finish my little project.

A: To copy files when you build, run, and archive your project uncheck Copy only when installing.
For your use case I'd suggest Copy Files to Products Directory and add your text file.
Documentation is hard to find, so here are some tips:

*

*Build Settings

*

*Xcode's build settings panel have environment counterparts, but they don't mirror them.

*

*For example, the build setting Installation Directory is the counterpart to the environment variable INSTALL_PATH.

*Hover over the build setting value for a tool-tip describing it's environment variable, if any.

*Run the command xcodebuild -showBuildSettings at the root of your project folder.

*Copy Files Destinations

*

*Absolute Path is an actual absolute path. If Copy only ... is unchecked it will copy the files to the path specified.

*

*However, it will fail silently for certain paths. For example ~/Desktop will fail, but ~/Desktop/subdir will not.

*Use absolute path to install data to known directory such as ~/.local/share or /usr/local/share or ~/Library/Application Support/YourApp.

*Products Directory is where your binary will be placed.

*

*It is equal to BUILD_DIR or TARGET_BUILD_DIR or INSTALL_DIR.

*Most of the other destinations will expand to products directory for command line tool target.

*See the install structure of your app by creating an Archive. Go to Product > Archive. Then in the Archive popup select Distribute Content > Built Products.

Hope this helps.


text:
Q: Angular UI modalinstance pass data to view Id like to pass data from 1 view (master view ) to modal view using angular ui bootstrap plugin , below is my code which doesn't seem to work :
master view
vm.receipt_id = "1234"

<button type="button" class="btn btn-default" ng-click="vm.alertMeJimmy(vm.receipt_id)">Large modal</button>

controller
       vm.alertMeJimmy = function(receipt_id) {

            $uibModal.open({
            animation: true ,
            templateUrl: '/cashier/views/cashier.angular_components.modal',
            controller: 'PatientsController',
            controllerAs: 'vm',
            resolve: {
             receipt_id : function () {
                  return receipt_id ;
                }

             },
            size: 'lg'

          });

        }

modal view
id like to access it like below in my modal view

A: Return an object instead of a primitive:
angular.module('App').controller('Controller', [
             '$uibModal',
    function ($uibModal) {
        var vm = this;
        vm.receipt_id = 1234;
        vm.alertMeJimmy = function (receipt_id) {
            var modalInstance = $uibModal.open({
                size: 'sm',
                templateUrl: 'modal.html',
                controller: 'Modal as vm',
                resolve: {
                    'receipt': { id: receipt_id }
                }
            });
        }
    }
]);

angular.module('App').controller('Modal', [
             'receipt',
    function (receipt) {
        var vm = this;
        vm.receipt = receipt;
    }
]);

Example on Plunker: http://plnkr.co/edit/d9RLJLHr1zr9d5gVKHpD?p=preview


text:
Q: Calculate If it's been less or more than 24 Hours using PHP I want to calculate the times between two set times (Cron job run 1 Hour, every Hour).
E.G:
2:18 PM on 20/06/2012
3:00 PM on 21/06/2012 * Cron Job Runs,  More than 24 Hours
How would I calculate this in PHP to do a task that I will develop later.
Script I've attempted:
define("SECONDS_PER_HOUR", 60*60);
date_default_timezone_set('UTC');

$result = mysql_query("SELECT * FROM tickets") or die(mysql_error());

while($row = mysql_fetch_array($result)) {
    // Calculate the start time
    $str = $row['openTime'] . " " . $row['openDate'];

    $startdatetime = strtotime($str);

    $enddatetime = time();

    // calculate the difference in seconds.

    $difference =  $enddatetime - $startdatetime;

    $hoursDiff = $difference / SECONDS_PER_HOUR;

    $minutesDiffRemainder = $difference % SECONDS_PER_HOUR;

    echo $row['ticketID'] . ": " . $hoursDiff . "h " . $minutesDiffRemainder . "m<br />";
}

A: Have you considered actually doing a query that does what you need and not pull all data and doing the comparison in PHP? You could do
SELECT * from TICKETS WHERE DATE_ADD(open time, INTERVAL 24 HOUR) > CURTIME();
From reading your code, I'd assume you need to make the opentime field is a timestamp, containing both date and time. But that is the sensible choice in most cases, anyway.


text:
Q: Binary Converter Not Working for Large Numbers I'm writing C code that converts from an integer to its binary representation, reverses the binary and then converts back to an integer. It's working well, but I need it to work for input values up to 10^9. Right now, it seems to break for anything larger than 10^7. What I mean is I put in a number such as 10000000 and get out 17967657062982931584 as being the binary representation (despite being accurate for smaller integers). In addition, I am not sure where my int_to_binary is the only function experiencing this problem, or if the others need to be optimized for large inputs as well. Any ideas where I'm going wrong? Thank you.
#include <stdio.h>
#include <string.h>

unsigned long long int_to_binary(unsigned long long k) {
    if (k == 0) return 0;
    if (k == 1) return 1;
    return (k % 2) + 10 * int_to_binary(k/2);
}

unsigned long long reverse_int(unsigned long long l) {
        unsigned long long reversed;
    reversed = 0;
        while (l > 0) {
                reversed = reversed * 10 + (l%10);
                l = l / 10;
        }
        return reversed;
}

unsigned long long binary_to_int(unsigned long long k) {
    char binaryString[80];
    snprintf(binaryString, 4, "%llu", k);
    unsigned long long decimal = 0;
    int length = strlen(binaryString);
    int i = 0;
    while(i < length) {
        decimal = (decimal << 1) + (binaryString[i] - 0x30);
        i++;
    }
    return decimal;
}

int main() {
    int number;
    printf("Enter a number: ");
    scanf("%d", &number);
    printf("You entered %d\n", number);
    unsigned long long b = int_to_binary(number);
    printf("In Binary, this is %llu\n", b);
    unsigned long long c = reverse_int(b);
    printf("When we reverse it, it looks like this: %llu\n", c);
    unsigned long long d = binary_to_int(c);
    printf("And when we convert that back to an int, it looks like this: %llu\n", d);
        return 0;
}

A: You're using long long to represent a binary number as a decimal.  On many architectures this results in the maximum value being stored of 2**64-1 = 18446744073709551615.
If you put in a decimal number such as 10000000, it cannot be represented as a decimal-binary number in 64 bits.

A: The problem is attempting to manipulate a binary number as a sum of powers of ten. It's more efficient to manipulate binary directly. Just change 10 to 2 in the reverse_int function.
unsigned long long reverse_int(unsigned long long l) {
        unsigned long long reversed;
        reversed = 0;
        while (l > 0) {
                reversed = reversed * 2 + (l%2);
                l = l / 2;
        }
        return reversed;
}

In order to print numbers in binary, write a loop, testing each bit in sequence, using modulo % or bitwise operators like & and >>.


text:
Q: Add ViewModel to Mobile View I am working on making a separate set of views for mobile devices, rather than using additional adaptive UI states for the phone. I am able to achieve this by adding a sub-folder in my Views folder called DeviceFamily-Mobile and adding a new View with the same name as the one I am overriding.
I have the following View that will work and display "MOBILE" on a mobile device/emulator.
<Page x:Class="MyApp.PayeesPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:behaviors="using:Template10.Behaviors"
      xmlns:controls="using:Template10.Controls"
      xmlns:core="using:Microsoft.Xaml.Interactions.Core"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:interactivity="using:Microsoft.Xaml.Interactivity"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:models="using:MyApp.Models"
      xmlns:viewModels="using:MyApp.ViewModels"
      xmlns:views="using:MyApp.Views"
      mc:Ignorable="d">

    <RelativePanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock x:Name="MobileTextBlock"
                   Foreground="{ThemeResource ForegroundColorBrush}"
                   Text="MOBILE" />
    </RelativePanel>
</Page>

However, if I try to set the DataContext to allow me to actual display something useful, like so:
<Page.DataContext>
    <viewModels:PayeesPageViewModel x:Name="ViewModel" />
</Page.DataContext>

Then I get an error when navigating to the PayeesPage:

Unable to cast object of type 'Windows.UI.Xaml.Controls.TextBlock' to type 'MyApp.ViewModels.PayeesPageViewModel'.

This is the same way I set the DataContext on the original PayeesPage and it works fine. Is there a different way to set the DataContext on these alternate Views, or am I missing something?

A: It turns out that the mobile View needs to have the same x:Class as the original Page. ReSharper was complaining when I tried to call it MyApp.Views.PayeesPage because that already existed, so I changed it to MyApp.PayeesPage. However, when I switched it back so that both were using the same x:Class then everything started working as expected.
Unfortunately, I am getting a bunch of red squigglies from ReSharper, but things are working as they should be. Just in case anyone comes across this question in the future:
Views/PayeesPage.xaml:
<Page x:Class="MyApp.Views.PayeesPage"
 ...>

Views/DeviceFamily-Mobile/PayeesPage.xaml:
<Page x:Class="MyApp.Views.PayeesPage"
 ...>


text:
Q: Problems with 'FileNotFoundError [Errno 2]' again I have again problems with that famous Exception.
The problem is the following:
I have wanted to write a simple code for an easy exercise about files and excel libraries (openpyxl) that I have to be make for my python programming course. At first, I have to say that I usually make all my codes in iOS.
For this time, I have wanted to do this exercise in my old PC whose O.S. is Windows, so I have exported the file where I work in iOS in a pen drive and next, export that file in my Windows desktop.
I opened VSC and the first code's line is the problem because I try to load the excel file but the exception FileNotFoundError appears.
As simple as write:
import openpyxl
fw = openpyxl.load_workbook("Data_File_2.xlsx")

The file when I'm writing the code is in the follow route: C:\Users\xxxx\Desktop\pyWork
which is the same route where the file "Data_File_2" is in it.
Well, the problem continues because every time I want to write a new code for working with extern files, this Exception appears again, even with other 'py' files that I made where I worked with extern files and now I can't run because this Exception appears again and block the program. (I'm talking about old files made in previously days or weeks which works correctly with external files)
For example, now I'm trying to open a try file .txt from a new py.file, both of them located in the same directory:
with open("try_to_open.txt","r") as op_file:
    rfile = op_file.read()
    print(rfile)

#The exception FileNotFoundError appears again in the first line.
I know that I can use try/else blocks but I want to know why this Exception appears, what is the Error in this case and why it appears  every time I want to work with external file one time that the Exception appears at first.

A: I think I have found a solution but I dont know if it's correct for similar situations like this. I was able to resolve by writing as follows:
import openpyxl

file_work = openpyxl.load_workbook("Pyworks\\Data_File_2.xlsx")


text:
Q: ion-view does not update when changing states I'm trying to make a simple log in system in Ionic.  When I type in my credentials and hit log in it should take me to a settings screen.  It does so, but it doesn't update the header; it still says account - it should say settings.
Settings View:
 <ion-view view-title = "Settings">
         <ion-nav-buttons side="primary">
            <button class="button button-full button-assertive" style = "margin-top: 0px;" ng-click = "signOff()">
              Log Off
            </button>
          </ion-nav-buttons>
        <ion-content class="has-header padding">
            ...
            ...
            ...
  </ion-content>
</ion-view>

Account View:
 <ion-view view-title="Account">
             <ion-nav-buttons side="primary">
                <button class="button button-full button-assertive" style = "margin-top: 0px;" ng-click = "signOff()">
                  Log Off
                </button>
              </ion-nav-buttons>
      <ion-content class = "padding">

            Username
            <input type="text" ng-model = "userName">

            Password
            <input type="password" ng-model = "password">

          <button style = "margin: 10px"; class="button button-positive"; ng-click = "logIn(userName, password)">
            Log in
          </button>

          <button style = "margin: 10px"; class="button button-positive"; ng-click = "createAccount(userName, password)">
            Create Account
          </button>

      </ion-content>
    </ion-view>

tabs.html:
<ion-tabs class="tabs-icon-top tabs-color-active-positive">

  <ion-tab title="Status" icon-off="ion-ios-pulse" icon-on="ion-ios-pulse-strong" href="#/tab/dash">
    <ion-nav-view name="tab-dash"></ion-nav-view>
  </ion-tab>

  <ion-tab title="Chats" icon-off="ion-ios-chatboxes-outline" icon-on="ion-ios-chatboxes" href="#/tab/chats">
    <ion-nav-view name="tab-chats"></ion-nav-view>
  </ion-tab>

  <ion-tab title="Account" icon-off="ion-ios-gear-outline" icon-on="ion-ios-gear" href="#/tab/account">
    <ion-nav-view name="tab-account"></ion-nav-view>
  </ion-tab>

  <ion-tab title="Settings" hidden="true">
      <ion-nav-view name="tab-settings"></ion-nav-view>
  </ion-tab>

</ion-tabs>

logIn Function:
  $scope.logIn = function(userName, password) {
    console.log(userName);
    console.log(password);
      $rootScope.ref.authWithPassword({
        email    : userName,
        password : password
      }, function(error, authData) {
        if (error) {
          console.log("Login Failed!", error);
        } else {
          console.log("Authenticated successfully with payload:", authData);
          $rootScope.isLoggedIn = true;
          $state.go('tab.settings');
         // $window.location.href = "#/tab/settings";
        }
      });
  };

I've tried $window.location.href instead of $state.go and I've tried to use ion-nav-title inside of my ion-view but both still yields the same result...
Any ideas?
Thanks in advanced!
EDIT: It looks like it also uses the account controller instead of the settings controller.


text:
Q: Django Foreign key in another schema I have a MySQL database with 2 shemas (A & B).
My django app can read & write into A.
It can just read from B.
My app managed all the tables in A.
B already contains some data in a table (b).
I want to add a one to one field between A and B.
Something like this :
class SchemaBTableB(models.Model):
    class Meta:
        managed = False
        db_schema = 'B'
        db_table = 'b'

    [...]

class SchemaATableA(models.Model):
    class Meta:
        db_schema = 'A'
        db_table = 'a'

    id = models.OneToOneField(
        SchemaBTableB,
        on_delete=models.DO_NOTHING,
        primary_key=True
    )

    [...]

Unfortunately, db_schema does not exist.
Does someone know a solution ?

A: I have been tried to use two databases to simulate your case, and find out the solution below:
1. Scenario:

*

*database schema1, which is managed by django (read & write)

*database schema2, which is NOT managed by django

2. Steps:

*

*create migrations python manage.py makemigrations for your models

*Generate SQL for your migration: python manage.py sqlmigrate app 0001.
(suppose the generated migration file name is 0001_initial.py from step 1)

The sql for this migration should look like this:
CREATE TABLE `user_info` (`id_id` integer NOT NULL PRIMARY KEY, `name` varchar(20) NOT NULL);
ALTER TABLE `user_info` ADD CONSTRAINT `user_info_id_id_e8dc4652_fk_schema2.user_extra_info_id` FOREIGN KEY (`id_id`) REFERENCES `user_extra_info` (`id`);
COMMIT;

If you run the above sql directly, you will be ended up with error like this:
django.db.utils.OperationalError: (1824, "Failed to open the referenced table 'user_extra_info'")

That's because django assumes that all your migration steps are executed in the same database. So it can not find out the user_extra_info in schema1 database.
3. Following Steps:

*Explicit specify the database schema2 for table user_extra_info:
ALTER TABLE `user_info` ADD CONSTRAINT `user_info_id_id_e8dc4652_fk_schema2.user_extra_info_id` FOREIGN KEY (`id_id`) REFERENCES schema2.user_extra_info (`id`);

*Manually run the revised sql in schema1 database.

*Tell django I have run the migration myself: python manage.py migrate --fake

*Done!!

Source code For your reference:
models.py
from django.db import models

class UserExtraInfo(models.Model):
    # table in schema2, not managed by django
    name = models.CharField('name', max_length=20)

    class Meta:
        managed = False
        db_table = 'user_extra_info'

class UserInfo(models.Model):
    # table in schema1, managed by django
    id = models.OneToOneField(
        UserExtraInfo,
        on_delete=models.CASCADE,
        primary_key=True
    )
    name = models.CharField('user name', max_length=20)

    class Meta:
        db_table = 'user_info'

settings.py
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'schema1',
        'USER': 'USER',
        'PASSWORD': 'PASSWORD',
        'HOST': 'localhost',
        'PORT': 3306,
    },
    'extra': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'schema2',
        'USER': 'USER',
        'PASSWORD': 'PASSWORD',
        'HOST': 'localhost',
        'PORT': 3306,
    }
}

DATABASE_ROUTERS = ['two_schemas.router.DBRouter']

router.py
class DBRouter(object):
    """
    A router to control all database operations on models in the
    auth application.
    """
    def db_for_read(self, model, **hints):
        """
        Attempts to read auth models go to auth_db.
        """
        if model._meta.db_table == 'user_extra_info':
            # specify the db for `user_extra_info` table
            return 'extra'
        if model._meta.app_label == 'app':
            return 'default'
        return None

    def db_for_write(self, model, **hints):
        """
        Attempts to write auth models go to auth_db.
        """
        if model._meta.db_table == 'user_extra_info':
            # specify the db for `user_extra_info` table
            return 'extra'
        if model._meta.app_label == 'app':
            return 'default'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        """
        Relations between objects are allowed if both objects are
        in the primary/replica pool.
        """
        db_list = ('default', 'extra')
        if obj1._state.db in db_list and obj2._state.db in db_list:
            return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        """
        Make sure the auth app only appears in the 'auth_db'
        database.
        """
        if app_label == 'app':
            return db == 'default'
        return None

A: There is a difference between a OneToOne and ForeignKey: since you mentioned FK specifically - I'll assume you want to actually make a foreign-key, which is done like this: ForeignKey(SomeModel, unique=True)
class ObjectTableA(models.Model):

    id = models.ForeignKey(
        ObjectTableB,
        on_delete=models.DO_NOTHING,
        unique=True,
    )

    [...]

class ObjectTableB(models.Model):
    class Meta:
        managed = False
        db_table = 'b'

    [...]

The difference between OneToOne and ForeignKey is like this:
With regards to a OneToOne, conceptually, this is similar to a ForeignKey with unique=True, but the "reverse" side of the relation will directly return a single object.
In contrast to the OneToOneField "reverse" relation, a ForeignKey "reverse" relation returns a QuerySet.
Since your app manages TableA, get rid of the table_schema and db_table.
In your TableB model, you may want to get rid of the table_schema
Edit: since you're sure you want a OneToOne you should just be able to do something like this:
id = models.OneToOneField(
ObjectB,
on_delete=models.DO_NOTHING,
)

Since your ObjectA is managed by Django, just link it up OneToOne to your ObjectB.


text:
Q: How to query nested objects in Firebase? I'm trying to create a query string, so the response from Firebase only returns the rows with corresponding userId (Not in top level).
The goal is to only get the orders for the user who currently logged in.
My Javascript object is like this:

const order = {
  itemId: "9T9WvJBbHiQpqyWdhBO0yX7lRny1"
  price: 5.3,
  customer: {
    userId: "-L9EyOPFB2PnyAPFUH9M",
    name: "demo user",
    address: "some place in earth",
  }
}

In Firebase, I have rules like this:
{
  "rules": {
    "orders": {
      ".read": "auth != null",
      ".write": "auth != null",
      ".indexOn": ["userId"]
    }
  }
}

However, this is obviously not working out, since the index is pointing at top level.
Here is the URL I created for the API call:

const queryParams = `?auth=${token}&orderBy="userId"&equalTo="${userId}"`;

axios
  .get('/orders.json' + queryParams)
  .then(res => {
    // get orders for the currently logged-in user
  })
  .catch(err => {
    console.error(err);
  });

If I move userId one level up, this works completely fine, but customer and authenticated user are using same ID, so I rather keep them in one object.
Is it possible to query data with nested index in Firebase?
If so, what rules and query string should I use?

A: You're looking to order on orderBy="customer/userId".
You'll also need to define the index on that nested field, which is done like this:
{
  "rules": {
    "orders": {
      ".read": "auth != null",
      ".write": "auth != null",
      ".indexOn": ["customer/userId"]
    }
  }
}

Just quickly confirmed that last one against Tom's answer here.


text:
Q: operator overloading(friend and member function) What is the difference between operator overloading using the friend keyword and as a member function inside a class?
Also, what is the difference in the case of any unary operator overloading (i.e. as a friend vs. as a member function)?

A: The difference is that the friended function is actually in global scope, so you do not need to be an instance of the class to have access to it.

A: Jacob is correct… a friend function declared within a class has access to that class, but it's not inside the class at all, and everyone else has access to it.
For an operator overload which is not a member of the class (also called a free function, it may be a friend, or maybe not), the arguments are the same as the operands. For one which is a member of a class, the first operand is the "implicit argument" which becomes this.
The implicit argument is different from the first argument to a free function in a few ways:

*

*Its type is reference-to-class, whereas the free function can declare any type for its first argument.

*It does not participate in implicit type conversion. (It will not be a temporary initialized by a conversion constructor.)

*It does participate in virtual override resolution. (A virtual overload will be chosen by the dynamic type of the first operand, which is not possible with free functions without extra code.)

The situation is the same for unary, binary, or n-ary (in the case of operator()).
Members privilege of mutation: Operators which change the first operand (eg +=, =, prefix ++) should be implemented as member functions, and should exclusively implement the guts of all overloads. Postfix ++ is a second-class citizen; it is implemented as Obj ret = *this; ++ this; return ret;. Note that this sometimes extends to copy-constructors, which may contain *this = initializer.
Rule of freedom for commuters: Only commutative operators (eg /) should be free functions; all other operators (eg unary anything) should be members. Commutative operators inherently make a copy of the object; they are implemented as Obj ret = lhs; ret @= rhs; return ret; where @ is the commutative operator and lhs and rhs are left-hand side and right-hand side arguments, respectively.
Golden rule of C++ friendship: Avoid friendship. friend pollutes the semantics of a design. Overloading corollary: Overloading is simple if you follow the above rules, then friend is harmless. friending boilerplate overload definitions allows them to be placed inside the class { braces.
Note that some operators cannot be free functions: =, ->, [], and (), because the standard specifically says so in section 13.5. I think that's all… I thought unary & and * were too, but I was apparently wrong. They should always be overloaded as members, though, and only after careful thought!

A: A member function requires that the left hand operator must be of that type.
A friend function can allow implicit casting on the left hand operator.
So for example, lets say we create a BigInt class. And we create a member function operator + to take a right hand operator of BigInt.
Now lets also say BigInt has a constructor that takes a regular int. This constructor is NOT explicit (explicit keyword) and it takes one parameter. That means C++ can implitily convert from int to BigInt.
When we have these things we can do this:
BigInt foo( 5 );
BigInt bar;
bar = foo + 5;
But we CAN'T do this:
BigInt foo( 5 )
BigInt bar;
bar = 5 + foo;
However, if we used a friend function instead of a member function then both will work.

A: A member function requires that the left hand operator must be of that type. A friend function can allow implicit casting on the left hand operator.

A: Member functions can be called on rvalues, whereas free functions accepting references to non-const cannot be called with rvalues. For example, ++function_returning_iterator_by_value() only compiles if you implement operator++ as a member.