text:
Q: Why can't I use the enumerator of an array, instead of implementing it myself? I have some code like this:
public class EffectValues : IEnumerable<object>
{
    public object [ ] Values { get; set; }

    public IEnumerator<object> GetEnumerator ( )
    {
        return this.Values.GetEnumerator ( );
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator ( )
    {
        return this.GetEnumerator ( );
    }
}

But the compiler complains saying:

"Cannot implicitly convert type
  'System.Collections.IEnumerator' to
  'System.Collections.Generic.IEnumerator'.
  An explicit conversion exists (are you
  missing a cast?)"

I thought the Array type implemented both IEnumerable interfaces, does it not? Because I can use Linq features on the Values instance directly.

A: This is a subtle and a bit unfortunate. The easy workaround is:
public IEnumerator<object> GetEnumerator ( )
{
     return ((IEnumerable<object>)this.Values).GetEnumerator ( );
}

I thought the Array type implemented both IEnumerable interfaces, does it not?

The rules are:

*

*System.Array implements IEnumerable "implicitly", with public methods.

*every array type T[] inherits from System.Array.

*every array type T[] implements IList<T>, IEnumerable<T> and so on.

*therefore every array type T[] is convertible to IEnumerable<T>
Notice that the third point was NOT

*

*every array type T[] implements IList<T>, IEnumerable<T> and so on with public methods and properties defined on T[] that implicitly implement the members
And there you go. When you look up GetEnumerator, we look it up on object[] and don't find it, because object[] implements IEnumerable<object> explicitly. It is convertible to IEnumerable<object>, and convertibility doesn't count for lookups. (You wouldn't expect a method of "double" to appear on int just because int is convertible to double.) We then look at the base type, and find that System.Array implements IEnumerable with a public method, so we've found our GetEnumerator.
That is, think about it like this:
namespace System
{
    abstract class Array : IEnumerable
    {
        public IEnumerator GetEnumerator() { ... }
        ...
    }
}

class object[] : System.Array, IList<object>, IEnumerable<object>
{
    IEnumerator<object> IEnumerable<object>.GetEnumerator() { ... }
    int IList<object>.Count { get { ... } }
    ...
}

When you call GetEnumerator on object[], we don't see the implementation that is an explicit interface implementation, so we go to the base class, which does have one visible.

How do all the object[], int[], string[], SomeType[] classes get generated "on the fly"?

Magic!

This is not generics, right?

Right. Arrays are very special types and they are baked in at a deep level into the CLR type system. Though they are very similar to generics in a lot of ways.

It seems like this class object [] : System.Array is something that can't be implemented by a user, right?

Right, that was just to illustrate how to think about it.

Which one do you think is better: Casting the GetEnumerator() to IEnumerable<object>, or just use foreach and yield?

The question is ill-formed. You don't cast the GetEnumerator to IEnumerable<object>. You either cast the array to IEnumerable<object> or you cast the GetEnumerator to IEnumerator<object>.
I would probably cast Values to IEnumerable<object> and call GetEnumerator on it.

I will probably use casting but I am wondering if this is a place where you or some programmer who could read the code, would think it's less clear.

I think it's pretty clear with the cast.

when you said implicit implementation, you mean in the form of Interface.Method, right?

No, the opposite:
interface IFoo { void One(); void Two(); }
class C : IFoo
{
    public void One() {} // implicitly implements IFoo.One
    void IFoo.Two() {} // explicitly implements IFoo.Two
}

The first declaration silently implements the method. The second is explicit about what interface method it implements.

What's the reason for implementing IEnumerable<T> like that, instead of implicit implementation with public methods? I got curious because you said "This is a subtle and a bit unfortunate", so it seems like it's because of an older decision that forced you to do this I imagine?

I don't know who made this decision. It is kind of unfortunate though. It's confused at least one user -- you -- and it confused me for a few minutes there too!

I would have thought the Array type would be something like this: public class Array<T> : IEnumerable<T> etc. But instead there is some magical code about it then, right?

Right. As you noted in your question yesterday, things would have been a lot different if we'd had generics in CLR v1.
Arrays are essentially a generic collection type. Because they were created in a type system that did not have generics, there has to be lots of special code in the type system to handle them.
Next time you design a type system put generics in v1 and make sure you get strong collection types, nullable types and non-nullable types baked in to the framework from the beginning.  Adding generics and nullable value types post hoc was difficult.

A: You have to cast the array to IEnumerable<object> to be able to access the generic enumerator:
public IEnumerator<object> GetEnumerator() {
  return ((IEnumerable<object>)this.Values).GetEnumerator();
}


text:
Q: iReport, use SQL instead HQL query with an hibernate connection i'm writing a query that need UNION and hql doesn't support it. So the only workaround is to use standrad SQL query but the problem is i can't use it in iReport if i use hibernate.
There is a way to use sql in iReport with an hibernate connection?
Thanks.

A: Use a View. See this: Hibernate Union alternatives

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android Development: How To Check If FTPFile Is a Directory? In my app I have a ListView which I populate with names of files and folders in a directory for my file browser.
I have overrid the getView method so that I can manually set a different icon in each row of the ListView depending on the child's file type, or if it's a directory or not.
Now if I were to check if a path on the sdcard is a directory I'd simply do:
if(new File("/sdcard/folder/path").isDirectory()){
 icon.setImageResource(R.drawable.foldericon);
}

But when dealing with FTPFile's that method doesn't seem to work.
Does anybody know how I can achieve the same outcome as the code above but with an FTPFile?


text:
Q: Navigate back to component, cannot refresh state I am trying to load the relevant video react-native-youtube standaloneplayer,  depending what params are passed to the component.
It works fine on first load, but when I click the back button and navigate back to the page using react-navigation and with a different id, the video is the same - how can I change the player with new props:
   <Text
      onPress={() => {
        NavigationService.navigate("VideoPlayer", { id });
      }}
      style={styles.text}
    >

My videoplayer component:
 class VideoPlayer extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
    };
  }

  render() {
    const { id: propId } = NavigationService.getParams();
    const { videos } = this.props;

    // videos is array of objects
    let videoProps = videos.find(obj => obj.id == propId);

    let { id, icon, title, description, youtubeVideo, preview } = videoProps;
    const url = `https://img.youtube.com/vi/${youtubeVideo}/0.jpg`;

    return (
      <View style={styles.container}>
        <TouchableOpacity
          onPress={() =>
            YouTubeStandaloneAndroid.playVideo({
              apiKey: "AIzaSyBXX5qe0B2hb1HzvIvExJZbqspeG9dg0Dk",
              videoId: youtubeVideo,
              autoplay: true,
              lightboxMode: true,
              startTime: 124.5
            })
              .then(() => console.log("Android Standalone Player Finished"))
              .catch(errorMessage => console.log(errorMessage))
          }
        >
          <Image style={styles.image} source={{ uri: url }} />
        </TouchableOpacity>
        <Text>{description}</Text>
      </View>
    );
  }
}

const mapStateToProps = state => {
  return {
    videos: state.videos
  };
};

A: You can try replacing navigate with the push action. The difference is that once a route from a stack is visited once, navigate will take you to it without mounting it again. With push you can mount the same route multiple times with different parameters. Here is more info from the official docs:
https://reactnavigation.org/docs/en/stack-actions.html#push


text:
Q: How print Body sent from proxy to client php? I use a php proxy through which I can make POST requests via CURL to the servers of a website.
$response = curl_exec($request);

if i print_r($response) i have a big output...Headers sent to proxy Host, Headers sent to target POST and Body sent from proxy to client but i want to print only Body sent from proxy to client.
How can i do this ?
Body sent is like:
{"errors":[{"message":"Lana","loc":[{"line":1,"column":1}],"path":["bufield"],"extensions":{"code":30056,"type":"FOR"}}],"data":{"bufield":null}}

i would to print only content of data

A: Try the following:
$response = curl_exec($request);

print_r(json_decode($response, true)["data"]);

// It should give you the following:
// {"bufield":null}


text:
Q: What C++ templates issue is going on with this error? Running gcc v3.4.6 on the Botan v1.8.8 I get the following compile time error building my application after successfully building Botan and running its self test:
../../src/Botan-1.8.8/build/include/botan/secmem.h: In member function `Botan::MemoryVector<T>& Botan::MemoryVector<T>::operator=(const Botan::MemoryRegion<T>&)':
../../src/Botan-1.8.8/build/include/botan/secmem.h:310: error: missing template arguments before '(' token

What is this compiler error telling me?  Here is a snippet of secmem.h that includes line 310:
[...]
/**
* This class represents variable length buffers that do not
* make use of memory locking.
*/
template<typename T>
class MemoryVector : public MemoryRegion<T>
   {
   public:
      /**
      * Copy the contents of another buffer into this buffer.
      * @param in the buffer to copy the contents from
      * @return a reference to *this
      */
      MemoryVector<T>& operator=(const MemoryRegion<T>& in)
         { if(this != &in) set(in); return (*this); }  // This is line 310!
[...]

A: Change it to this:
{ if(this != &in) this->set(in); return (*this); }

I suspect that the set function is defined in the base-class? Unqualified names are not looked up in a base class that depends on a template parameter. So in this case, the name set is probably associated with the std::set template which requires template arguments.
If you qualify the name with this->, the compiler is explicitly told to look into the scope of the class, and includes dependent base classes in that lookup.


text:
Q: Add cells to range of columns only I am attempting to write a macro (new to VBA/writing code) that will add a value to an existing list (Col B).  The value is defined by an InputBox then added in the list in alphabetical order.  I am able to get the macro to work, however I would like to add cells in a range instead of an entire row.
My spreadsheet has data in columns A through K.  This is the area that I want to insert a 'row' into.  There is a catch however.  I have another set of data in columns L through AF which I do not want to add the row to.  This is where I have failed as I am only able to insert a complete row.
Is there a way to do this?  I have not run across any methods that seem to work as the insert must happen based on the new value's position in the list (alphabetically) which prevents me from selecting the location to insert.  I have tried recording macros to view the code and am unable to manipulate that input due to the selection being defined by the value.
Here is the code that I have so far...may be a bit clunky as I am still learning.
Sub Add_Project()
Dim NewProject As String, iRow As Long, ProjRng As Range, RowRng As Range
'The ProjRng MUST represent the project column!
    Set ProjRng = Range("B:B")
'Defines the range of columns to add a row to
    Set RowRng = Range("B:K")
'Create message box for user input on project name
    NewProject = InputBox("Enter Project Name")
    If NewProject = "" Then Exit Sub
'Determines if the New Project name already exists
    iRow = Application.WorksheetFunction.Match(NewProject, ProjRng)
    If Cells(ProjRng.row + iRow - 1, ProjRng.Column) = NewProject Then
        MsgBox ("Project already exists")
Exit Sub
    End If
'Inserts a new row with containing the new Project name
    With Cells(ProjRng.row + iRow, ProjRng.Column)
        .EntireRow.Insert
        .Offset(-1, 0).Value = NewProject
    End With
Exit Sub
End Sub

I realize that the macro is doing what I have instructed it to do.  I would like to manipulate the section adding an "EntireRow" with something that only adds to the range of column A:K.  Any suggestions or pointers as to where I could get started would be much appreciated.
Thanks!

A: Sub Add_Project()

    Dim strNewProject As String
    Dim iRow As Long

    strNewProject = InputBox("Enter Project Name")
    If Len(strNewProject) = 0 Then Exit Sub 'Pressed cancel

    If WorksheetFunction.CountIf(Columns("B"), strNewProject) > 0 Then
        MsgBox "Project already exists"
        Exit Sub
    End If

    iRow = WorksheetFunction.Match(strNewProject, Columns("B")) + 1
    Intersect(Range("A:K"), Rows(iRow)).Insert xlShiftDown
    Cells(iRow, "B").Value = strNewProject

End Sub


text:
Q: How do I specify dtype with read_csv for data and index independently I am trying to specify the dtype of the values when loading a pandas dataframe, but only for the values in the dataframe, not the index. Is this possible?
from io import StringIO
my_csv = StringIO('''b, c\nx, 1, 2\ny, 3, 2''')

I would have assumed the following would work:
pd.read_csv(my_csv, dtype='int64')

But if fails with:
ValueError: invalid literal for int() with base 10: 'x'

I can load the table without specifying dtype and then set it to just the values, but is there a way I can do this directly when reading the table?

A: One method would be to read just the header to get the column names and then zip them with your desired dtype and read the csv again:
In [6]:
t="""b,c
x,1,2
y,3,2"""
cols = pd.read_csv(io.StringIO(t), nrows=1).columns
dtyp = dict(zip(cols,['int64'] * len(cols)))
pd.read_csv(io.StringIO(t), dtype=dtyp).info()

<class 'pandas.core.frame.DataFrame'>
Index: 2 entries, x to y
Data columns (total 2 columns):
b    2 non-null int64
c    2 non-null int64
dtypes: int64(2)
memory usage: 48.0+ bytes


text:
Q: Efficient modular exponentation of powers Is there any way to efficiently compute $(((\mathrm{base}^{M_1})^{M_2})^{M_3} \dots )^{M_n}$ modulo $P$, where $P$ is prime? One way is to repeatedly do modular exponentiation for each of the powers. Another way, we could compute the Multiplicative order and powers thereafter would just be 1. Are there any alternative ways to do this efficiently?

A: IF $P$ divides $b,$ the remainder will be $0$
Else  $(b,P)=1$
$$((b^{M_1})^{M_2})^{M_3}\cdots)^{M_n}=b^{M_1\cdot M_2\cdot M_3\cdots M_n}$$
As $P$ is prime, $a^{P-1}\equiv\pmod P$ if $(a,P)=1$ using Fermat's Little Theorem.
So, we need to find $M_1\cdot M_2\cdot M_3\cdots M_n\pmod {(P-1)}$
Then use repeated exponentiation.


text:
Q: Gamma function Eulera I have gamma function Eulera.
Can I write that $\Gamma (n+3)=\Gamma((n+1)+2)=\Gamma(n+1)+\Gamma(2)=n!+1$?
And I'm not sure whether $\Gamma(2)=1$?

A: You began well by writing $\Gamma\big(n+3\big)=\Gamma\Big(\big(n+2\big)+1\Big).~$ Now apply $\Gamma\big(x+1\big)=x~\Gamma\big(x\big).~$ Then repeat the process.


text:
Q: How to I reshape the 2D array like this? (By using tensor) I want to resize my image from 32 * 32 to 16 * 16. (By using torch.tensor)
Like decreasing the resolution?
Can anyone help me?

A: If you have an image (stored in a tensor) and you want to decrease it's resolution, then you are not reshaping it, but rather resizing it.
To that end, you can use pytorch's interpolate:
import torch
from torch.nn import functional as nnf

y = nnf.interpolate(x[None, None, ...], size=(16, 16), mode='bicubic', align_corners=False, antialias=True)

Notes:

*

*nnf.interpolate operates on batches of multi-channel images, that is, it expects its input x to have 4 dimensions: batch-channels-height-width. So, if your x is a single image with a single channel (e.g., an MNIST digit) you'll have to create a singleton batch dimension and a singleton channel dimension.

*Pay close attention to align_corners and antialias -- make sure you are using the right configuration for your needs.

For more information regarding aliasing and alignment when resizing images you can look at ResizeRight.

A: you can use resize from torchvision transforms:
import torchvision.transform as T
T.Resize(16)(your_image)

you can also chain it to other transforms
preprocess = T.Compose([
   T.Resize(N),
   T.CenterCrop(N),
   T.ToTensor(),
   T.Normalize(
       mean=mean,
       std=std
   )
])
preprocess(your_image)


text:
Q: JQuery Unbind and then bind I've found lots of examples on this topic.. however, I do not fully understand.  Does my logic seem correct?  I have a div as button (class of .myClass) and I don't want it clickable unless myCount >= 1.
// I want to unbind if myCount == 0
if ( myCount == 0) {
 $('.myClass').unbind().css("opacity","0.5");
} else {
 // **would this rebind?**
 $('.myClass').click(callMyFunction);
}

A: I'm not sure exactly what you're trying to achieve, but .unbind() removes all handlers attached to the element when called with no arguments. Therefore, $('.myClass').unbind() removes all event handlers attached to the elements with a class of .myClass. Since you only seem to be adding one event handler, click, it would be better to only unbind the click handler, like so: $('.myClass').unbind('click'). This way you won't be confused why other events are being unbinded if you add additional events later on.

A: click(callMyFunction) is shorthand for .bind("click", callMyFunction) or .on("click", callMyFunction).
To bind use on() to unbind use off(). Those are the preferred methods since jQuery 1.7. If you are using an older version use bind(), unbind(), or delegate() and undelegate()
$('.myClass').off('click')

and to bind
$('.myClass').on('click', function(){});

As mentioned in another post, using namespaces is an additional way to categorize your events such as click.mynamespace for example.
See this post for much more detail on the different available binding methods and which were introduced when and have replaced what and why.
Some more resources:

*

*click()

*unbind()

*on()

*off()

A: You could use namespaced events, with on(). bind() has been deprecated.
var foo = function () { ... }

if (myCount)
  $('.myclass').on('click.foo', foo)
else
  $('.myclass').off('.foo')


text:
Q: Focus box on lightning:input When the input element is 'focused' (currently selected/tabbed) , Chrome puts a blue border around it. And I just can't figure out how I can get this away. I think the browser is putting it there. But I can't get the right style to overwrite it. Any experience with this? Thanks
Code:
< lightning:input aura:id="firstName"   value="{!v.something}" class="slds-input slds-input_bare " name="Name" label="First Name" onchange="{!c.doSomething}" />

A: The blue border is added by the lightning design system on the slds-input class like this:
.slds-input:focus, .slds-input:active {
    outline: 0;
    border-color: rgb(21, 137, 238); /* This is the blue color of the border */
    background-color: rgb(255, 255, 255);
    box-shadow: 0 0 3px #0070d2; /* This is the blue color of the shadow */
}

If you want to remove it you can override the color. Here's an example with the default color:
.THIS .slds-input:focus, .THIS .slds-input:active {
     border-color: rgb(216, 221, 230);
     box-shadow: none;
}


text:
Q: Broadcom BCM4356 driver I just received a lenovo T460S with Broadcom 4356 wireless adapter.
Is there any driver available for this adapter ?
I tried the traditionnal bcmwl-kernel-source package but it did not work.
Do you know if there is any official driver available somewhere or if any other broadcom driver would work ?
Thanks :)
$ lspci -vvnn | grep -A9 Network
04:00.0 Network controller [0280]: Broadcom Corporation BCM4356 802.11ac Wireless Network Adapter [14e4:43ec] (rev 02)
    Subsystem: Lenovo Device [17aa:0777]
    Control: I/O- Mem+ BusMaster- SpecCycle- MemWINV- VGASnoop- ParErr- Stepping- SERR- FastB2B- DisINTx-
    Status: Cap+ 66MHz- UDF- FastB2B- ParErr- DEVSEL=fast >TAbort- <TAbort- <MAbort- >SERR- <PERR- INTx-
    Interrupt: pin A routed to IRQ 18
    Region 0: Memory at f1400000 (64-bit, non-prefetchable) [size=32K]
    Region 2: Memory at f1000000 (64-bit, non-prefetchable) [size=4M]
    Capabilities: <access denied>

$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 15.10
Release:    15.10
Codename:   wily

$ uname -a
Linux gimly 4.2.0-30-generic #35-Ubuntu SMP Fri Feb 19 13:52:26 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

A: Your device is covered by the driver brcmfmac in Ubuntu 15.10. It also requires firmware that is included in linux-firmware-1.149 and later. Let's install the latest firmware first. Download this package to any convenient place. https://launchpad.net/ubuntu/+source/linux-firmware/1.156/+build/9020816/+files/linux-firmware_1.156_all.deb Right-click it and select 'Open with Ubuntu Software Center' and install it.
Now open a terminal and do:
sudo apt-get purge bcmwl-kernel-source
sudo modprobe -r brcmfmac

The last command may end in an error; that's fine, just continue:
sudo modprobe brcmfmac

The wireless should now be working.

A: I'm running a Lenovo T560 with Broadcom 4356 on Kubuntu 18.04.1 LTS and using linux-firmware_1.156, wireless works. But, when updating packages, all newer linux-firmware in use, disconnected me from wireless.
So I just followed the steps mentioned above and afterwards, I put the package on hold:
sudo apt-mark hold linux-firmware

Thus, the package stays at the same version (1.156).
At some point there may be linux-firmware, that supports Broadcom 4356 again, then simply replace "hold", with "unhold" in that CLI command and then run the update.


text:
Q: Webpage is responsive in chrome's inspect but fails on real phone I'm facing an issue with my webpage: I have a webpage which I want to be responsive on mobile phones.

I tried
<meta name="viewport" content="width=device-width, initial-scale=1.0">

and all CSS attributes like width:100% and max-width and so on And the issue is: when I use chrome's inspect to simulate webpage on phone, it shows up correctly but when I access through real mobile phone, it fails (It shows up like a desktop version, No responsiveness)

HTML Codes
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Love calculator | Home</title>
    <link rel="stylesheet" type="text/css" href="style.css">

        <form method="POST" enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">

Your Name

                    <input type="text" placeholder="Your name" required name="firstname">

Partner's Name

                    <input type="text" placeholder="Partner's Name" required name="lastname">

            <input type="submit" value="" name="submit" style="border: medium none ; background: transparent url(img/calculate.png) repeat scroll 0% 0%; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous; width: 131px; height: 52px;">

</form>

STYLE.CSS
*{
    margin: 0;
    padding: 0;
    user-select: none;
}
body{
    background-image: url(img/bg-love.jpg);
    background-repeat: no-repeat;
}
.wrapper{
    width: 100%;
    max-width: 680px;
    margin: 10px auto 0;
    padding: 20px;
    box-sizing: border-box;
}
.content{
    text-align: center;
    width: 100%;
}
.submitbtn{
    width: 100%;
}
.content h1{
    letter-spacing: 1px;
}
.form{
    width: 100%;
    margin: 25px 0;

}
.top-form,
.middle-form,
.bottom-form{
    width: 100%;
    min-height: 65px;
    margin: 30px 0;
    overflow: hidden;
}
.form input[type="text"],
.form textarea{
    padding: 15px 5px;
    box-sizing: border-box;
    width: 100%;
    border: 2px solid #fff;
    border-radius: 2px;
    outline: none;
    transition: all 0.2s ease;

}
.form input:focus,
.form textarea:focus{
    border-color: #4ca1af;
    box-shadow: inset 0 1px 1px rgba(0,0,0, 0.0125),
        0 0 8px rgba(76,161,175,0.5);

}
.form .label{
    margin-bottom: 5px;
    text-transform: capitalize;
    color: white;
    font-weight: bold;
    font-family: sans-serif;

}
.top-form .inner-form{
    width: 29.9%;
    float: left;
    margin-right: 5%;
}
.top-form .inner-form:last-child {
    margin-right: 0;
}

.middle-form{
    clear: both;
}
.bottom-form textarea{
    height: 60px;

}
.btn{
    background: #4ca1af;
    width: 200px;
    padding: 10px 0;
    border-radius: 2px;
    text-align: center;
    text-transform: uppercase;
    color: #fff;
    letter-spacing: 5px;
    cursor: pointer;
}
::-moz-input-placeholder{
    text-transform: capitalize;
}
::-ms-input-placeholder{
    text-transform: capitalize;
}
#targetDiv{
    align: center;
    z-index: 4;
    color:   #FFFFFF;
    width:   133;
    font-size: 28px;
    }

@media screen and (max-width: 460px){
    .img {
        width: 100%;
    }
    .wrapper{
        margin: 25px auto 0;
    }
    .top-form .inner-form{
        width: 100%;
        margin: 5px 0;
    }

}

Why could this happen? can background image affect responsiveness!?

A: You can add shrink type in the content of viewport like the following
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

or just use one of following media query for smartphone
portrait
/* Smartphones (portrait) ---------- */
@media screen and (max-width: 320px){
 /* styles */
}

landscape
/* Smartphones (landscape) ---------- */
@media screen and (min-width: 321px){
 /* styles */
}

both portrait and landscape
/* Smartphones (portrait and landscape) ---------- */
@media screen and (min-width: 320px) and (max-width: 480px){
 /* styles */
}

And if the problem is still there try to alter many possible html elements inside the media query in the way that makes sense and check your browser as well or try another smart phones.
Or you can try another way using JavaScript if you know some.

in JavaScript there is function called window.matchMedia() which helps you to work with media queries in JavaScript and the following is the syntax
if (window.matchMedia('only screen and (max-width: 480px)').matches) {
// style here
}

A:
Can background image affect responsiveness!?

Yes, it can. Consider using the background-size property on your affected div:
body{
    background-image: url(img/bg-love.jpg);
    background-size: cover;
    background-repeat: no-repeat;
}

This is only one of the possible issues though. Try adjusting that and see if anything improves.


text:
Q: `delete[]` on `int*` allocated with `new` gives malloc error Following my understanding of C++ convention, I have:
class BlockRepresentation : public FPRepresentation
{
    private:
        class Block
        {
            public:
                int id;
                int fpDimensions;
                int* position;        // pointers in question
                int* blockDimensions; // pointers in question

                ~Block();
        };
        std::vector<Block> all_blocks;

    public:
        BlockRepresentation( int count, int dimensions, int volumn[] );
        void AddBlock( int id, int position[], int dimensions[] );
        std::string ToGPL();
};

where new blocks are created in AddBlock:
void BlockRepresentation::AddBlock( int id, int position[],
        int dimensions[] )
{
    Block newBlock;

    newBlock.id = id;
    newBlock.fpDimensions = fpDimensions;
    newBlock.position = new int[fpDimensions];        // pointers in question
    newBlock.blockDimensions = new int[fpDimensions]; // pointers in question

    for (int i = 0; i < fpDimensions; ++i)
    {
        newBlock.position[i] = position[i];
        newBlock.blockDimensions[i] = dimensions[i];
    }

    all_blocks.push_back( newBlock );
}

so I have the following destructor:
BlockRepresentation::Block::~Block()
{
    delete[] position;
    delete[] blockDimensions;
}

but then I get:
rep_tests(11039,0x7fff71390000) malloc: *** error for object 0x7fe4fad00240: pointer being freed was not allocated

Why should I not delete[] the 2 pointers here?

A: As was pointed out in the comments, you violated the rule of three, and the violation is very obvious:
{
    Block newBlock;

    // snip

    all_blocks.push_back( newBlock );
}

When this function returns, the newBlock object goes out of scope, and its destructor will delete all the newed arrays.
But you push_back()ed this object. This constructs a copy of the object into the vector. Because your Block does not define a copy constructor, the default copy-constructor simply makes a copy of all the pointers to the newed arrays.
If you somehow manage to avoid dereferencing the no-longer valid pointers, or you survived that experience, you're not of the woods yet. That's because, when the vector gets destroyed, and its Blocks get destroyed, their destructors will, once again, attempt to delete the same newed arrays that were already deleted once before.
Instant crash.

A: There is nothing wrong with your Block destructor.  It is doing its job, which is releasing the memory that is pointed to by your two int * member variables.  The problem is that the destructor is being called on the same pointer value multiple times, which results in a double-free error.
The entity that causes this is the std::vector<Block>, since a std::vector will make copies of your Block object, and your Block object is not safely copyable.
Since the member variables of Block that are pointers are position and blockDimensions, the most painless way to alleviate this issue is to use std::vector<int> instead of int *, as demonstrated by this sample program.
However, if you really wanted to use int *, you would need to implement a user-defined copy constructor.  In addition, a user-defined assignment operator would complement the copy constructor.  This is what is called the Rule of Three.
 #include <algorithm>
 //...
 class Block
 {
    public:
       int id;
       int fpDimensions;
       int *position;
       int *blockDimensions;

       Block() : position(nullptr), blockDimensions(nullptr),
                 id(0), fpDimensions(0) {}
      ~Block()
      {
          delete [] position;
          delete [] blockDimensions;
      }

      Block(const Block& rhs) : id(rhs.id), fpDimensions(rhs.fpDimensions),
                                position(new int[rhs.fpDimensions]),
                                blockDimensions(new int[rhs.fpDimensions])
      {
         std::copy(rhs.position, rhs.position + fpDimensions, position);
         std::copy(rhs.blockDimensions, rhs.blockDimensions + fpDimensions,
                   blockDimensions);
      }

      Block& operator=(const Block& rhs)
      {
         Block temp(rhs);
         std::swap(temp.position, position);
         std::swap(temp.blockDimensions, blockDimensions);
         std::swap(temp.id, id);
         std::swap(temp.fpDimensions, fpDimensions);
         return *this;
      }
  };

See the live sample here.
See all of the hoops we had to jump through to get the Block class to behave correctly when used within a std::vector, as opposed to simply using std::vector<int>?


text:
Q: Select Earliest Date from List of Distinct Employee numbers SELECT
    a1.[employee_number],
    a1.[class_id],
    a1.[TraineeAddedOn],
    a1.[TraineeRemovedOn],
    a1.[effective_start_date],
    a2.REHIRE
FROM TrainingAnalytics_Staging..VW_FACT_TRAINING_USER_INFO a1
LEFT JOIN DW..[VW_DIM_EMPLOYEE_DETAIL] a2 ON a1.employee_number = a2.employee_number
GROUP BY a1.class_id
HAVING MIN(a1.TraineeAddedOn)

I'm using this query but getting this error:

An expression of non-boolean type specified in a context where a
  condition is expected, near ')'.

A: Try below query
   SELECT Top 1 a1.[employee_number], a1.[class_id], a1.[TraineeAddedOn],
           a1.[TraineeRemovedOn], a1.[effective_start_date], a2.REHIRE
    FROM TrainingAnalytics_Staging..VW_FACT_TRAINING_USER_INFO a1
    LEFT JOIN
            DW..[VW_DIM_EMPLOYEE_DETAIL] a2
        ON a1.employee_number = a2.employee_number
    ORDER BY a1.TraineeAddedOn

A: Basically you are trying to get the min TraineeAddedOn for each employee?
I think something like this would do:
-- First get list of min date per employee
With MinDatePerEmploye AS
(
SELECT employee_number, MIN(TraineeAddedOn) AS MinTraineeAddedOn
FROM TrainingAnalytics_Staging..VW_FACT_TRAINING_USER_INFO
GROUP BY employee_number
)
-- and now join that up with rest of dataset
SELECT
    a1.[employee_number],
    a1.MinTraineeAddedOn,
    a2.[class_id],
    a2.[TraineeAddedOn],
    a2.[TraineeRemovedOn],
    a2.[effective_start_date],
    a2.REHIRE
FROM MinDatePerEmploye a1
INNER JOIN TrainingAnalytics_Staging..VW_FACT_TRAINING_USER_INFO a2
ON a1.employee_number = a2.employee_number AND a1.MinTraineeAddedOn = a2.TraineeAddedOn


text:
Q: Reflect on Gremlin traversal type (Edge, Vertex, Property) in CHOOSE step, possible? I am extending sparql-to-gremlin code to support fully and partially unbound predicate queries that can be used by automated processes to explore the graph structure. The idea being that you could just connect to some graph DB and ask a fully unbound query with some limit and get vertex properties, edge types, edge properties, etc. That can then be explored more.
I can now solve a fully unbound query and can solve one that has the subject bound to a vertex. Now I am trying to put it together into a multi-literal query and finding that the Gremlin MATCH Step would need to reflect on the type of Traversal before it can decide which steps would actually apply. For example if, the Traversal results in a Vertex, asking for out/in edges and properties makes sense; if it's an Edge though, asking for out/in edges does not make sense and actually results in errors about unexpected type being thrown.
Thus the question, is it possible to write a kind of "switch" statement that would reflect on the type and then only ask for things that makes sense in that context?
Here's one type of SPARQL query that I am trying to support (based on the Graph of the Gods described here https://old-docs.janusgraph.org/0.1.0/getting-started.html):
https://old-docs.janusgraph.org/0.1.0/images/graph-of-the-gods-2.png
SELECT ?BATTLE ?PRED ?VALUE
WHERE {
    vid:6 ep:battled ?BATTLE .
    ?BATTLE ?PRED ?VALUE .
}

Here we are starting from a vertex with id 6, grabbing the outgoing edge reference with "battled" label, then grabbing all possible properties of the edge along with their values.
Here vertex with id 6 is Hercules, which has 3 outgoing edges with label "battled" going to vertex with id 9 (Nemean), 10 (Hydra) and 11 (Cerberus). I would want to the have ?PRED be bound to v:id (edge id), v:label (edge label), v:time (edge time property value), v:place (edge place property value), eps:battled (an extension to sparql-to-gremlin relating edge to an IN vertex).

A: I think that I follow your problem and I don't think I have a good answer for you. At the moment, Gremlin isn't terribly good with type detection and the issue remains open on TINKERPOP-2234. The typical workaround for most people when they have a mixed set of elements in a stream is to use a step like coalesce() or choose() to act as a form of switch statement and then figure out some filter than can identify the object type. So here's some mixed results that I've contrived:
gremlin> g.V().union(outE(),__.in())
==>e[9][1-created->3]
==>e[7][1-knows->2]
==>e[8][1-knows->4]
==>v[1]
==>v[1]
==>v[4]
==>v[6]
==>e[10][4-created->5]
==>e[11][4-created->3]
==>v[1]
==>v[4]
==>e[12][6-created->3]

and then I test with hasLabel() for labels I know to belong to vertices only, then everything else must be an edge:
gremlin> g.V().union(outE(),__.in()).choose(hasLabel('person','software'), values('name'), values('weight'))
==>0.4
==>0.5
==>1.0
==>marko
==>marko
==>josh
==>peter
==>1.0
==>0.4
==>marko
==>josh
==>0.2

Not ideal obviously but it typically resolves most people's problems. Hopefully we will see TINKERPOP-2234 solved for 3.5.0.
Another possible workaround is to use a lambda which works well for some use cases though we try to avoid them when possible:
gremlin> g.V().union(outE(),__.in()).choose(filter{it.get() instanceof Vertex}, values('name'), values('weight'))
==>0.4
==>0.5
==>1.0
==>marko
==>marko
==>josh
==>peter
==>1.0
==>0.4
==>marko
==>josh
==>0.2


text:
Q: The "XamarinDownloadArchives" task could not be initialized with its input parameters I am getting two error while Compiling Xamarin.iOS application on Visual Studio Mac (Version 8.4.3 (build 12)).
Xamarin.Forms 4.4.0.991640
Xamarin.Build.Download.0.9.0
Error :
1.packages/Xamarin.Build.Download.0.9.0/build/Xamarin.Build.Download.targets(3,3):
Error MSB4063: The "XamarinDownloadArchives" task could not be initialized with its input parameters.  (MSB4063)
**2.**packages/Xamarin.Build.Download.0.9.0/build/Xamarin.Build.Download.targets(4,4):
Error MSB4064: The "AllowUnsecureUrls" parameter is not supported by the "XamarinDownloadArchives" task. Verify the parameter exists on the task, and it is a settable public instance property. (MSB4064)

A: As suggested byb an answer in https://stackoverflow.com/a/59202701/10627299, restarting the visual studio fixed the issue.

A: In my case it was due to Xamarin.Build.Download versions mismatch: some projects used 0.10.0 and some others used older 0.4.1 which caused the old nuget's msbuild task to be loaded

A: I got this after I paired my Mac. I did a Clean and a Rebuild on the Android Project and it worked for me again.

A: Try downgrading Xamarin.Build.Download on Nuget, in my case using 0.8.0 worked fine.

A: For me, it worked when I changed the Android Project compiler setting -
Debug Information from 'Full' to 'None'.
Although it doesn't allow breakpoints in Android project when done so, I'm at least able to compile both iOS & Android projects without any issue.
When I'm dedicatedly working on the Android project, I change the setting back to 'Full' and then revert it to 'None' once done.


text:
Q: How to clone a user's settings I have to set up a bunch of computers and a bunch of user accounts to set up on Ubuntu Gnome.
I'd like to set up a standard 'skel'eton as a base for new accounts. Here's what I've done so far.

*

*Created a skel user and set up the desktop as I want it.

*Copy the /home/skel files to /etc/skel

*Dump the dconf settings for this user
dconf dump / >skel_settings

*Add user adduser test1

*Login as test1 and re-import the settings
dconf load / <skel_settings

But this still misses some details, e.g. shell extensions are missing and the default applications for opening Directories is wrong.
Is there a better/fuller way?
EDIT
actually, I think this works! Think I did something wrong with rsync...


text:
Q: $\rho=\sqrt{\frac{R+j \omega L}{G+j \omega C}}$, find the condition to have $Re\{\rho\}\ge0$ and $Im\{\rho\}\ge0$ $$\rho=\sqrt{\frac{R+j \omega L}{G+j \omega C}} \qquad R,G \ge 0 \qquad \omega,L,C>0 $$

$$\rho=\sqrt{\frac{(R+j \omega L) \ (G-j \omega C)}{G^2+\omega^2C^2}}$$
$$\rho=\sqrt{\frac{RG+j \omega LG-j\omega RC+\omega^2 LC}{G^2+\omega^2C^2}}$$
$$0 \le \arctan\Big( \frac{\omega LG-\omega RC}{RG+\omega^2LC} \Big) \le \frac{\pi}{2}$$
Is it correct?
Thanks!

A: Hint.
$$
|\rho| = \sqrt{\frac{L^2 \omega ^2+R^2}{C^2 \omega ^2+G^2}}
$$
and
$$
\angle \rho = \frac 12\arctan{\left(\frac{(GL-CR)\omega}{CL \omega^2+GR}\right)}
$$
then $\Re(\rho) \ge 0 $ and $\Im(\rho) \ge 0 $ implies on
$$
0 \le \frac 12\arctan{\left(\frac{(GL-CR)\omega}{CL \omega^2+GR}\right)}\le \frac{\pi}{2}
$$
NOTE
$$
z = \rho e^{i\phi}\to \sqrt z = \rho^{\frac 12} e^{\frac i2 \phi}
$$


text:
Q: Scene2d: How to place a widget at the bottom of the screen and another one at the top? I want to have a ScrollPane with two Labels  above a Button which always stays at the bottom of the screen. This is working fine if there is so much text inside these labels, that scrolling is possible. But if there are only a few lines, the button stays right under the ScrollPane and so it may happen that the Button is at the middle of the screen.
Here's my code:
    Table container = new Table();
    container.setFillParent(true);
    container.top();

    Table table = new Table();

    ScrollPane scrollPane = new ScrollPane(table);
    scrollPane.setOverscroll(false, false);

    Label label1 = new Label(text1, labelStyle);

    Label label2 = new Label(text2, labelStyle);
    label2.setWrap(true);

    Button button = new Button(buttonStyle);

    table.add(label1).pad(paddingText);
    table.row();
    table.add(label2).pad(0, paddingText, 0, paddingText).width(stage.getViewport().getWorldWidth() - 2 * paddingText);

    container.add(scrollPane);
    container.row();
    container.add(button).pad(paddingButton).bottom();

    stage.addActor(container);

It should look like this:

A: Take a look at the Cell#fill and Cell#expand methods:
table.add(...).fillY().expandY();

This will expand the cell on the Y-Axis and fill it.


text:
Q: Python + Jinja2 displaying data from json I am trying to build a basic site to list podcast episodes. Data about the episodes is stored in a single json file (there are not many episodes yet).
I am using Python and Jinja2 to build the site. However, I am running into a not especially helpful error message when I try to render the page, passing the decoded json as a parameter.
http://pod.luketimoth.me/site/index.py This will show the error: dictionary update sequence element #0 has length 7; 2 is required which I don't find especially helpful. What is a dictionary update sequence? Why is element #0 required to be of size 2? Surely it can be whatever size I define it to be?
The json file is stored here: http://pod.luketimoth.me/site/data/episodes.json

A: I fixed it. Turns out the Json file cannot be just an anonymous array. I had to wrap the array in an object first. As you will see if you click the link to the json file.


text:
Q: DDD - transactions with services, repositories and aggregates I have a root aggregate Orders. Orders have line items. I have a repository of type IOrderRepository, which has methods like GetOrderName, GetAllOrdersItems, AddLineItem, RemoveLineItem, CountOrderItems.
Let's say I am using SQL. I use 2 tables - Orders and OrderItems. For some reason, let's assume I decide to have a field order_item_count on Orders. Whenever the user adds or removes a line item we update this count. Therefore I need to have this count updated atomically at the same time we add or remove a line item.
This means I should use transactions - I want my persistence to be such that if I update one table I update both tables (we don't want a line item to be added to OrderItems but a concurrent request also removes LineItems and the Order table count field to be wrong). But how does this fit into the services, repositories and aggregates setup. My feeling is that it shouldn't touch the aggregates (domain), as that breaks the idea of persistence ignorance. Should it be in the services*. Would the service be responsible for injecting a database transaction object into into my implementation of IOrderRepository, call it OrderSQLRepository
If it's in the services that means the services needs to know details about the domain, such as when we should construct an OrderSQLRepository with a transactions and when it should not. Cases where we might not want to use a transaction is when the domain is just going to call IOrdersRepository.GetAllOrdersItems IOrdersRepository.GetOrderName.
If we started using a noSQL database and use OrderNoSQLRepository where there is only the Order table and OrderItems is now just a document on the Order tables, is it correct that the service application would know that we don't need to use transactions here.
Thank you
FYI, I read How handle database Transactions in DDD if Repositories need handle more than one table for get or persist a Domain Model? which was helpful, but I still have remaining questions

*

*and if so domain or application services


text:
Q: NSTask completion How do I provide a callback to know when a task has completed? Do I need to set up an NSRunLoop or something?
ObjC.import('Cocoa');

exec("/usr/bin/say",["hello"])
function done(notification) {
    $.NSLog('Application done');
    $.NSLog(notification);
}
function exec(cmd,args){
    var task = $.NSTask.alloc.init
    task.launchPath=cmd
    task.arguments=args
    task.terminationHandler = $(done) // does not work!
    task.launch
    $.NSLog("running: "+task.running)
    return task
}

PS The language is JavaScript for Automaton, a new OSASCRIPT language for Yosemite OS X 10.10

A: I'm not sure if you have tried this, but maybe is worth it to give it a shot and see if it works for you..
I think, you could try using one of these two functions.. as $.performSelector... and see if it works for you..
[self performSelectorOnMainThread:@selector(myTask) withObject:nil waitUntilDone:YES];

[self performSelector:@selector(myTask) onThread:[NSThread mainThread] withObject:nil waitUntilDone:YES];

I hope it helps..


text:
Q: iOS reset float after button press I have an app that tracks your speed and altitude. How it works is when you press a start button it starts tracking you and when you press stop it stops and when you press reset it clears everything and the start button comes back. How I did this is I have a hidden label that shows the speed and when you press the button it is not hidden and when you press stop it is hidden again and I make another label say the last thing it said. I also have a max speed label that shows the top speed you reached. I did this using a float. I have the same thing happen for the max speed label that when you press reset the label that has the last thing the max speed label says clears and then the max speed label comes back when you press start. The problem I have is the max speed label itself doesn't reset. When I press start again the max speed label will still show what it had the last time. So how do I reset the max speed label float when the button is pressed to reset it?
EDIT
Here is the code that I have used...
to reset the label...
maxspeedlabel.text = @"0.00";

for the float...
- (void)locationUpdate:(CLLocation *)location {
speedLabel.text = [NSString stringWithFormat:@"%.2f", [location speed]*2.236936284];
altitudeLabel.text = [NSString stringWithFormat:@"%.2f", [location altitude]*3.2808399];
latitudeLabel.text = [NSString stringWithFormat:@"Lat: %f", location.coordinate.latitude];
longitudeLabel.text = [NSString stringWithFormat:@"Long: %f", location.coordinate.longitude];
errorlabel.text = @"   ";

  float currentSpeed = [location speed]*2.236936284;
if(currentSpeed - maxSpeed >= 0.01){
    maxSpeed = currentSpeed;
    maxspeedlabel.text = [NSString stringWithFormat: @"%.2f", maxSpeed];

}

float currentAltitude = [location altitude]*3.2808399;
if(currentAltitude - maxAltitude >= 0){
    maxAltitude = currentAltitude;
    maxaltitudelabel.text = [NSString stringWithFormat: @"%.2f", maxAltitude];
}

}
Thanks

A: Every time start is pressed add maxspeedlabel.text = @""; to clear the label and then update with the new one when needed.

A: currentSpeed - maxSpeed >= 0.01

Why this comparison? Should you not use
if(currentSpeed=>maxSpeed)

and I believe
maxSpeed = currentSpeed;
maxspeedlabel.text = [NSString stringWithFormat: @"%.2f", maxSpeed];

is wrong, I think it should be
currentSpeed = maxSpeed;
maxspeedlabel.text = [NSString stringWithFormat:@"%.2f", maxSpeed];

otherwise you would be setting your maxSpeed higher, which would probably be incorrect.
The error might be in the currentSpeed calculation, have you checked whether or not it enters the if statement?

A: I figured it out. I had to set the float to 0 when I tapped the button...
maxSpeed = 0;


text:
Q: Windows 2008 R2 NTFS file permissions not working as intended We just got our first Windows Server 2008 R2 server in. It's going to be a file server. However, I am running into a weird issue with it that seems to be a result of UAC.
When I try to share a folder, I set the everyone group to "Full Control" on the share permissions. I then setup the NTFS permissions so they don't inherit from the default security descriptors when you format an NTFS volume and I choose to remove the current descriptors so I can setup my own. I setup so that the local administrators group has full control, the domain\Domain Admins group has full control, and the SYSTEM built in user has full control.
When I do this, I lose permissions to the folder as a domain administrator. What is causing this to happen? The machine has been joined to the domain and the Domain Admins group is part of the local administrators group (not that that should matter anyway since I specifically have the domain admins in the NTFS permissions).
This is what the default NTFS security descriptors look like:

This is what the modified security looks like:

Why would this cause the logged on domain administrator and any other domain admin to lose access? This behaviour is not seen on a Windows Server 2003 machine.
Edit: I've done some more testing and it appears only the logged on user of that machine is denied access, even though the user logged on is a member of the Domain Admins group. A Domain Admin has no problem accessing the share through the network.
Edit 2: Alright, so thank you to Zoredache below, I was able to get on the right track and figure out what was going on. It was indeed UAC but not the default UAC settings that comes on Windows Server 2008 R2. We actually have a domain wide UAC group policy object that was changing the default settings on the server.
This is the default settings:

And this is what the settings on the GPO were:

Since GPO takes precedence to local security, this is what was stopping me from seeing the NTFS permissions or gaining access to the folder.
I've fixed this behaviour by simply making a new UAC GPO and WMI filtering it to servers only.

A: You are right about mentioning the UAC.  This is a feature.  See this for how to disable the UAC.
Administrator File Modification Privilege


text:
Q: MS Teams. How to add a file into the file tab of the bot programatically? In teams, there is an bot app called Dev3.
Our users can take a chat with the bot Dev3.
When user want to upload a file. She/He can upload an attachment file with the attachment clip icon.
Meanwhile after uploading the attachment files, She/He can review the file uploaded in the file tab.
For Users, it is a quick way for users to check the files between She/He and the bot.

Now we have following demand.
We get the graph api privilege at our server side and we want to upload some file to the file tab too! where user can also check the file which is uploaded by application.
We want to confirm that whether it is possible or not?
Currently, we tried the way of uploading file into the user's private one drive folder but those files are not displayed in the file tab.

Can anyone give some suggestion on how to putting a file in the file tab?

A: The Files tab in channel is nothing it linked to SharePoint site default folder, Please take a look at Upload Files This API restricted to file size to 4MB. if you want to upload greater than 4MB you need to upload the file in stream or chunks.


text:
Q: Segre Embedding and Group Actions The segre embedding takes two schemes $X, Y$ with $G_m$ and (I think) produces an embedding $X/G_m \times Y/G_m \hookrightarrow (X \times Y)/G_m$, with $G_m$ acting diagonally on $X \times Y$.
My confusion is that this seems like a "limit of colimit" to "colimit of limit" sort of map. Or at least, by the nature of the way things are pointing can't make use of the universal properties of these objects. I feel like the more natural thing to consider would be a map
$$
(X \times Y)/G_m \to X/G_m \times Y/G_m
$$
which naively would send $[(x, y)]$ (the equivalence class of $(x, y)$ to $([x], [y])$, which is well-defined on equivalence classes. Is this related to the Segre embedding at all? Is this even a well-defined map? Is there any reason why this latter map isn't discussed as much? Is there a group-actiony perspective on the Segre Embedding? Thanks!


text:
Q: Shortest path and sorting points in a 2-dimensional space Let's say I have an object in a 2-dimensional space, and a set of points that I need that object to visit.  Points may be added at any time, but not removed.
What I want is to be able to determine the next closest point to where my object is in O(lg(n)) time, then go to it, then determine the next closest, etc..
A simple priority queue doesn't work for this because the object is changing position, so the queue would need to be rearranged each time it moves.  I was imagining sorting the points into a BST somehow, but I'm unsure of how to sort with respect to (x, y) or if it's even possible.
This feels like I could be trying to solve traveling salesman without realizing it, if so, I apologize haha.

A: One option would be to use a space partitioning tree like a quadtree or k-d tree to store all of the points in space.  These data structures efficiently (usually in sublinear time) support queries of the form "what is the closest points to point p?"  You could then do the following:

*

*Build a space partitioning tree for the points in space.

*Use the tree to find the point p closest to your starting point.

*Repeat the following:

*

*Move to point p.

*Remove p from the tree.

*Set p to be the point closest to your current location.

Hope this helps!


text:
Q: CheckGMail, aMSN in notification area won't use the gnome-panel background When I use CheckGMail, it shows up in Notification Area.
But it never use gnome-panel's background color. It looks like something wrong with the panel.
Same goes with aMSN.
Is there a way to fix it? Or change theme to cover this up. I am now using Elementary theme.

A: New version of CheckGMail (from PPA or in "check updates" command from tray icon menu), as far as I know, have that bug fixed.
BTW, gmail-notify have nicer integration with app-indicators. Try it.

A: Change ur panel background color until they fix the bug. Just delete or rename panel.png in /usr/share/themes/elementary/gtk-2.0 and you will be able to change the color of your panel.

A: You could use gmail-notify as Extender said, but you should also switch to emesene, instead of amsn, because amsn is almost dead (still under development, but going so slow you don't get a release for months).


text:
Q: Custom view's content in stack view are not visible even when on view debugger it is showing a proper frame? This is the code for my custom view;
import UIKit

class TodoCell: UIView {
@IBOutlet weak var label: UILabel!
@IBOutlet weak var radioButton: UIImageView!
var isTaskDone: Bool = false

override init(frame: CGRect) {
    super.init(frame: frame)
    customInit()
}

required init?(coder: NSCoder) {
    super.init(coder: coder)
    customInit()
}

func configure(title: String) {
    self.label.text = title
}

func customInit() {
    if let view = Bundle.main.loadNibNamed("TodoCell", owner: self, options: nil)?[0] as? TodoCell {
        view.frame = bounds
        self.backgroundColor = .clear
        addSubview(view)
    }
}

override func awakeFromNib() {
    super.awakeFromNib()
    radioButton.image = UIImage(named: "radio_button_unchecked")
 }
}

This is how I am adding my custom view inside stack view
        let view = TodoCell(frame: .zero)
        view.configure(title: $0.title)
        todoListStackView.addArrangedSubview(view)
        todoListStackView.translatesAutoresizingMaskIntoConstraints = false
        view.heightAnchor.constraint(equalToConstant: 90).isActive = true
        view.widthAnchor.constraint(equalTo: todoListStackView.widthAnchor).isActive = true

The highlighted cell is a TodoCell inside stackview.

This is my TodoCell xib.

A: OK - based on the xib image you posted, it looks like you have the custom class for File's Owner set to TodoCell.
However, in this part of your code:
func customInit() {
    if let view = Bundle.main.loadNibNamed("TodoCell", owner: self, options: nil)?[0] as? TodoCell {
        view.frame = bounds
        self.backgroundColor = .clear
        addSubview(view)
    }
}

your if statement says "Only do this if the view (the [0] object) from the xib is a TodoCell. With the way you've configured your xib, that is not the case.
Also, you want to set the autoresizingMask on the loaded view.
So, assuming you have constraints setup correctly in your xib, if you change that to:
func customInit() {
    if let view = Bundle.main.loadNibNamed("OldTodoCell", owner: self, options: nil)?[0] as? UIView {
        view.frame = bounds
        view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        self.backgroundColor = .clear
        addSubview(view)
    }
}

you should be on your way.
A side note...
Using "cell" when naming a custom view can be confusing, as anyone else would assume it's a table view or collection view cell. If you're the only person who will ever touch your code, that doesn't matter. But, it's something to consider.


text:
Q: UINavigationController view controller stack order is incorrect when using the "long press back button" feature in iOS 14 I've noticed that, when using the long-press back button feature in iOS 14, any properties relating to UINavigationController's view controller stack (.viewControllers, .topViewController, etc.) seem incorrect. Specifically, the order is reversed.
Regarding the .viewControllers property, Apple's docs state:

The root view controller is at index 0 in the array, the back view controller is at index n-2, and the top controller is at index n-1, where n is the number of items in the array.

If I've got three view controllers in a nav stack like as follows
[ViewController01, ViewController02, ViewController03] and print out the .viewControllers property in viewWillAppear, I get the expected output of:
[ViewController01]
[ViewController01, ViewController02]
[ViewController01, ViewController02, ViewController03]

If I tap the back button from ViewController03, I get the expected output from viewWillAppear in ViewController02:
[ViewController01, ViewController02]
However, if I set everything up again so I've got [ViewController01, ViewController02, ViewController03] and then use the long-press back button feature to jump back to ViewController01, I get the unexpected output of:
[ViewController03, ViewController01]
From viewWillAppear in ViewController01.
I'm not expecting this because ViewController03 isn't, and never was, the root view controller of the navigation stack. As per the docs, I'm expecting:
[ViewController01, ViewController03]
Could someone please let me know if this is expected behaviour or if I've overlooked something super-obvious?
Thank you!
I've reproduced this in a small sample app based on a "single view controller" project. Just embed the initial view controller in a nav stack and include the following:
class StubViewController: UIViewController {

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print("\(self) will appear. Current nav stack follows:")
        print("\(self.navigationController?.viewControllers ?? [])")
    }

}

class ViewController: StubViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.pushViewController(TestViewController01(), animated: true)
    }

}

class TestViewController01: StubViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.pushViewController(TestViewController02(), animated: true)
    }

}

class TestViewController02: StubViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.pushViewController(TestViewController03(), animated: true)
    }
}

class TestViewController03: StubViewController {
}

(I'm aware the above is very horrible)

A: Basically, what's happening here is that you have accidentally looked inside the sausage factory and you've seen how the sausage is made. And it isn't pretty...!
The workaround is: don't do that. Give the view controllers stack a chance to settle down before you look at it:
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    DispatchQueue.main.async {
        print("\(self) will appear. Current nav stack follows:")
        print("\(self.navigationController?.viewControllers ?? [])")
    }
}

Even more simple: just move the code to viewDidAppear.

A: i'm stuck with this too, but what i've found is navigation controller changed the viewControllers stack because of animation to handle what controller will goes to another in back operation
for example if stack is [vc1, vc2, vc3, vc4] and you are in vc4 and if you call
navigationController.popToRootViewController(animated: true)

stack will be [vc4, vc1] in willShow delegate method.
the only way i found is to set animation to false
navigationController.popToRootViewController(animated: false)

to keep the stack as what it really is


text:
Q: SQL SELECT - GROUP BY Very much starting with SQL.
I am trying to gather data from a couple of tables to produce a summary where the values from the first table are grouped by a field, Repcode, and totalled.  And in the resultant cursor there is to be a description taken from the second table, by looking up on the Repcode field.
This is a much simplified test program
CREATE CURSOR Nomtot (tcode C(4), tRepcode C(2), tBalance N(9,2))
INSERT INTO nomtot (tCode, tRepcode, tBalance) VALUES ("A001", "12", 123.45)
INSERT INTO nomtot (tCode, tRepcode, tBalance) VALUES ("B003", "17", 555.45)
INSERT INTO nomtot (tCode, tRepcode, tBalance) VALUES ("B006", "19", 666.00)
INSERT INTO nomtot (tCode, tRepcode, tBalance) VALUES ("E008", "12", 810.00)

CREATE CURSOR RepLook (tRepcode C(2), tDesc C(30))
INSERT INTO Replook(tRepcode, tDesc) VALUES ("12", "Materials")
INSERT INTO Replook(tRepcode, tDesc) VALUES ("17", "Carriage")
INSERT INTO Replook(tRepcode, tDesc) VALUES ("19", "Dividends")

SELECT a.tRepcode, SUM(a.tBalance) AS tBalance, b.tDesc ;
  FROM Nomtot a, Replook b ;
  GROUP BY a.tRepcode ;
  WHERE a.tRepcode = b.tRepcode ;
  INTO CURSOR cResult

This however produces an error : SQL GROUP BY command is missing or invalid.
If I then change the  statement to GROUP BY a.tRepcode, b.tDesc ;
   . . . the program produces the required result.
Why is this second clause necessary?  Am I doing this correctly
Grateful for guidance.  Thanks.

A: add the group by for all the columns not involved in aggreagation function
and move the where before the group by
SELECT a.tRepcode, SUM(a.tBalance) AS tBalance, b.tDesc
FROM Nomtot a, Replook b
WHERE a.tRepcode = b.tRepcode
GROUP BY a.tRepcode, b.tDesc

or using the the current join style  (as ssuggested  by YogeshSharma)
SELECT a.tRepcode, SUM(a.tBalance) AS tBalance, b.tDesc
FROM Nomtot a
INNER JOIN  Replook b ON a.tRepcode = b.tRepcode
GROUP BY a.tRepcode, b.tDesc

A: The reason why is that SQL will need to aggregate on all colomns that arent a calculation.
In other language like SAS it wouldnt be required but your calculation would be based only on what the group by has. In other words your SUM(a.tBalance) would have the same value for all b.tDesc. In your case it may be a one to one match and it wouldnt matter but in some other case your b.Table could have multiple matched values and should have different sums....
Another way to do it without having to include the b.tDesc in group by :
select a.*, b.tDesc
from (
SELECT a.tRepcode, SUM(a.tBalance) AS tBalance
  FROM Nomtot) a
inner join Replook b
on a.tRepcode = b.tRepcode ;

A: You need to include all non-aggregate columns in group by. That is the reason. A better way of writing that query would be:
CREATE CURSOR Nomtot (tcode C(4), tRepcode C(2), tBalance N(9,2))
INSERT INTO nomtot (tCode, tRepcode, tBalance) VALUES ("A001", "12", 123.45)
INSERT INTO nomtot (tCode, tRepcode, tBalance) VALUES ("B003", "17", 555.45)
INSERT INTO nomtot (tCode, tRepcode, tBalance) VALUES ("B006", "19", 666.00)
INSERT INTO nomtot (tCode, tRepcode, tBalance) VALUES ("E008", "12", 810.00)

CREATE CURSOR RepLook (tRepcode C(2), tDesc C(30))
INSERT INTO Replook(tRepcode, tDesc) VALUES ("12", "Materials")
INSERT INTO Replook(tRepcode, tDesc) VALUES ("17", "Carriage")
INSERT INTO Replook(tRepcode, tDesc) VALUES ("19", "Dividends")

SELECT a.tRepcode, a.tBalance, b.tDesc ;
  FROM ;
  (select tRepCode, sum(tBalance) as tBalance ;
   from nomtot ;
   group by tRepCode ) a ;
  inner join Replook b on a.tRepcode = b.tRepcode ;
  INTO CURSOR cResult ;
  nofilter

A: Assuming you're using vfp 8 or 9 then all you have to do is add this one line of code to the top of your program.
SET ENGINEBEHAVIOR 70

using your example.
SET ENGINEBEHAVIOR 70

CREATE CURSOR Nomtot (tcode C(4), tRepcode C(2), tBalance N(9,2))
INSERT INTO nomtot (tCode, tRepcode, tBalance) VALUES ("A001", "12", 123.45)
INSERT INTO nomtot (tCode, tRepcode, tBalance) VALUES ("B003", "17", 555.45)
INSERT INTO nomtot (tCode, tRepcode, tBalance) VALUES ("B006", "19", 666.00)
INSERT INTO nomtot (tCode, tRepcode, tBalance) VALUES ("E008", "12", 810.00)

CREATE CURSOR RepLook (tRepcode C(2), tDesc C(30))
INSERT INTO Replook(tRepcode, tDesc) VALUES ("12", "Materials")
INSERT INTO Replook(tRepcode, tDesc) VALUES ("17", "Carriage")
INSERT INTO Replook(tRepcode, tDesc) VALUES ("19", "Dividends")

SELECT a.tRepcode, SUM(a.tBalance) AS tBalance, b.tDesc ;
  FROM Nomtot a, Replook b ;
  GROUP BY a.tRepcode ;
  WHERE a.tRepcode = b.tRepcode ;
  INTO CURSOR cResult

of course you could rewrite the query the correct way but this works all the same.

A: Cetin Basoz's answer is right and it should be accepted as answer but I want to add one more thing that you can use MAX() or MIN() function with not aggregated fields like this
SELECT MAX(a.tRepcode) AS tRepcode, SUM(a.tBalance) AS tBalance, MAX(b.tDesc) AS tDesc ;
  FROM Nomtot a, Replook b ;
  GROUP BY a.tRepcode ;
  WHERE a.tRepcode = b.tRepcode ;
  INTO CURSOR cResult


text:
Q: Can letter-spacing be applied to UINavigationBar's title with Pixate? The letter-spacing property appears to have no effect on the title child in a navigation bar using Pixate.

A: In iOS the UINavigationBar title's attributed text only supports font, text color, text shadow color, and text shadow offset. To get letter-spacing you need to create your own text field, assign the NSKernAttributeName attribute to it, and then assign it to the titleView of your NavigationItem. This is done per nav page, not generically for the UINavigationBar.


text:
Q: Where can I find a chart or data comparing CPU speed to memory speed? If you look at this, there is a chart of memory speed versus CPU speed from 1980 - 2000. I need to use a similar chart in a research paper, and I need a good set of data from a reputable source to use for the chart.

Does anyone know where I could find this?

A: I'd say your best bet is looking up the frequencies of the main processor/memory types (like Pentium) on Wikipedia, since they tend to give you some nice tables with an overview of their specs.
In the case of Pentium you get a very broad range (in time) of frequencies, which is probably what your after.
For memory, someone else will have to suggest a type or brand though you could look for things like DDR memory etc.
Downside: you'll have to create a graph like this yourself, though with Excel, that shouldn't be too hard. And in case you miss some years, just interpolate ;-) Moore's Law will keep you safe!


text:
Q: Quantile regression in JAGS I am trying to implement a simple quantile regression in R using JAGS:
n <- 200
x <- runif(n=n,min=0,max=10)
y <- 1 + 2*x + rnorm(n,sd=.6*x)
p <- 0.95
jdf <- list(y=y,x=x,p=p)
params <- c("alpha","beta","tau")
mcmcmodel <- jags.model(file="qreg.jag",data=jdf,n.chains=3)
update(mcmcmodel,2000)
mcsamples <- coda.samples(mcmcmodel,params,n.iter=10000,thin=10)

with qreg.jag as follows:
model{
 for(i in 1:length(y)){
   mu[i] <- alpha + beta*x[i]
   cmu[i] <- (step(mu[i])/(1-p) + step(-mu[i])/p)*mu[i]/2
   y[i] ~ ddexp(cmu[i],2*tau*p*(1-p))
 }

 #priors for regression
 alpha ~ dnorm(0,1E-6)
 beta ~ dnorm(0,1E-6)#dunif(0,100)

 lsigma ~ dunif(-5,15)
 sigma <- exp(lsigma)
 tau <- pow(sigma,-2)
}

I have compared my results with bayesQR package: the results do not match and what I have implemented gives unreasonable estimates.
Can anybody help?

A: I used a data augmentation procedure suggested here with the following model:
model{
 for(i in 1:length(y)){
   mu[i] <- alpha + beta*x[i]
   w[i] ~ dexp(tau)
   me[i] <- (1-2*p)/(p*(1-p))*w[i] + mu[i]
   pe[i] <- (p*(1-p)*tau)/(2*w[i])
   y[i] ~ dnorm(me[i],pe[i])
 }

 #priors for regression
 alpha ~ dnorm(0,1E-6)
 beta ~ dnorm(0,1E-6)

 lsigma ~ dunif(-5,15)
 sigma <- exp(lsigma/2)
 tau <- pow(sigma,-2)
}

This works reasonably well.


text:
Q: Types linearly-ordered by deduction? I'm wondering whether anyone has come across the following concept before:
Consider a first-order language $L$ and a type $p$ over a theory $T$. I say that $p$ has a well-ordered filter-base if there exists a transfinite sequence $(\phi_\alpha)_{\alpha < \lambda} \subseteq p$ (where $\lambda$ is some ordinal) such that $\{\phi_\alpha : \alpha < \lambda\}$ is a filter-base for $p$ (considered as a filter in the appropriate Boolean algebra) and $T \vdash (\phi_\beta \to \phi_\alpha)$ for all $\alpha < \beta < \lambda$. Such a type $p$ will correspond to a point in the space of types with a neighbourhood base linearly-ordered by $\subseteq$. I could call such a type linear. Of course, if the language were countable then $p$ would be countable, so I could enumerate it and take conjunctions of initial finite segments. But if $L$ were uncountable then this property becomes non-trivial.
Or more generally, what if $p$ were a p-point in the space of types; that is, for every countable subcollection $\Phi \subseteq p$, there exists a $\psi \in p$ such that $T \vdash (\psi \to \phi)$ for all $\phi \in \Phi$.
Thanks!


text:
Q: Matrix definition using some rules for the elements I'm gonna produce a matrix in which the matrix elements obey the following rules
$\left<n \right|M \left| m \right> = m^2 \delta_{m,n},$
$\left<m \pm 2 \right|M \left| m \right> = (1-m) \delta_{m,m \pm 2}.$
How can I produce such a matrix in Mathematica?
Since I have no idea about it, I could not make any code.

A: Assuming that you meant
$$
\langle n\lvert M \rvert m \rangle = m^2 \delta_{m,n}+(1-m)(\delta_{m,n+2}+\delta_{m,n-2})
$$
and ranges of $n,m\in\{1,2,3,\ldots,a\}$, you can define this matrix with
M[a_] := Table[m^2 KroneckerDelta[n, m] +
           (1 - m) (KroneckerDelta[m, n + 2] + KroneckerDelta[m, n - 2]),
           {n, a}, {m, a}]

or, more efficiently,
M[a_] := SparseArray[{{m_,m_} -> m^2, {n_,m_} /; Abs[n-m]==2 -> 1-m}, {a,a}]

or even
M[a_] := SparseArray[{Band[{1, 1}] -> Range[a]^2,
                      Band[{3, 1}] -> -Range[0, a - 3],
                      Band[{1, 3}] -> -Range[2, a - 1]}]

Test:
M[6] // MatrixForm
(*    {{ 1,  0, -2,  0,  0,  0},
       { 0,  4,  0, -3,  0,  0},
       { 0,  0,  9,  0, -4,  0},
       { 0, -1,  0, 16,  0, -5},
       { 0,  0, -2,  0, 25,  0},
       { 0,  0,  0, -3,  0, 36}}    *)

Considering that this matrix isn't Hermitian and that you are using Dirac-notation matrix elements, I suspect that there is something wrong in these definitions.


text:
Q: Is there a way of determining the last entry when looping through an array? Create a find command from an array I am trying to create a find command options string using entries from an array but on the last entry of the array I would like to add a different string.
EXT=(sh mkv txt)

EXT_OPTS=(-iname)

# Now build the find command from the array
for i in "${EXT[@]}"; do
    #echo $i
    EXT_OPTS+=( "*.$i" -o -iname)
done

cheers
EDIT:
So now I am going with:
#!/bin/bash

EXT=(sh mkv txt)

EXT_OPTS=()
# Now build the find command from the array
for i in "${EXT[@]}"; do
    EXT_OPTS+=( -o -iname "*.$i" )
done

# remove the first thing in EXT_OPTS
EXT_OPTS=( "${EXT_OPTS[@]:1}" )

# Modify to add things to ignore:

EXT_OPTS=( "${EXT_OPTS[@]:-1}" )
EXT_OPTS=( '(' "${EXT_OPTS[@]}" ')' ! '(' -iname "*sample*" -o -iname "*test*" ')' )

#echo "${EXT_OPTS[@]}"

searchResults=$(find . -type f "${EXT_OPTS[@]}")

echo "$searchResults"

for me produces this:
./Find2.sh
./untitled 2.sh
./countFiles.sh
./unrar.sh
./untitled 3.sh
./untitled 4.sh
./clearRAM.sh
./bash_test.sh
./Test_Log.txt
./untitled.txt
./Find.txt
./findTestscript.sh
./untitled.sh
./unrarTest.sh
./Test.sh
./Find.sh
./Test_Log copy.txt
./untitled 5.sh
./IF2.sh

A: It will be easiest just to fix the array after the fact. After done, adding
unset 'EXT_OPTS[-1]'
unset 'EXT_OPTS[-1]'

will remove the last two values (-o and -iname), and then you can add others if you want (or just replace them to begin with).
It might be slightly easier still just to add a redundant condition:
EXT_OPTS+=( "*.${EXT[0]}" )

if your real situation is a bit more complicated, but for this one I would just fix it as above.

A: Add the options in another order, then delete the first element:
EXT=(sh mkv txt)

EXT_OPTS=()
# Now build the find command from the array
for i in "${EXT[@]}"; do
    EXT_OPTS+=( -o -iname "*.$i" )
done

# remove the first thing in EXT_OPTS
EXT_OPTS=( "${EXT_OPTS[@]:1}" )

If you don't use $@ for anything, it's neater looking:
EXT=(sh mkv txt)

# Empty $@
set --

# Now build the find command from the array
for i in "${EXT[@]}"; do
    set -- -o -iname "*.$i"
done

# remove the first thing in $@
shift

# assign to EXT_OPTS (this would be optional, you could just use "$@" later)
EXTS_OPTS=( "$@" )

I prefer adding -o -iname "*.$i" to the intermediate array, because "*.$i" -o -iname is difficult to read.  Adding -o -iname "*.$i" to $@ also makes it really easy to just shift off the first -o after the loop.

To combine with a few exclusions (names to ignore):
extensions=( sh mkv txt )
ignore_patterns=( '*sample*' '*test*' )

include=()
# Now build the find command from the array
for ext in "${extensions[@]}"; do
    include+=( -o -iname "*.$ext" )
done

# Do the ignore list:
ignore=()
for pattern in "${ignore_patterns[@]}"; do
    ignore=( -o -iname "$pattern" )
done

# combine:
EXT_OPTS=( '(' "${include[@]:1}" ')' ! '(' "${ignore[@]:1}" ')' )

Note the parentheses added to sort out the precedence of the tests.

A:
Is there a way of determining the last entry when looping through an array?

Just to answer the question as literally stated, I don't think you can do that directly. But you could of course count the elements while looping and compare that against the array size:
test=(foo bar blah qwerty)
count=${#test[@]}
n=1
for x in "${test[@]}"; do
   last=""
   if [[ $((n++)) -eq count ]]; then
        last=" (last)"            # last element, add a note about that
   fi
   printf "%s%s\n" "$x" "$last"
done

Of course in your case, you could also make the first item the exceptional one.


text:
Q: Get last messages for user inbox using sql i am working on user inbox. i have to retrieve last message to show in inbox, either it was from me or from my friend. i have tried every possible solution but i am not getting any result that's why i am asking here. i am still learning sql. here is my db picture
database table
solution i want: example:
id | sent_by | sent_to | descp
42 | 3       | 7       | fdssdf
30 | 3       | 6       | sdas

A: I'm not quite sure what you mean, but usually when you want to select the latest of something, you use SELECT TOP 1 and ORDER BY x DESC
SELECT TOP 1 *
FROM your_table_name
WHERE sent_by = 3
ORDER BY id DESC


text:
Q: Get a specific child from Firebase In my Firebase, I have a database for an app. Let's say this is my Firebase JSON:
{
  "Users" :{
    "User1":{
      "City": "Genk"
    }
    ,"User2":{
      "City": "Hasselt"
    }
    ,"User3":{
      "City": "Genk"
    }
    ,"User4":{
      "City": "As"
    }
    ,"User5":{
      "City": "Genk"
    }
  }
}

Now what I want is an ArrayList with all the users with city Genk. How is this possible? I want to use this ArrayList to put the specific Users who live in the city Genk in a ListView.

A: I suggest you create another child from the root like "UsersCity", In that way you can just call this child and retrieve it to your listview. Here's what i did:
String key = mDatabase.child("post").push().getKey();
UserPost userPost = new UserPost(author,uid,setemoticon,postData,mDate,latlng);
Map<String, Object> postValues = userPost.toMap();

Map<String, Object> childUpdates = new HashMap<>();
                childUpdates.put("/post/" + key,postValues);
                childUpdates.put("/user-post/" + uid + "/" + key, postValues);

mDatabase.updateChildren(childUpdates);

Here's the Json output for that :
{
"post" : {
"-KcGVPpS9CTWPNax61wf" : {
  "authorName" : "Test 1",
  "dateCreated" : {
    "dateCreated" : 1486352395887
  },
  "postDescription" : "sample post",
  "postEmotion" : 2130837658,
  "userId" : "KTcgauWoJugXUsq6TAgrdqUvVYm1"
}
},
"user-post" : {
"KTcgauWoJugXUsq6TAgrdqUvVYm1" : {
  "-KcGVPpS9CTWPNax61wf" : {
    "authorName" : "Test 1",
    "dateCreated" : {
      "dateCreated" : 1486352395887
    },
    "postDescription" : "sample post",
    "postEmotion" : 2130837658,
    "userId" : "KTcgauWoJugXUsq6TAgrdqUvVYm1"
  }
}
},
//This child node is for users where you'll want to get the $uid to use for  creation of other child nodes.
"users" : {
"KTcgauWoJugXUsq6TAgrdqUvVYm1" : {
  "fullname" : "Test 1"
  }
 }
}

I am just a newbie programmer and I know my answer is not the best but I hope it could help you out with your problem. :)

A: just fetch specific node data and its working perfect for me
mFirebaseInstance.getReference("yourNodeName").getRef().addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
            Log.e(TAG, "======="+postSnapshot.child("email").getValue());
            Log.e(TAG, "======="+postSnapshot.child("name").getValue());
        }
    }

    @Override
    public void onCancelled(DatabaseError error) {
        // Failed to read value
        Log.e(TAG, "Failed to read app title value.", error.toException());
    }
});


text:
Q: How to get the extension of a file name using a SQL Server stored procedure How do I get the extension of a file name using a SQL Server stored procedure?
I want to get the extension of the file name
For example, if the file name is sdgfh_h670-ff.docx, the result should be .docx.

A: You can use SQL Server's built in string functions:
SELECT RIGHT('sdgfh_h670-ff.docx',CHARINDEX('.',REVERSE('sdgfh_h670-ff.docx')))


text:
Q: Kaltura Install on Plesk / Media Temple DV3.5 apachectl error Some pain today as with everything new and exciting.  I am attempting to install Kaltura CE on a subdomain on my Media Temple DV runnning plesk 8.6.0.  I get to a step that asks for my apachectl path and I enter correctly but keep getting errors as listed below.  I do know this is meant to be on a dedicated box but as with everything I am sure there is a way to make it work.
> /usr/sbin/apachectl

The path you inserted is not valid. Please try again.
The full pathname to your Apache apachectl/apache2ctl file:
Examples:
/usr/bin/apachectl
/usr/bin/apache2ctl
/opt/lampp/bin/apachectl
sh: /which: No such file or directory
sh: /which: No such file or directory
>

As always,  any and all help is appreciated.  Thanks in advance.

A: After much pain and hours of trying to make something work that really cannot work.  I set up a linode.com box using Ubuntu 10.0.4 and installed kaltura following the directions from kaltura.org. Getting this to work would involve modifying your my.conf file to support lower_case_table_names = 1 which will render Plesk unusable.  My recommendations for installing Kaltura would be to follow the step by step instructions using the patched xampp file they provide you with.
Installing Kaltura on 10.04


text:
Q: How to clip an isosurface to a ball? Consider the Togliatti implicit surface. I want to clip it to the ball centered at the origin with radius 4.8. A solution, with the misc3d package, consists in using the mask argument of the computeContour3d function, which allows to use only the points satisfying x^2+y^2+z^2 < 4.8^2:
library(misc3d)

# Togliatti surface equation: f(x,y,z) = 0
f <- function(x,y,z){
  w <- 1
  64*(x-w)*
    (x^4-4*x^3*w-10*x^2*y^2-4*x^2*w^2+16*x*w^3-20*x*y^2*w+5*y^4+16*w^4-20*y^2*w^2) -
    5*sqrt(5-sqrt(5))*(2*z-sqrt(5-sqrt(5))*w)*(4*(x^2+y^2-z^2)+(1+3*sqrt(5))*w^2)^2
}

# make grid
nx <- 220; ny <- 220; nz <- 220
x <- seq(-5, 5, length=nx)
y <- seq(-5, 5, length=ny)
z <- seq(-4, 4, length=nz)
g <- expand.grid(x=x, y=y, z=z)

# calculate voxel
voxel <- array(with(g, f(x,y,z)), dim = c(nx,ny,nz))

# mask: keep points satisfying x^2+y^2+z^2 < 4.8^2, in order to
#       clip the surface to the ball of radius 4.8
mask <- array(with(g, x^2+y^2+z^2 < 4.8^2), dim = c(nx,ny,nz))

# compute isosurface
surf <- computeContour3d(voxel, maxvol=max(voxel), level=0, mask=mask, x=x, y=y, z=z)

# draw isosurface
drawScene.rgl(makeTriangles(surf, smooth=TRUE))

But the borders of the resulting surface are irregular:

How to get regular, smooth borders?

A: The solution I found resorts to spherical coordinates. It consists in defining the function f in terms of spherical coordinates (ρ, θ, ϕ), then to compute the isosurface with ρ running from 0 to the desired radius, and then to transform the result to Cartesian coordinates:
# Togliatti surface equation with spherical coordinates
f <- function(ρ, θ, ϕ){
  w <- 1
  x <- ρ*cos(θ)*sin(ϕ)
  y <- ρ*sin(θ)*sin(ϕ)
  z <- ρ*cos(ϕ)
  64*(x-w)*
    (x^4-4*x^3*w-10*x^2*y^2-4*x^2*w^2+16*x*w^3-20*x*y^2*w+5*y^4+16*w^4-20*y^2*w^2) -
    5*sqrt(5-sqrt(5))*(2*z-sqrt(5-sqrt(5))*w)*(4*(x^2+y^2-z^2)+(1+3*sqrt(5))*w^2)^2
}

# make grid
nρ <- 300; nθ <- 400; nϕ <- 300
ρ <- seq(0, 4.8, length = nρ) # ρ runs from 0 to the desired radius
θ <- seq(0, 2*pi, length = nθ)
ϕ <- seq(0, pi, length = nϕ)
g <- expand.grid(ρ=ρ, θ=θ, ϕ=ϕ)

# calculate voxel
voxel <- array(with(g, f(ρ,θ,ϕ)), dim = c(nρ,nθ,nϕ))

# calculate isosurface
surf <- computeContour3d(voxel, maxvol=max(voxel), level=0, x=ρ, y=θ, z=ϕ)

# transform to Cartesian coordinates
surf <- t(apply(surf, 1, function(rtp){
  ρ <- rtp[1]; θ <- rtp[2]; ϕ <- rtp[3]
  c(
    ρ*cos(θ)*sin(ϕ),
    ρ*sin(θ)*sin(ϕ),
    ρ*cos(ϕ)
  )
}))

# draw isosurface
drawScene.rgl(makeTriangles(surf, smooth=TRUE, color = "violetred"))

Now the resulting surface has regular, smooth borders:

A: Your solution is excellent for the problem you stated, because spherical coordinates are so natural for that boundary.  However, here is a more general solution that would work for other smooth boundaries.
The idea is to allow input of a boundary function, and cull points when they are too large or too small.  In your case it would be the squared distance from the origin, and you would want to cull points where the value is bigger than 4.8^2.  But sometimes the triangles being drawn to make the smooth surface should only be partially culled:  one point would be kept and two deleted, or two kept and one deleted.  If you cull the whole triangle that leads to the jagged edges in your original plot.
To fix this, the points can be modified.  If only one is supposed to be kept, then the other two points can be shrunk towards it until they lie on an approximation to the boundary.  If two are supposed to be kept you want the shape to be a quadrilateral, so you would build that out of two triangles.
This function does that, assuming the input surf is the output of computeContour3d:
boundSurface <- function(surf, boundFn, bound = 0, greater = TRUE) {
  # Surf is n x 3:  each row is a point, triplets are triangles
  values <- matrix(boundFn(surf) - bound, 3)
  # values is (m = n/3) x 3:  each row is the boundFn value at one point
  # of a triangle
  if (!greater)
    values <- -values
  keep <- values >= 0
  # counts is m vector counting number of points to keep in each triangle
  counts <- apply(keep, 2, sum)
  # result is initialized to an empty array
  result <- matrix(nrow = 0, ncol = 3)
  # singles is set to all the rows of surf where exactly one
  # point in the triangle is kept, say s x 3
  singles <- surf[rep(counts == 1, each = 3),]
  if (length(singles)) {
    # singleValues is a subset of values where only one vertex is kept
    singleValues <- values[, counts == 1]
    singleIndex <- 3*col(singleValues) + 1:3 - 3
    # good is the index of the vertex to keep, bad are those to fix
    good <- apply(singleValues, 2, function(col) which(col >= 0))
    bad <- apply(singleValues, 2, function(col) which(col < 0))
    for (j in 1:ncol(singleValues)) {
      goodval <- singleValues[good[j], j]
      for (i in 1:2) {
        badval <- singleValues[bad[i,j], j]
        alpha <- goodval/(goodval - badval)
        singles[singleIndex[bad[i,j], j], ] <-
          (1-alpha)*singles[singleIndex[good[j], j],] +
             alpha *singles[singleIndex[bad[i,j], j],]
      }
    }
    result <- rbind(result, singles)
  }
  doubles <- surf[rep(counts == 2, each = 3),]
  if (length(doubles)) {
    # doubleValues is a subset of values where two vertices are kept
    doubleValues <- values[, counts == 2]
    doubleIndex <- 3*col(doubleValues) + 1:3 - 3
    doubles2 <- doubles
    # good is the index of the vertex to keep, bad are those to fix
    good <- apply(doubleValues, 2, function(col) which(col >= 0))
    bad <- apply(doubleValues, 2, function(col) which(col < 0))
    newvert <- matrix(NA, 2, 3)
    for (j in 1:ncol(doubleValues)) {
      badval <- doubleValues[bad[j], j]
      for (i in 1:2) {
        goodval <- doubleValues[good[i,j], j]
        alpha <- goodval/(goodval - badval)
        newvert[i,] <-
          (1-alpha)*doubles[doubleIndex[good[i,j], j],] +
             alpha *doubles[doubleIndex[bad[j], j],]
      }
      doubles[doubleIndex[bad[j], j],] <- newvert[1,]
      doubles2[doubleIndex[good[1,j], j],] <- newvert[1,]
      doubles2[doubleIndex[bad[j], j],] <- newvert[2,]
    }
    result <- rbind(result, doubles, doubles2)
  }
  # Finally add all the rows of surf where the whole
  # triangle is kept
  rbind(result, surf[rep(counts == 3, each = 3),])
}

You would use it after computeContour3d and before makeTriangles, e.g.
fn <- function(x) {
  apply(x^2, 1, sum)
}

drawScene.rgl(makeTriangles(boundSurface(surf, fn, bound = 4.8^2,
                                         greater = FALSE),
                            smooth = TRUE))

Here's the output I see:

It's not quite as good as yours, but it would work for many different boundary functions.
Edited to add:  Version 0.100.26 of rgl now has a function clipMesh3d which incorporates these ideas.


text:
Q: XCode Instruments - Show taps on screen I have just started using XCode Instruments and I'm doing some UI automation. To make life a bit easier I would like some kind of indication on the screen where I am tapping.
Does Instruments have an API call that will display the current location of a tap?


text:
Q: Authors get duplicated in Index I want to create an author index with backend=bibtex and indexing=cite using biblatex. However, some authors get duplicated when I have cited both books and inproceedings published by the same author.
In the following MWE, the author of both bibliographical entries gets listed twice although the author's name is identical:
\documentclass{article}

\usepackage{filecontents}
\begin{filecontents*}{\jobname.bib}
@book{velemaWatChristelijkGereformeerd1947,
  langid = {Nederlands},
  location = {{Amsterdam}},
  title = {Wat is Christelijk Gereformeerd?},
  pagetotal = {151},
  publisher = {{Ds. H. Janssen-fonds}},
  date = {1947},
  author = {Velema, J.H.}}

@incollection{velemaKerkStrijd1992,
  location = {{Kampen}},
  title = {{{Kerk en strijd}}},
  booktitle = {{{Een eeuw christelijk-gereformeerd: aspecten van 100 jaar Christelijke Gereformeerde Kerken}}},
  publisher = {{Kok}},
  date = {1992},
  pages = {221-240},
  author = {Velema, J.H.},
  editor = {van 't Spijker, W. and Noorlandt, J.N. and van der Schaaf, H.},
  options = {useprefix=true}}
\end{filecontents*}

\usepackage[style=authoryear,indexing=cite,backend=bibtex]{biblatex}
\addbibresource{\jobname.bib}

\usepackage{makeidx}
\makeindex

\begin{document}
\cite{velemaWatChristelijkGereformeerd1947,velemaKerkStrijd1992}

\printbibliography
\printindex
\end{document}

Which results in:

To merge the duplicated names in the index, I tried the solution provided in this answer but that did not help. Could anyone provide an alternative solution to merge both names? Thank you.

A:
biblatex 3.13 contains a fix for https://github.com/plk/biblatex/issues/893 that is equivalent to the definition of \mkbibindexname (option 2) shown in the MWE below.
Update your TeX distribution to obtain the current versions of biblatex and Biber.
Further changes to the document should not be necessary.
\documentclass{article}

\usepackage[style=authoryear, indexing=cite, backend=bibtex]{biblatex}

\usepackage{filecontents}
\begin{filecontents*}{\jobname.bib}
@book{velemaWatChristelijkGereformeerd1947,
  langid    = {dutch},
  location  = {Amsterdam},
  title     = {Wat is Christelijk Gereformeerd?},
  pagetotal = {151},
  publisher = {Ds.~H.~Janssen-fonds},
  date      = {1947},
  author    = {Velema, J. H.},
}
@incollection{velemaKerkStrijd1992,
  location  = {Kampen},
  title     = {Kerk en strijd},
  booktitle = {Een eeuw christelijk-gereformeerd: aspecten van 100 jaar Christelijke Gereformeerde Kerken},
  publisher = {Kok},
  date      = {1992},
  pages     = {221-240},
  author    = {Velema, J. H.},
  editor    = {van 't Spijker, W. and Noorlandt, J. N. and van der Schaaf, H.},
  options   = {useprefix=true},
}
\end{filecontents*}
\addbibresource{\jobname.bib}

\usepackage{makeidx}
\makeindex

\begin{document}
\cite{velemaWatChristelijkGereformeerd1947,velemaKerkStrijd1992}

\printbibliography
\printindex
\end{document}

produces the expected result.
The answer below is kept for historical interest.

As mentioned in the comments, the .idx file contains
\indexentry{Velema, J. H.}{1}
\indexentry{Velema, J. H.@Velema, J. H.}{1}

The index then ends up with two entries for J. H. Velema, one for Velema, J. H. and one for Velema, J. H.@Velema, J. H..
The different entries are caused by biblatex's name indexing settings. The relevant bits can be found in biblatex.def (ll. 1166-1187)
\newcommand*{\mkbibindexname}[4]{%
  \ifuseprefix
    {\ifdefvoid{#3}{}{#3 }%
     \@firstofone #1% remove spurious braces
     \ifdefvoid{#4}{}{ #4}%
     \ifdefvoid{#2}{}{, #2}%
     \actualoperator
     \ifdefvoid{#3}{}{\MakeCapital{#3} }%
     #1%
     \ifdefvoid{#4}{}{ #4}%
     \ifdefvoid{#2}{}{, #2}}
    {\@firstofone #1% remove spurious braces
     \ifdefvoid{#4}{}{ #4}%
     \ifboolexpe{%
       test {\ifdefvoid{#2}}
       and
       test {\ifdefvoid{#3}}}
       {}
       {,}%
     \ifdefvoid{#2}{}{ #2}%
     \ifdefvoid{#3}{}{ #3}}}

If useprefix is true, biblatex will use \actualoperator (i.e. @) to make sure that the prefix is sorted correctly but shown in the expected capitalisation. But the @ is also added in cases where it is not needed since there is no prefix.
The entry velemaKerkStrijd1992 has an explicit useprefx=true, while velemaWatChristelijkGereformeerd1947 uses the default useprefix=false setting. Hence, the former produces Velema, J. H.@Velema, J. H. and the latter Velema, J. H. for the index.
There are at least two possible solutions.

*

*Enable useprefix=true globally and not only for velemaKerkStrijd1992. Then both entries will send Velema, J. H.@Velema, J. H. to the index.

*Redefine \mkbibndexname to only use \actualoperator when necessary.

The MWE demonstrates option 2.
\documentclass{article}

\usepackage[style=authoryear, indexing=cite, backend=bibtex]{biblatex}

\makeatletter
\renewcommand*{\mkbibindexname}[4]{%
  \ifuseprefix
    {\ifdefvoid{#3}{}{#3 }%
     \@firstofone #1% remove spurious braces
     \ifdefvoid{#4}{}{ #4}%
     \ifdefvoid{#2}{}{, #2}%
     \ifdefvoid{#3}{}{%
       \actualoperator
       \MakeCapital{#3} %
       #1%
       \ifdefvoid{#4}{}{ #4}%
       \ifdefvoid{#2}{}{, #2}}}
    {\@firstofone #1% remove spurious braces
     \ifdefvoid{#4}{}{ #4}%
     \ifboolexpe{%
       test {\ifdefvoid{#2}}
       and
       test {\ifdefvoid{#3}}}
       {}
       {,}%
     \ifdefvoid{#2}{}{ #2}%
     \ifdefvoid{#3}{}{ #3}}}
\makeatother

\usepackage{filecontents}
\begin{filecontents*}{\jobname.bib}
@book{velemaWatChristelijkGereformeerd1947,
  langid    = {dutch},
  location  = {Amsterdam},
  title     = {Wat is Christelijk Gereformeerd?},
  pagetotal = {151},
  publisher = {Ds.~H.~Janssen-fonds},
  date      = {1947},
  author    = {Velema, J. H.},
}
@incollection{velemaKerkStrijd1992,
  location  = {Kampen},
  title     = {Kerk en strijd},
  booktitle = {Een eeuw christelijk-gereformeerd: aspecten van 100 jaar Christelijke Gereformeerde Kerken},
  publisher = {Kok},
  date      = {1992},
  pages     = {221-240},
  author    = {Velema, J. H.},
  editor    = {van 't Spijker, W. and Noorlandt, J. N. and van der Schaaf, H.},
  options   = {useprefix=true},
}
\end{filecontents*}
\addbibresource{\jobname.bib}

\usepackage{makeidx}
\makeindex

\begin{document}
\cite{velemaWatChristelijkGereformeerd1947,velemaKerkStrijd1992}

\printbibliography
\printindex
\end{document}

Note how I changed langid = {Nederlands}, to langid = {dutch}, since langid takes babel language names as values. I also removed excess braces in some fields.


text:
Q: Prove or disprove whether this is a vector space: Let $V = F_3×F_3$ be the direct product of the field of three elements with itself. Define + as componentwise
multiplication of the elements, for example $$(a, b) + (c, d) = (a ∗ c, b ∗ d).$$ Let $F = F_3$ and have scalar
multiplication defined as usual (component wise).

A: This is not a vector space.  A vector space must have an identity element for vector addition,
say $(c,d)$ in $V$, satisfying $(a,b)+(c,d)=(a*c,b*d)=(a,b)$.
Furthermore, each vector must have an additive inverse.
But $a* c=a$ and $b* d=b$ for $a,b\in F_3\setminus \{0\}$ imply $(c,d)=(1,1).$
and since $(0,0)+(e,f)=(0
*e,0*f)=(0,0)$ for all $e,f\in F_3$,
there is no additive inverse for $(0,0)$ in your proposed vector space.


text:
Q: Как встроить telegram в android приложение? Каким образом встроить чат-бота в Android приложение. Получать ответы от бота в виде json-массива и выводить? или пытаться интегрировать его?

A: Все довольно просто, но так как я ни разу не работал с ботом, то постараюсь помочь максимально используя свои знания. Насколько я знаю, суть бота, как вы вероятнее всего знаете, заключается в том чтобы человек общался с программой. Вы хотите обрабатывать ответы бота у себя в приложении, а для этого у вас должно быть несколько вещей:

*

*Апи куда вы посылаете запрос - если это определенный бот, а вероятнее всего определенный, то вам нужно получать именно от нужного бота ответы. Для этого у вас должно быть апи. Чаще всего апи представлено в виде кусочка или целого адреса.

*Класс-запрос (данные которые нужны для получения ответа от вашего бота) - это класс или кучка данных которые требуются серверу, для вашей идентификации. Вот к примеру, для вашей идентификации серверу нужен ваш логи и пароль. Дальше вам нужно отправить id бота или как там они идентифицируется. Значит у вас в вашей кучке данных будет три поля - логин, пароль и id-бота. И вы создаете класс который вмещает все эти поля, например:

public class Regest{
             private Integer id;
private String login;
private Integer bot_id;
public Regest(Integer id,String login,Integer bot_id) {
    this.id= id;
    this.login= login;
    this.bot_id= bot_id;
}

}

*Класс-ответ - этот класс будет помогать вам обрабатывать ответ вашего сервера, то есть ответ вашего бота. В этот класс будет входить массив ваших сообщений и еще какие-то данные которые он будет слать, без примера ответа довольно сложно представить что там есть.

*Послание запроса из активности и заполнение вашего вью-элемента:
После того как вы все сделали вышеперечисленное, вам пора послать запрос. Для этого из активности вы должны послать запрос и полученные данные распарсить в вьюху:

 public APIService apiService() {
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(url)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    return retrofit.create(APIService.class);
}

 public void getData() {
     mAPIService.auth(new Regest(login, password, bot_id)).enqueue(new Callback<SpeakWithBot>() {
            @Override
            public void onResponse(@NonNull Call<SpeakWithBot> call, @NonNull Response<SpeakWithBot> response) {
                if (response.isSuccessful()) {
здесь обрабатываете то что вам прислал сервер
}

            @Override
            public void onFailure(@NonNull Call<GetToken> call, @NonNull Throwable t) {
            }
        });

для обработки вашего ответа можете использовать как recyclerView с адаптером подстроенным под ваши данные, так и любой другой вью элемент. Если я где-то ошибся, то найдутся те кто меня исправит, или откорректирует мой ответ. Но я почему-то уверен что используя retrofit можно обрабатывать то что шлет вам в ответ ваш бот. Надеюсь что помог чем-то в решении вашей проблемы. Удачи :)