text:
Q: UIScrollView shift down 44px (equal navigation bar height) right after dismiss modal view controller I have an UIViewController with a navigation bar. My UIScrollView which contains a list of UIButtons is added programmatically. I used AutoLayout to add the scrollview and its buttons list as the code below.
It works perfectly until there is a modal view is showed and dismissed. After the modal view dismissed, the button list in the scrollview is shifted down 44px (equal navigation bar height).
When I try removing the navigation bar, everything work correctly.
I searched in the below questions but they aren't my case:
Contents of UIScrollView shifted after dismissing ModalViewController
Dismiss modal view changes underlying UIScrollView
My code to add an uiscrollview using AutoLayout:
UIScrollView* scrollView = [UIScrollView new];
[scrollView setTranslatesAutoresizingMaskIntoConstraints:NO];

//calculate contentSize based on the button count
int buttonCount = 10;
CGSize contentSize = CGSizeMake(ICON_X*2 + (ICON_WIDTH + ICON_SPACE) * buttonCount - ICON_SPACE, ICON_HEIGHT);

//calculate trailing offset for the first button
CGFloat trailingOffset = contentSize.width - (ICON_X + ICON_WIDTH);

//add list of button to the scrollview
for (int i = 0; i < buttonCount; i++) {

    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTranslatesAutoresizingMaskIntoConstraints:NO];

    //set button image
    //set button target

    //set tag
    button.tag = i;

    //add to the scroll view
    [scrollView addSubview:button];

    //calculate the button's frame using AutoLayout
    NSDictionary *dict = NSDictionaryOfVariableBindings(button);
    [scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"H:|-%g-[button(%d)]-%g-|", ICON_X + (ICON_WIDTH + ICON_SPACE)*i, ICON_WIDTH, trailingOffset] options:NSLayoutFormatAlignAllCenterY metrics:nil views:dict]];
    [scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat: @"V:|-%g-[button(%d)]-%g-|", ICON_Y, ICON_HEIGHT, ICON_Y] options:NSLayoutFormatAlignAllCenterY metrics:nil views:dict]];

    //update the trailing offset for the next button
    if (i == buttonCount - 2) //the next one is the last button
        trailingOffset = ICON_X;
    else
        trailingOffset -= (ICON_SPACE + ICON_WIDTH);
}

//add the scrollView to self.viewIcon
//self.viewIcon is a UIView which was added as a subview of self.view in the storyboard using AutoLayout
[self.viewIcon addSubview:scrollView];

//calculate the scrollview's frame using AutoLayout
//contraint autolayout
NSArray *verticalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(1)-[scrollView(58)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(scrollView)];
NSArray *horizontalContraints = [NSLayoutConstraint constraintsWithVisualFormat:@"|[scrollView]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(scrollView)];
[self.viewIcon addConstraints:verticalConstraints];
[self.viewIcon addConstraints:horizontalContraints];

Please notice that the scrollview is added to self.viewIcon which was added as a subview of self.view in the storyboard using AutoLayout
Thank you

A: I have also the same problem on iOS 6. The problem seems to be solved on iOS7GM.
Look here for a solution : Shifting view after displaying modal - possibly AutoLayout related


text:
Q: Auto expanding divs based on lack of content I've been working on a template for a database-driven page that ideally should have four divs for content like this:
----- -----
| 1 | | 2 |
----- -----
----- -----
| 3 | | 4 |
----- -----

The same content will always be in the same boxes. News is in #1, images in #2, etc. Based on the content provided, there could be all of these sections or only one. If for example box 2 doesn't exist, how can I get box 1 to expand to the width of the parent div?
i.e.:
-----------
| 1       |
-----------
----- -----
| 3 | | 4 |
----- -----

or if 3 & 4 do not exist
-----------
| 1       |
-----------
-----------
| 2       |
-----------

Granted, this might be something that can only wholly be done with if/then statements, but I was wondering if there was a way to do this in CSS...  Or could it be jquery? I feel like this should be simple but my brain is just not getting how to do it.
I set up two 50% width floating divs side by side, but I'm not sure how it would know how to expand if the other is missing.
Thanks!
Edit: Adding HTML! There's nothing really fancy here yet...

        Upcoming Events

            March 5, 2014

            Book signing

            March 5, 2014

            Ice cream party

        Media Gallery

A: Based on your comment that ideally a div wouldn't be in the DOM, here might be something to help you, pure CSS.
Add in your HTML a "wrapping" div for each row:

1

2

3

4

Together with this CSS:
.row {
    width: 600px;
    display: table;
}
.row > div {
    display: table-cell;
}

It will give you this result
Taking, for example, the second div away, will give you this result.
It however makes it harder when div #3 and #4 don't exist and you want div#2 to be on the next line. You'll need to add an extra class or something on the server side of your script.
Hope this will help you!

A: Here is an option you can use but it is not pure css sadly, could be depending on what you need.
How are the children being added to the parent that contains them?
What I am doing is adding a class .half to the child class which will break the child into half the width. To achieve the end result I do need to know the answer to the question I asked.
Here is a demo to play with,
css:
body * {
    box-sizing: border-box;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
}

.parent {
    width: 600px;
    height: 300px;
    border: 5px solid #ffdd00;
    margin-bottom: 20px;
    padding: 5px;
}

.child {
    width: 100%;
    height: 100%;
    background: #ff7200;
}

.child.half {
    width: 49.5%;
    display: inline-block;
    vertical-align: top;
}

jQuery:
var child = '
I am a child DIV
',
    halfChild = '
I am a child DIV
'

$('#fullTwo').on('click', function() {
    if($('.parent').find('.child')) {
        $('.parent').append(halfChild);
        $('.parent').find('.child').addClass('half');
    }
    else {
        $('.parent').append(child);
    }
});

Finally, a fiddle: Demo
Another fiddle to show how adding another class can effect the layout: Demo

A: lets say that news, images, comments and advertising classes position your divs this way:
-------------------
| news  |  images |
|------------------
| comms |  advert |
-------------------

one option whould be that you always have this base Html and based on the content of each div you decide the width of your elements:

now your js would look like this:
var isNewsEmpty = $('.news').html() == "";
var isImagesEmpty = $('.images').html() == "";
var isCommentsEmpty = $('.comments').html() == "";
var isAdvertisingEmpty = $('.advertising').html() == "";

//now just set width if empty
if (isNewsEmpty) { $('.images').css('width','100%') }
if (isImagesEmpty) { $('.news').css('width','100%') }
if (isCommentsEmpty) { $('.advertising').css('width','100%') }
if (isadvertisingEmpty) { $('.comments').css('width','100%') }

hope it helps!
Update
This would work even is one of the sections does not exits

redpajama_set_name: RedPajamaStackExchange


text:
Q: Coloring problem in plot3D with transparent texture I need to plot multiple surfaces with textures. Each texture is a matrix plot with transparent background. In this way, we can see the multiple surfaces from the top.
L= 10;
m1 = RandomInteger[{-1, 1}, {L, L}];
m2 = RandomInteger[{-1, 1}, {L, L}];
mp1 = MatrixPlot[m1, Frame -> None, Background -> None, ColorRules -> {0 -> None, -1 -> Red, 1 -> Blue}];
mp2 = MatrixPlot[m2, Frame -> None, Background -> None, ColorRules -> {0 -> None, -1 -> Red, 1 -> Blue}];
mplt1 = Plot3D[1, {x, 0, L}, {y, 0, L}, Lighting -> "Neutral", PlotStyle -> Directive[Texture[mp1]], TextureCoordinateFunction -> Automatic, BoundaryStyle -> None, Mesh -> None, PlotRange -> All, TextureCoordinateScaling -> True, Background -> None];
mplt2 = Plot3D[5, {x, 0, L}, {y, 0, L}, Lighting -> "Neutral", PlotStyle -> Directive[Texture[mp2]], TextureCoordinateFunction -> Automatic, BoundaryStyle -> None, Mesh -> None, PlotRange -> All, TextureCoordinateScaling -> True, Background -> None];
Show[{mplt1,mplt2}]

The image has slight red color on the surface, which I want to make completely transparent. After I overlay 50 sheets of this kind, the red color really mess up the whole picture.
Could anyone help me to manage the reddish color?
Thank you,


text:
Q: Kubernetes pod doesn't accept connections on exposed port I have a multi container pod deployment that exposes port 8080 the port inside the container is accessible through localhost but not the pod IP
when I telnet on the pod local host I'm able to connect but when I telnet on the pod IP that's in /etc/hosts I get connection refused.
deployment.yaml
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
 name: test
 namespace: yara
 labels:
   component: test-multi-container-pod
  spec:
 replicas: 1
 template:
   metadata:
     labels:
       app: test
          spec:
     serviceAccountName: test
     containers:
       - name: container-1
         image: "gcr.io/projectID/my-image1:v1.9.3"
         pullPolicy: "IfNotPresent"
         resources:
           limits:
             cpu: 1000m
             memory: 2Gi
            requests:
             cpu: 500m
             memory: 2Gi
       - name: container2
         image: "gcr.io/projectID/my-image2:0.0.107"
          pullPolicy: "IfNotPresent"
          securityContext:
           runAsUser: 0
         resources:
           limits:
             cpu: 1000m
             memory: 2Gi
           requests:
             cpu: 500m
             memory: 2Gi
       - name:  "app-container"
       ## nodejs image that exposes ports 3000 & 8080
         image: "gcr.io/projectID/node:8.9.4_1804082101"
         workingDir: "/usr/src/app"
         pullPolicy: "Always"
         command: ["tail", "-f", "/dev/null"]
         ports:
         - name: http
           containerPort: 3000
         - name: graphql
           containerPort: 8080
         resources:
           limits:
             cpu: 1500m
             memory: 2Gi
           requests:
             cpu: 1500m
             memory: 2Gi

service.yaml
apiVersion: v1
kind: Service
metadata:
  name: test-app
  namespace: "yara"
  labels:
    component: test-multi-container-pod
spec:
  type: NodePort
  ports:
  - protocol: TCP
    name: http
    port: 3000
    targetPort: http
  - protocol: TCP
    name: graphql
    port: 8080
    targetPort: graphql
  selector:
    component: test-multi-container-pod

A: The command option in Pod Spec overrides Entrypoint option in Docker Container, that's why you actually run tail instead of your application
  - name: "app-container"
    ...
    command: ["tail", "-f", "/dev/null"]

According to the documentation, command in kubernetes overrides docker containers entrypoint with the following rules:

*

*If you do not supply command or args for a Container, the defaults defined in the Docker image are used.

*If you supply a command but no args for a Container, only the supplied command is used. The default EntryPoint and the default Cmd defined in the Docker image are ignored.

*If you supply only args for a Container, the default Entrypoint defined in the Docker image is run with the args that you supplied.

*If you supply a command and args, the default Entrypoint and the default Cmd defined in the Docker image are ignored. Your command is run with your args.

All containers in a Pod share the same network namespace. It looks similar, as if processes from containers in the Pod would run on the same host and be able to bind only to ports which aren't occupied by other processes in the same Pod. Practically, if you configure two containers that use the same port binding, one of them fails to start with error: "[emerg] 1#1: bind() to 0.0.0.0:80 failed (98: Address already in use)".
If you need that particular pod container process to be found and accessed by other Pods and Services, you can describe it with port: directive in Pod Spec. It gives the system additional information about the network connections a container uses, but is primarily informational. Not specifying a port in Pod Spec does not  prevent that port from being exposed. Any port which is listening on the default "0.0.0.0" address inside a container will be accessible from the network by the Pod address and from other containers in the pod via localhost.
So, the response you've received from localhost:8080 could be delivered from another container in the pod which binds to that port.
You can find a good explanation of the Pod networking in this article.


text:
Q: How to select an option from Laravel into a select? I'm bringing all the data from the database and displaying in inputs for an edit page of my CRUD, but I can't figure out how to select an option based on the data.
With inputs I know that I can just do this:

    Nome Empresarial
    <input type="text" name="razao" value="{{$cliente->razao ?? old('razao')}}" class="form-control"  id="razao">

But i can't find anything about select, and how to set an option "selected" based on the data from the database.
The select:

Tipo de Contribuição
  <select class="form-control select2-single" name="tipoContribuinteCnpj" id="tipoContribuinteSelectCnpj">
     <option hidden></option>
     <option value="I">ICMS</option>
     <option value="X">Isento</option>
     <option value="N">Não Contribuinte</option>
  </select>

The data saved in the database is a single char that corresponds to the value of the option of the select.

A: Give this a shot:
<option value="I" {{ $cliente->tipoContribuinteCnpj == 'I' ? 'selected' : '' }}>ICMS</option>

A: Although it looks stupid, this is how i did in case you came here from google:

     Tipo de Contribuição
     <select class="form-control select2-single" name="tipoContribuinteCnpj" id="tipoContribuinteSelectCnpj">
          <option hidden></option>
          <option value="I" @if($cliente->tipoContribuinteCnpj == "I") selected @endif>ICMS</option>
          <option value="X" @if($cliente->tipoContribuinteCnpj == "X") selected @endif>Isento</option>
          <option value="N" @if($cliente->tipoContribuinteCnpj == "N") selected @endif>Não Contribuinte</option>
     </select>


text:
Q: Why is this showing an error? This is the error message I get for the line \end{equation}
You can't use `\eqno' in vertical mode.
\endequation ->\eqno
                     \hbox {\@eqnnum }$$\@ignoretrue
l.19 \end{equation}

Why is it happening?

A: You have some code equivalent to
\documentclass{article}

\begin{document}

\begin{equation}
1=2
$$

\end{equation}

\end{document}

You can not have $$ or a blank line inside the equation.
As above it produces
! You can't use `\eqno' in vertical mode.
\endequation ->\eqno
                     \hbox {\@eqnnum }$$\@ignoretrue
l.10 \end{equation}

Delete the $$ and blank line
\documentclass{article}

\begin{document}

\begin{equation}
1=2
\end{equation}

\end{document}

runs without error.


text:
Q: Why does the delete[] syntax exist in C++? Every time somebody asks a question about delete[] on here, there is always a pretty general "that's how C++ does it, use delete[]" kind of response.  Coming from a vanilla C background what I don't understand is why there needs to be a different invocation at all.
With malloc()/free() your options are to get a pointer to a contiguous block of memory and to free a block of contiguous memory.  Something in implementation land comes along and knows what size the block you allocated was based on the base address, for when you have to free it.
There is no function free_array().  I've seen some crazy theories on other questions tangentially related to this, such as calling delete ptr will only free the top of the array, not the whole array.  Or the more correct, it is not defined by the implementation.  And sure... if this was the first version of C++ and you made a weird design choice that makes sense.  But why with $PRESENT_YEAR's standard of C++ has it not been overloaded???
It seems to be the only extra bit that C++ adds is going through the array and calling destructors, and I think maybe this is the crux of it, and it literally is using a separate function to save us a single runtime length lookup, or nullptr at end of the list in exchange for torturing every new C++ programmer or programmer who had a fuzzy day and forgot that there is a different reserve word.
Can someone please clarify once and for all if there is a reason besides "that's what the standard says and nobody questions it"?

A: Generally, C++ compilers and their associated runtimes build on top of the platform's C runtime. In particular in this case the C memory manager.
The C memory manager allows you to free a block of memory without knowing its size, but there is no standard way to get the size of the block from the runtime and there is no guarantee that the block that was actually allocated is exactly the size you requested. It may well be larger.
Thus the block size stored by the C memory manager can't usefully be used to enable higher-level functionality. If higher-level functionality needs information on the size of the allocation then it must store it itself.  (And C++ delete[] does need this for types with destructors, to run them for every element.)
C++ also has an attitude of "you only pay for what you use", storing an extra length field for every allocation (separate from the underlying allocator's bookkeeping) would not fit well with this attitude.
Since the normal way to represent an array of unknown (at compile time) size in C and C++ is with a pointer to its first element, there is no way the compiler can distinguish between a single object allocation and an array allocation based on the type system. So it leaves it up to the programmer to distinguish.

A: Basically, malloc and free allocate memory, and new and delete create and destroy objects. So you have to know what the objects are.
To elaborate on the unspecified overhead François Andrieux's answer mentions, you can see my answer on this question in which I examined what does a specific implementation do (Visual C++ 2013, 32-bit). Other implementations may or may not do a similar thing.
In case the new[] was used with an array of objects with a non-trivial destructor, what it did was allocating 4 bytes more, and returning the pointer shifted by 4 bytes ahead, so when delete[] wants to know how many objects are there, it takes the pointer, shifts it 4 bytes prior, and takes the number at that address and treats it as the number of objects stored there. It then calls a destructor on each object (the size of the object is known from the type of the pointer passed). Then, in order to release the exact address, it passes the address that was 4 bytes prior to the passed address.
On this implementation, passing an array allocated with new[] to a regular delete results in calling a single destructor, of the first element, followed by passing the wrong address to the deallocation function, corrupting the heap. Don't do it!

A: The cover story is that delete is required because of C++'s relationship with C.
The new operator can make a dynamically allocated object of almost any object type.
But, due to the C heritage, a pointer to an object type is ambiguous between two abstractions:

*

*being the location of a single object, and

*being the base of a dynamic array.

The delete versus delete[] situation just follows from that.
However, that's does not ring true, because, in spite of the above observations being true, a single delete operator could be used. It does not logically follow that two operators are required.
Here is informal proof. The new T operator invocation (single object case) could implicitly behave as if it were new T[1]. So that is to say, every new could always allocate an array. When no array syntax is mentioned, it could be implicit that an array of [1] will be allocated. Then, there would just have to exist a single delete which behaves like today's delete[].
Why isn't that design followed?
I think it boils down to the usual: it's a goat that was sacrificed to the gods of efficiency. When you allocate an array with new [], extra storage is allocated for meta-data to keep track of the number of elements, so that delete [] can know how many elements need to be iterated for destruction. When you allocate a single object with new, no such meta-data is required. The object can be constructed directly in the memory which comes from the underlying allocator without any extra header.
It's a part of "don't pay for what you don't use" in terms of run-time costs. If you're allocating single objects, you don't have to "pay" for any representational overhead in those objects to deal with the possibility that any dynamic object referenced by pointer might be an array. However, you are burdened with the responsibility of encoding that information in the way you allocate the object with the array new and subsequently delete it.

A: Something not mentioned in the other (all good) answers is that the root cause of this is that arrays - inherited from C - have never been a "first-class" thing in C++.
They have primitive C semantics and do not have C++ semantics, and therefore C++ compiler and runtime support, which would let you or the compiler runtime systems do useful things with pointers to them.
In fact, they're so unsupported by C++ that a pointer to an array of things looks just like a pointer to a single thing. That, in particular, would not happen if arrays were proper parts of the language - even as part of a library, like string or vector.
This wart on the C++ language happened because of this heritage from C.  And it remains part of the language - even though we now have std::array for fixed-length arrays and (have always had) std::vector for variable-length arrays - largely for purposes of compatibility: Being able to call out from C++ to operating system APIs and to libraries written in other languages using C-language interop.
And ... because there are truckloads of books and websites and classrooms out there teaching arrays very early in their C++ pedagogy, because of a) being able to write useful/interesting examples early on that do in fact call OS APIs, and of course because of the awesome power of b) "that's the way we've always done it".

A: An example might help.  When you allocate a C-style array of objects, those objects may have their own destructor that needs to be called.  The delete operator does not do that.  It works on container objects, but not C-style arrays.  You need delete[] for them.
Here is an example:
#include <iostream>
#include <stdlib.h>
#include <string>

using std::cerr;
using std::cout;
using std::endl;

class silly_string : private std::string {
  public:
    silly_string(const char* const s) :
      std::string(s) {}
    ~silly_string() {
      cout.flush();
      cerr << "Deleting \"" << *this << "\"."
           << endl;
      // The destructor of the base class is now implicitly invoked.
    }

  friend std::ostream& operator<< ( std::ostream&, const silly_string& );
};

std::ostream& operator<< ( std::ostream& out, const silly_string& s )
{
  return out << static_cast<const std::string>(s);
}

int main()
{
  constexpr size_t nwords = 2;
  silly_string *const words = new silly_string[nwords]{
    "hello,",
    "world!" };

  cout << words[0] << ' '
       << words[1] << '\n';

  delete[] words;

  return EXIT_SUCCESS;
}

That test program explicitly instruments the destructor calls.  It's obviously a contrived example. For one thing, a program does not need to free memory immediately before it terminates and releases all its resources.  But it does demonstrate what happens and in what order.
Some compilers, such as clang++, are smart enough to warn you if you leave out the [] in delete[] words;, but if you force it to compile the buggy code anyway, you get heap corruption.

A: Objects in C++ often have destructors that need to run at the end of their lifetime. delete[] makes sure the destructors of each element of the array are called. But doing this has unspecified overhead, while delete does not. This is why there are two forms of delete expressions. One for arrays, which pays the overhead and one for single objects which does not.
In order to only have one version, an implementation would need a mechanism for tracking extra information about every pointer. But one of the founding principles of C++ is that the user shouldn't be forced to pay a cost that they don't absolutely have to.
Always delete what you new and always delete[] what you new[]. But in modern C++, new and new[] are generally not used anymore. Use std::make_unique, std::make_shared, std::vector or other more expressive and safer alternatives.

A: Delete is an operator that destroys array and non-array(pointer) objects which are generated by new expression.
It can be used by either using the Delete operator or Delete [ ] operator
A new operator is used for dynamic memory allocation which puts variables on heap memory.
This means the Delete operator deallocates memory from the heap.
Pointer to object is not destroyed, value or memory block pointed by the pointer is destroyed.
The delete operator has a void return type that does not return a value.


text:
Q: Counting figures in xslt I am trying to write some xslt that will enumerate all images in my xml(s!)
i am using a key for this so that i can reference the images later in the content,
my problem here is i cant figure out how to get a consistent value.
Meaning:
the xml has references to multiple other documents which i am loading using document(),
whenever i "enter" a new document the key is reset, so in documents that have 2 images i get a count of two, in others one
so you can imagine
root doc:
<root>
  <chapter href="chapters/doc1.xml"/>
  <chapter href="chapters/doc2.xml"/>
</root>

doc1.xml
<root>
  <image id="a"/>
  <image id="b"/>
</root>

doc2.xml
<root>
  <image id="f"/>
</root>

i found a old thread here on stackoverflow that i think goes kind of in my direction: XSLT: create 'key' across multiple documents?
but i was not able to make it work.
what is currently working:
i have defined a key
<xsl:key name="image" match="image" use="@id"/>

that im using later like this
 key value for image:<xsl:value-of select="count(key('image', @id)/preceding::image) + 1"/>

this always produces the mentioned result (for doc1 i get "key value for image:1 key value for image:2" bur for doc2 i get "key value for image:1" again and here i would expect a 3)
trying to adapt to the linked post i have tried to load all documents using collection and at create a new key hoping it would yield me at least all images for the start
<xsl:key name="images" match="image" use="all"/>

 <xsl:variable name="location"><xsl:value-of select="$xml-base"/>/chapters?select=*.xml;recurse=yes</xsl:variable>
<xsl:variable name="documents">
  <xsl:value-of select="collection($location)"/>
</xsl:variable>
<xsl:for-each select="collection($location)">
  <xsl:message>
    <xsl:value-of select="./count(key('figure','all'))"/>
  </xsl:message>
</xsl:for-each>

and that always gives me 0
i am not even sure if using key is the right approach here
tldr:
how can i enumerate images in xslt across multiple documents?
*edit as i think it was a bit unclear:
i have multiple xml inputs imported by a root xml,
all of them can contain images
i have a final output file that needs to enumerate all images continiously and be able to reference them

A: That last document has a single image element, therefore that image doesn't have any preceding::image.
It is also not clear why you need a key at all if you want to count image elements, count(//image) for a single document or count(document(/root/chapter/@href)//image) for using the document function on that first sample or count(collection('chapters?select=*.xml;recurse=yes')//image) for the XSLT 2/3 and Saxon 9 specific collection() call should do.
<xsl:key name="images" match="image" use="all"/> is meaningless unless any image element has child elements named all.
Dealing with severals documents is possible but requires some extra effort. If you need general processing and can't push all elements together through a template to exploit position() but somehow need to index all those image elements then perhaps doing <xsl:variable name="images" select="document(/root/chapter/@href)//image"/> and <xsl:variable name="image-ids" select="for $img in $images return generate-id($img)"/> and then simply using <xsl:value-of select="index-of($image-ids, generate-id())"/> in any xsl:template match="image" should work.
The for $img in $images return generate-id($img) can be written more compactly in XSLT 3 as $images ! generate-id().


text:
Q: Justifying an early equation from *Introduction to Statistical Learning* I'm self-studying Introduction to Statistical Learning. Page 19 of the book states the following:

Consider a given estimate $\hat{f}$ and a set of predictors $X$, which yields the prediction $\hat{Y} = \hat{f}(X)$. Assume for a moment that both $\hat{f}$ and $X$ are fixed. Then, it is easy to show that
$$
E(Y-\hat{Y})^2 = E[f(X) + \epsilon - \hat{f}(X)]^2
= [f(X) = \hat{f}(X)]^2 + Var(\epsilon)$$

Question: How exactly is the step from $E[f(X) + \epsilon - \hat{f}(X)]^2$ to $[f(X) = \hat{f}(X)]^2 + Var(\epsilon)$ justified?


text:
Q: Video thumbnail not appearing in wordpress homepage Here is my blog i added youtube video to my blog.This is the post but my problem is iam not able to view the video thumbnail in my homepage. I the thumbnail or image of the video is not appearing in homepage.Can we fix by adding any plugin or we should code to do it?

A: Probably your theme uses "the_excerpt" on the homepage, which is a stripped-down text-only version of your post. Some themes have the option to show the full post instead (look onder settings -> reading or under settings page of your theme).
If it is a Child Theme, you can manually alter the code to use "the_content" instead.


text:
Q: Eclipse can't find openJDK after minor update - Best practice? In a CentOS 7 box, I'm using Eclipse [Mars.2 v4.5.2] with OpenJDK 8.
When I upgraded the box ('yum update') the openJDK package had a minor update, from version:
java-1.8.0-openjdk-1:1.8.0.91-0.b14.el7_2.x86_64
to version :
java-1.8.0-openjdk-1.8.0.101-3.b13.el7_2.x86_64
Then, launching Eclipse failed with this error:

A Java Runtime Environment (JRE) or Java Development Kit (JDK) must be
  available in order to run Eclipse. No Java virtual machine was found
  after searching the following locations:
  /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.91-0.b14.el7_2.x86_64/jre/bin

Indeed, the folder mentioned above had been deleted by the yum update.
The workaround I came up with was to launch Eclipse using the -vm flag pointing to the latest openJDK version 8.0.101.
/home/olivier/eclipse/cpp-mars/eclipse/eclipse -vm /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.101-3.b13.el7_2.x86_64/jre/bin

What is the best practice here? (I'm new to CentOS & openJDK : didn't have that kind of problems with Fedora and Sun/Oracle-JDK).


text:
Q: Huge amounts of "multiply-claimed blocks" during fsck The basic question:
How long should fsck take to fix a 100GB (17 million block) file with multiply-claimed blocks?
The long version of the question:
After a UPS failure, I am faced with an Ubuntu 10.04 server which dropped into fsck on initial boot. This is normal, buy usually about half an hour of fixing the various problems by agreeing to the prompts is enough to get the server back.
Not today, though. Today, I got a huge list of numbers scroll past the console matrix-style for a good few minutes. It was basically line after line of:
Multiply-claimed blocks in inode xxxxxxxxx
Anyway, after a few minutes of those scrolling past, it finally settled down and I got:
Pass 1C: Scanning directories for inodes with multiply-claimed blocks
followed by...
Pass 1D: Reconciling multiply-claimed blocks
..and..
(There are 32 inodes containing multiply-claimed blocks.)
That didn't sound so bad, but then it started going through some files as so:
File /path/to/a/file
has 1 multiply-claimed block(s) shared with 1 file(s):
/path/to/another/file
Clone multiply-claimed blocks? yes
This question was answered for me and the process continued. However, it took a very very long time. Hours and hours even though it was only a 2MB file.
After that, a similar dialogue appeared but this time for a virtual machine image file which is 100GB and reported as being over 17 Million multiple-claimed blocks, shared with 0 file(s).
That was 2 days ago and it's still running now.
So, back to my original question, how long should this take? Is it a lost cause and are there any alternative ways to deal with this? What I really don't understand is why the 100GB file is reported as being shared with 0 files which is a contradiction if I understand the meaning of multiply-claimed blocks correctly.

A: It seems as thought the cause for the large amount of time and also the mystery of the multiply-claimed blocks being shared by zero files was the result of a degraded RAID array.
As soon as I removed the faulty drive, the fsck went much faster. There were still a few multiply-claimed blocks but they were fixed very quickly.
I have experienced degraded RAID arrays in Ubuntu before and usually there is a warning just after the grub phase, but this did not happen in this case.

A: This happens to me on RAID array of 6 disks, 4.5TB ext4 filesystem.  Linux 3.3.7-1-ARCH #1 SMP PREEMPT i686
I use rsync to sync over entire servers onto the ext4 and these are the files I mostly get these multiply-claimed-blocks and duplicate inode messages on.
EXT4 Mount Options
A couple things I did that seemed to help was to make sure that the ext4 was being mounted with barrier and data=ordered support.
/dev/md5 /md5  ext4  defaults,noatime,nouser_xattr,stripe=1536,data=ordered  0 2

RAID Bitmap
The other step I took was to enable bitmap on the RAID.
mdadm --grow /dev/md5 --bitmap=internal

or
mdadm --grow /dev/md5 --bitmap=/external/md5.bitmap

Having both the raid bitmap and ext4 journal located on an external device seems to work the best.
USB Autosuspend
In the past I had experienced this issue when my drives would go into autosuspend mode.  Writing to them (or attempting to) while they were trying to wake up from a suspended state seemed to cause these issues big time.  What I did was disable autosuspend compeletely on usb devices with:
usbcore.autosuspend=-1

EXT4 Data Modes
From: http://kernel.org/doc/Documentation/filesystems/ext4.txt

There are 3 different data modes:

*

*writeback mode
  In data=writeback mode, ext4 does not journal data at all.  This mode provides
  a similar level of journaling as that of XFS, JFS, and ReiserFS in its default
  mode - metadata journaling.  A crash+recovery can cause incorrect data to
  appear in files which were written shortly before the crash.  This mode will
  typically provide the best ext4 performance.

*ordered mode
  In data=ordered mode, ext4 only officially journals metadata, but it logically
  groups metadata information related to data changes with the data blocks into a
  single unit called a transaction.  When it's time to write the new metadata
  out to disk, the associated data blocks are written first.  In general,
  this mode performs slightly slower than writeback but significantly faster than journal > mode.

*journal mode
  data=journal mode provides full data and metadata journaling.  All new data is
  written to the journal first, and then to its final location.
  In the event of a crash, the journal can be replayed, bringing both data and
  metadata into a consistent state.  This mode is the slowest except when data
  needs to be read from and written to disk at the same time where it
  outperforms all others modes.  Currently ext4 does not have delayed
  allocation support if this data journalling mode is selected.

Fix with Debugfs
This has great examples to fix: http://www.redhat.com/archives/ext3-users/2009-February/msg00021.html

A: How long it takes would depend on disk subsystem performance, the damage being repaired, etc.
It sounds like there's some decent filesystem corruption. How big is the actual filesystem? You said it's a 100 GB file and later that it's a VM image? Is this a VM server? Or are you talking about virtualbox?
Personally if it took over a day and the damage was definitely to one file, I'd restore the file from backup and if there were any indications of continuing issues, reformat and restore from backup, assuming the drive isn't coincidentally failing. I have trust issues with filesystems that start to go bad. If the drive itself isn't failing, the filesystem may have a pervasive problem until it's started fresh.
But that's me.

A: I think, I had a similar problam. I have 2 HDD in a RAID0 array. Once, I did a fsck manually, after I unmounted the device. To my pain, I didn't realize, that a VM was still running and accessing the device during I fsck'ed. The result was lots of multiply claimed blocks and because I rebooted my server during the progress, I think it broke the superblock. So I couldn't even mount the RAID anymore.
I fixed the issue by restoring the superblock, once again by running fsck and repairing all issues which didn't have anything to do with "multiply claimed blocks". This took me some time and I needed to attend the process, to tell fsck not to repair the "multiply claimed blocks".
After that, the superblock was fixed and I could mount the device once again. Now, I ran fsck several times and checked, which files were affected by "multiply claimed blocks", stopped the process by hitting ctrl^c and simply copied the affected files and deleted the original once.
Sounds unconventional, but it fixed my problems in a quick way and my HDDs seem to be clean (according to e2fsck).
If there was a better/faster way to fix these to problems, I am glad to hear about them.

A: Are you using ext2 or ext4 without a journal?  You shouldn't ever see this kind of error with a journal.
Yes, it makes no sense to have multiply claimed blocks that are shared by zero files.  You should report this bug on the linux-ext4@vger.kernel.org mailing list.


text:
Q: How can I access my app's ionic-storage (localForage) from a second web view? I have an ionic app that uses ionic-storage.  I also have a native android background service that generates a separate webview to do work outside of the ionic app.  This service needs to write to the app's storage. I am using the same config (name & storeName) for both of these storage objects but they seem to be accessing completely different spaces, I'm guessing because they are separate WebViews.
Has anyone else encountered a similar problem or know how I might be able to remedy this?

A: The issue was that Ionic instantiates the storage object with a different priority for storage drivers than if you just do let storage = new Storage(); (what I'm doing in my separate background service WebView).  I was unable to get my non-ionic WebView to use SQLite correctly so I just changed the driver order for my ionic app using driverOrder: ['indexeddb', 'sqlite', 'websql'].
This resulted in both the Ionic App and and the extra WebView accessing the same storage area.


text:
Q: Handeling Node, Express background errors I am quite unsure how I should properly handle uncaught exceptions that occurs in my node.js/express app. Right now I have an Express app that will send all caught errors to an Express error handeler using next(err):
function(err, req, res, next) {
   // Do something with the error
}

This seems to work all fine and well for errors I have anticipated. For instance a database connection not working, essentially all things that will return a callback(err). Thought problem occurs when I want to preform a background task, which will finish after the response has been sent. For instance:
app.get('/url', function(req, res) {
   BackgroundTask.run() // Here an uncaught exception occurs, for instance a bug
   res.send('Running your background task')
}

The background modules that I want to run aren't express related (no use of req,res) and upon a caught errors they will use a custom in errorHandeler that will send the error to some error reporting service. However when an uncaught exception occurs in one of these background tasks I have no clue how to send the error to my error report service (Raygun in this case). The only thing that seems to work is to add a process.on('uncaughtException') event listener. However almost every post on the subject describes the latter a 'bad' or crude way of doing things. They seems to recommand using node domains however I don't really see how I can implement these for background tasks.

A: I use process.on(uncaughtException), because all you're really trying to do is catch the output from the error and shut the server down gracefully (and then restart).  I don't see any reason to do anything more complicated than that, because by nature of the exception, you don't want your application doing anything else in that state other than shutting down.
Domains are an alternative way of dealing with this, but it's not necessarily better than using the process handler, because you're effectively writing custom logic to handle things that you aren't anticipating.  It does give you finer granularity in terms of what your error handler does for different error types, but ultimately you're still potentially running your application in an unknown state after handling it.  I'd rather have my application log the exception, shut down, and then i'll fix the error so it never happens again, rather than risking my user's data on a domain solution which may or may not have handled the error correctly, depending on the nuance of the error it encountered.


text:
Q: DecodeStream error with Facebook Graph Request Hi i have implemented Facebook login into my app and am now trying to download the users profile picture and pass it into a RoundedImageView
However i am encountering an error when it test it and there is no image showing, the error is:
skia﹕ --- SkImageDecoder::Factory returned null

I am also getting these two errors directly before it
ReadStreamToBuffer : Qmage Stream read error!! required length 12 bytes, but red 0 bytes
isQmage : input SkStreamRewindable length is less than Qmage minimum size : 0

Here is my main asynctask for downloading and setting the image
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {

    private ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected void onPreExecute() {

    }

    protected Bitmap doInBackground(String... urls) {

        String userId = urls[0];
        Bitmap bmp = null;

            try {
                URL image_value = new URL("http://graph.facebook.com/"+ userId + "/picture?type=large");
                bmp = BitmapFactory.decodeStream(image_value.openConnection().getInputStream());
            } catch (IOException e) {
                Log.e("Error", "image download error");
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }

        return bmp;

    }

    protected void onPostExecute(Bitmap result) {

        bmImage.setImageBitmap(result);

    }
}

And here is how i call it
final RoundedImageView profilePic = (RoundedImageView) rootView.findViewById(R.id.myProfilePic);
    new DownloadImageTask(profilePic).execute(userId);

Thanks for any and all help


text:
Q: Why should you manually run a garbage collection in python? I have occasionally come across code that manually calls gc.collect(), but it's unclear why.  For what reasons, if any, would it be advantageous to manually run a garbage collection, rather than let Python handle it automatically?

A: In short, efficiency.
If you are using a pointer to reference something, it is using memory. Even when you stop pointing at it, it still takes up memory for a short amount of time.
Python's garbage collection used to use reference counting. Reference counting is a smart way to tell when something should no longer need memory (by checking how often it is referenced by other objects).
Unfortunately, reference counting is still a calculation so it reduces efficiency to run it all the time (especially when it is not needed), so instead Python now uses scheduled garbage collection.
The issue is that in some specific functionality Python now doesn't garbage collect immediately when it notices something is no longer used (as in the case with reference counting) because it garbage collects periodically instead.
You generally need to run garbage collection manually in a lot of server applications or large scale calculations where minor infractions in garbage collection matter to free memory.
Here is a link from Digi.com that sums it up perfectly if my explanation isn't clear. I hope this helps Brendan!

A: CPython (the Python implementation you are using most likely) does do both automatic reference counting and garbage collection.
Reference counting causes most objects in memory to be freed immediately when they're not needed any longer (no reference/variable pointing to the object).
Garbage collection will only be involved if you have cyclic references. CPython will collect "islands" of objects that are not referenced anymore on a regular basis.
You rarely need to get involved with Python memory management. The explicit call to gc.collect() makes sure that garbage collection (not reference counting!) is run immediately. You probably don't need this though, neither do most code bases that have calls to gc.collect().


text:
Q: I can't install Broadcom driver on Ubuntu 14.04 After installing Linux Ubuntu 14.04 on a new Lenovo V580c, I can't install Broadcom Wi-Fi adapter driver. After "Applying changes..." nothing happens.
lspci -nn | grep 0280
03:00.0 Network controller [0280]: Broadcom Corporation BCM43142 802.11b/g/n [14e4:4365] (rev 01)

A: Open your terminal and do the following,
sudo rmmod -f acer-wmi
sudo rfkill unblock all
rfkill list all

check the wifi is working fine,

A: Let's see if we can get the driver to install correctly. With a temporary internet connection, open a terminal and do:
sudo apt-get update
sudo apt-get install --reinstall bcmwl-kernel-source

Please open Software and Sources and uncheck the source CDROM and/or USB so that the system doesn't try to install from the USB but instead downloads from the internet. Then try the commands above once more.
Post any errors or messages and we'll proceed.


text:
Q: Splitting with Regex I want to split strings similar to abc123, abcdefgh12 or a123456 into letters and numbers, so that the result will be {"abc", "123"} etc.
What is the simplest way to do it in C# 4.0? I want to do it with one regex.

A: Why regex?
    static readonly char[] digits = {'0','1','2','3','4','5','6','7','8','9'};
    ....
    string s = "abcdefgh12", x = s, y = "";
    int i = s.IndexOfAny(digits);
    if (i >= 0) {
        x = s.Substring(0, i);
        y = s.Substring(i, s.Length - i);
    }

A: "Only numbers or only letters" can be represented using [a-zA-Z]*|[0-9]*. All you have to do is look for all matches of that regular expression in your string. Note that non-alphanumeric characters will not be returned, but will still split the strings (so "123-456" would yield { "123", "456"}).
EDIT: I've interpreted your question as stating that your strings can be a sequence of letters and numbers in any order - if your string is merely one or more letters followed by one or more numbers, a regular expression is unnecessary: look for the first digit and split the string.

A: In addition to Marc Gravell, read http://www.codinghorror.com/blog/2008/06/regular-expressions-now-you-have-two-problems.html .

What is the simplest way to do it in C# 4.0? I want to do it with one regex.

That's practically an oxymoron in your case. The simplest way of splitting by a fixed pattern is not with regexes.

A: Unless I'm missing something, this should do the trick... ([a-z]*)([0-9]*)

A: You could create a group for letteres and one for numbers.
use this guide for further info: http://www.regular-expressions.info/reference.html
HTH!


text:
Q: MySQL save array in the db Is it possible to store an associative array as it is in the db?
array(
       key  => value,
       key2 => value2,
       key3 => value3,
       ...
      )

Currently, if I write fieldname = '$array', only the string "Array" is stored in the field.

A: Try this
fieldname = json_encode($array);

and when you want to retrieve from database then use
$array = json_decode($fieldname);

A: You can also do this:
serialize($array);

and then when you fetch it from the database:
unserialize($array);

A: Do use
$fieldname = json_encode($array);

A:     php code to store array in database
    <?
        $array_string = array(key => value, key2 => value2, key3 => value3);
        $conn=mysql_connect('localhost', 'mysql_user', 'mysql_password');
        mysql_select_db("mysql_db",$conn);
        $array_string=mysql_escape_string(serialize($array));
        mysql_query("insert into table (column) values($array_string)",$conn);
    ?>

    To retrieve array from database

    <?
        $conn=mysql_connect('localhost', 'mysql_user', 'mysql_password');
        mysql_select_db("mysql_db",$conn);
        $q=mysql_query("select column from table",$conn);
        while($rs=mysql_fetch_assoc($q))
        {
        $array= unserialize($rs['column']);
        print_r($array);
        }
    ?>


text:
Q: Getting mouse coordinates on mouse click I'm using this code below but it doesn't work like I want it and I have no idea how to actually make it.
What I want it to do is get the mouse coordinates onClick, but this happens after the user confirm a messagebox.
MessageBox > User Click OK > User Click anywhere on screen > Get the coordinates
Should I start a timer at the "OK button"? What I do on timer code to wait for a mouse response?
This is what I have now (which shows the mouse position when I click OK button):
private void button12_Click(object sender, EventArgs e)
{
    if (MessageBox.Show("Pick a position after clicking OK", "OK", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) == DialogResult.OK)
    {
        // user clicked ok
        MouseEventArgs me = (MouseEventArgs)e;
        Point coordinates = me.Location;
        MessageBox.Show("Coordinates are: " + coordinates);
    }
}

A: You were almost there. The problem is that the EventArgs will give you the position relative to the button at the time of the click.
If you want the cursor position instead of the click, you can use the Cursor class to get its Position property:
private void button12_Click(object sender, EventArgs e)
{
    if (MessageBox.Show("Pick a position after clicking OK", "OK", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) == DialogResult.OK)
    {
        // user clicked ok
        Point coordinates = Cursor.Position;
        MessageBox.Show("Coordinates are: " + coordinates);
    }
}

To get the coordinates after the user closed the MessageBox, you can use a timer. In order to do so, you will have to declare one at the class level, set its Tick event and move your cursor login into it.
The button12_Click method will now start the timer, which will show the cursor position once it expires (In this example, after one second).
private Timer timer; //Declare the timer at class level
public Form1()
{
    InitializeComponent();
    // We set it to expire after one second, and link it to the method below
    timer = new Timer {Interval = 1000}; //Interval is the amount of time in millis before it fires
    timer.Tick += OnTick;
}

private void OnTick(object sender, EventArgs eventArgs)
{
    timer.Stop(); //Don't forget to stop the timer, or it'll continue to tick
    Point coordinates = Cursor.Position;
    MessageBox.Show("Coordinates are: " + coordinates);
}

private void button1_Click(object sender, EventArgs e)
{
    if (MessageBox.Show("Pick a position after clicking OK", "OK", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) == DialogResult.OK)
    {
        timer.Start();
    }
}

A: Cursor Position relative to the Screen
System.Windows.Forms.Cursor.Position

Cursor Position relative to a control
var relativePoint = myControl.PointToClient(Cursor.Position);

Global hooks are not supported in the .NET Framework. See Reference
If you want to handle global mouse click events have a look at this article.
Processing Global Mouse and Keyboard Hooks in C#

A: You have probably defined the click event for the wrong object.
If you use the click event for a panel, you will get the mouse coordinates relative to the upper-left corner of that panel. If you use the click event for another form control, you will get the mouse coordinates relative to the upper-left corner of that form control.
The below code will give the mouse coordinates relative to the upper-left corner of formobject1, whatever it is.
            formobject1.Click += (sender, e) => {
            MouseEventArgs e1 = (MouseEventArgs)e;
            System.Drawing.Point cc = e1.Location;
            MessageBox.Show(cc.ToString());
        };


text:
Q: Greasemonkey can't run at iframe not at first I refer to this Greasemonkey against an iframe using @include - does this work?
Unfortunately, it doesn't work, because the iframe is not loaded at first, and the domain in iframe is cross domain.
the userscript run only at page first loaded, not run at other time, even I register a domloaded event, the script runs at parent windows stills not handle the iframe


text:
Q: How to get Array one by one Randomly in array order in Python I have automated to send the numbers from the numbers array one by one to text box as shown below, while the numbers are get it from the array and at the same time how to get the mail id randomly one by one from the email array?
import time

numbers = [2589001,2589002,2589003,2589004,2589005,2589006,2589007,2589008,2589009,2589010]
email = ["mail1@gmail.com","mail2@gmail.com","mail3@gmail.com","mail4@gmail.com","mail5@gmail.com"]

def oo() :
    for idx in email :

        email_from_list = email[idx%len(email)]

#I want to put those email function code here and need to pass this def oo()

c = 0
def vs () :
    for idx, nm in enumerate(numbers) :

        #Number Input
        WebDriverWait(browser, 2500).until(EC.presence_of_element_located((By.NAME, "Number"))).send_keys(nw)
        time.sleep(1)

        WebDriverWait(browser, 2500).until(EC.presence_of_element_located((By.NAME, "Number"))).send_keys(oo()) #<---- here need to call
        time.sleep(1)
        #I need code here to get email id one by one randomly from array   <--- Fix you wording. You don't actually want them one by one randomly

w = 0
while w < 50 :
    vs ()
    w += 1

A: I've read your comment, and what you are describing there is not what you are asking for in the original post/question. What you want is to iterate over the same list of emails (not want to select a random email).
import time

numbers = [2589001,2589002,2589003,2589004,2589005,2589006,2589007,2589008,2589009,2589010]
email = ["mail1@gmail.com","mail2@gmail.com","mail3@gmail.com","mail4@gmail.com","mail5@gmail.com"]

c = 0
def vs () :
    for idx, nm in enumerate(numbers) :

        #Number Input
        WebDriverWait(browser, 2500).until(EC.presence_of_element_located((By.NAME, "Number"))).send_keys(nw)
        time.sleep(1)

        #I need code here to get email id one by one randomly from array   <--- Fix you wording. You don't actually want them one by one randomly
        email_from_list = email[idx%len(email)]

w = 0
while w < 50 :
    vs ()
    w += 1


text:
Q: Python Tkinter: How to decrease tab space in Treeview So I have the following code that creates the GUI in the picture below:
import tkinter as tk
import tkinter.ttk as ttk
root = tk.Tk()
# Some code

# Creating Master TreeView
treeView = ttk.Treeview(root)
treeView.heading("#0", text="Variables", anchor=tk.W)
treeView.place(relx=0, rely=0.00,relwidth=0.1,relheight=1)
# Some Code

# Creating Folders/Sub Folders
var = treeView.insert("", 0, text=name)
treeView.insert(var, "end", text="Type: "+type)
treeView.insert(var, "end", text="Value: "+str(value))

This is what It looks like without being pressed and then pressed

Is there anyway to decrease the tabspace of the sub folders? Like bring it back to where the black point is?

For context, this is what the whole gui looks like:

I have to reserve so much space for the Treeview just to make sure the subfolders appear on the screean, and it takes up way to much space. I tend to find that the treeview uses a lot of unnecessary space when adding subfolders

A: You can try and constain the tree column:
treeView.column('#0', width=your_width, stretch=False)


text:
Q: MySQL query for searching subset of two tables I have two tables:
CREATE TABLE IF NOT EXISTS `comments` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `photograph_id` int(11) NOT NULL,
    `created` datetime NOT NULL,
    `author` varchar(255) NOT NULL,
    `body` text NOT NULL,
    `email` varchar(255) NOT NULL,
    `liked` int(11) NOT NULL,
    PRIMARY KEY (`id`),
    KEY `photograph_id` (`photograph_id`)
)

And this:
CREATE TABLE IF NOT EXISTS `photographs` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `user_id` int(11) NOT NULL,
    `filename` varchar(255) NOT NULL,
    `type` varchar(100) NOT NULL,
    `size` int(11) NOT NULL,
    `caption` varchar(255) NOT NULL,
    `liked` int(11) NOT NULL,
    PRIMARY KEY (`id`),
    KEY `user_id` (`user_id`)
)

I am having trouble merging these two into one query. In this query I would like to have sorting call of number of comments that every photo have. In Comments table, there is column photograph_id, that links to the photo id in Photographs table. Thanks for the help.

A: For photo's with 1 or more comments do:
SELECT p.id, COUNT(*) as commentcount FROM photographs p
INNER JOIN comments c ON (p.id = c.photograph_id)
GROUP BY p.id
ORDER BY commentcount DESC

If you also want photo's with zero comments do:
SELECT p.id, COUNT(c.id) as commentcount FROM photographs p
LEFT JOIN comments c ON (p.id = c.photograph_id)
GROUP BY p.id
ORDER BY commentcount DESC

A: SELECT *,
       (SELECT COUNT(*) FROM comments
        WHERE photographs.id = ccomments.photograph_id)) commentcount
FROM photographs

This will probably be faster than the join method. Maybe. You will need to experiment.


text:
Q: Really strange permissions issue on page titles with slashes I'm using:

*

*mediawiki 1.34

*php 7.4

*apache 2.4.46

*mysql 8.0.22

The problem that I'm having is that I get permissions denied errors from the api when I try to edit, move, or delete pages that have a "/" in its title. This happens through the UI and in some cases things just fail silently and I had to open up the browser's dev tools to look at the network tab.
This has been happening for a while now and we've managed to just not use "/" in any of the page titles, but recently the Translate extension was installed and has been causing issues because translations are stored in pages like title/segment/lang.
Saving a translation POSTs this data:
action=edit&
format=json&
title=Translations%3ATest%2FPage+display+title%2Fes&
text=asdasdsasd&
summary=&
assert=user&
token=XXXX19%2B%5C

and it returns this from api.php:
{
  "error":
  {
    "code":"permissiondenied",
    "info":"You are not allowed to execute the action you have requested.",
    "*":"See https://localhost/api.php for API usage. Subscribe to the mediawiki-api-announce mailing list at <https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce> for notice of API deprecations and breaking changes."
  }
}

The user definitely has all of the translation permissions set, this happens even if I set all translate extension permissions to true for "*".
Does anyone possibly know what could be causing these issues? Or if there's some way to debug this to isolate what permission and where it's being checked? It looks like everything else works fine. I don't have very much experience with mediawiki, someone else used to manage it but they've left.

A: Try adding AllowEncodedSlashes NoDecode to your Apache config, and nocanon to the ProxyPass directive in it.


text:
Q: Can I use prepositions 'in' and 'for' interchangebly in this context? Question:

Which option is right. In case if both are right- for which case the using is more appropriate or I can use them interchangeably in some cases?

.

1) IN or/and FOR

*

*I haven't seen him in a few years

*I haven't seen him for a few years

2) IN or/and FOR

*

*I haven't seen him in a seven years

*I haven't seen him for a seven years

A: Both of these are correct and interchangeable:

I haven't seen him in a few years.
  I haven't seen him for a few years.

The article 'a' is not correct in these sentences:

I haven't seen him in a seven years
  I haven't seen him for a seven years

'A few' is an idiom, unlike 'seven', which is a precise number of years and doesn't require the article.
The following sentences are correct:

I haven't seen him in seven years.
  I haven't seen him for seven years.

Personally, I prefer "in a" in these scenarios but there is nothing wrong with "for a".


text:
Q: What is known about the transformation of a power series in which $z^n$ is replaced with $z^{n^2}$? Say we have the function $$G(z) = \sum_{n \geq 0} g_n z^n.$$
Is there a name for the transform T defined so that $$(T(G))(z) = \sum_{n \geq 0} g_n z^{n^2}?$$
Is there anything known about this kind of transformation?

A: If you know a formula for the ordinary generating function of the sequence and its $j^{th}$ derivatives, which must exist for all $j \geq 0$, then this article (2017) provides you with an integral representation of the transformed series in question. In particular, if $G(z)$ is the ordinary generating function of the sequence $\{g_n\}_{n \geq 0}$ and $q \in \mathbb{C}$ is such that $0 < |q| < 1$, then we have proved in the article that
$$\sum_{n \geq 0} g_n q^{n^2} z^n = \frac{1}{\sqrt{2\pi}} \int_0^{\infty}
     \left[\sum_{b = \pm 1} G\left(e^{bt \sqrt{2\log(q)} z}\right)\right] e^{-t^2 / 2} dt. $$ The article terms this general procedure for modifying the original sequence generating function a square series transformation integral, but more generally, some of the most interesting applications of this method include new integral representations for theta functions and classical identities such as the series expansion for Jacobi's triple product.


text:
Q: Como puedo crear base de datos en el almacenamiento externo SD Me gustaría crear la base de datos directamente en el directorio de sistema de archivos donde se guardan los archivos internos de mi aplicación y acceder a estos con getFilesDir().
Me encuentro con el problema que cuando se crea la base de datos dentro del proyecto y hago un backup luego no lo puedo restaurar porque no tengo acceso root.
¿Seria posible hacer esto?. ¿Como seria el código para indicar al creador de la base de datos sqlite que cree esta en la ruta que yo quiero?.
Espero haberme explicado con claridad y espero que me podais ayudar.
Gracias de antemano.


text:
Q: Modifying an Array I have an Array like this
example_array = ['dog', 'cat', 'snake']

And I am trying to append the timestamp to each element of the array and the output should look like
example_array = [{'dog': 'time_stamp'},{'cat':'time_stamp'},{'snake':'time_stamp'}]

I've tried this but the output is incorrect:
a = {}
example_array.each_with_index do |element, i|
  a.merge!("#{element}": "#{Time.now}")
  example_array.delete_at(i)
end

Can anyone suggest me a solution in ruby?
I have tried a lot of ways but couldn't obtain the output like above.

A: Aditha,
How about this?
array = ["cat", "hat", "bat", "mat"]
hash = []
hash.push(Hash[array.collect { |item| [item, Time.now] } ])

OUTPUT:  => [{"cat"=>"2018-02-28 04:23:08 UTC", "hat"=>"2018-02-28 04:23:08 UTC", "bat"=>"2018-02-28 04:23:08 UTC", "mat"=>"2018-02-28 04:23:08 UTC"}]
Instead of item.upcase you would insert your timestamp info.  It gives me hashes inside of array.

A: example_array.product([Time.now]).map { |k,v| { k.to_sym=>v }}
  #=> [{:dog=>2018-02-27 20:42:56 -0800},
  #    {:cat=>2018-02-27 20:42:56 -0800},
  #    {:snake=>2018-02-27 20:42:56 -0800}

]Note this ensures that all values (timestamps) are equal.

A: only weird thing is that you have to use => instead of :
arr = ['dog', 'cat', 'snake']
arr2 = []

for index in 0 ... arr.size
  arr2.push({arr[index] => Time.now})
end

puts arr2

A: ['dog', 'cat', 'snake'].map{|e| [{e.to_sym => "time_stamp"}]}
# => [[{:dog=>"time_stamp"}], [{:cat=>"time_stamp"}], [{:snake=>"time_stamp"}]]


text:
Q: My output does not show in perfect vertical, it shows randomly in python My ip address, country, and count output shows in random vertical. This is my print code:
print "Source IP\t\t\tCountry\t\t\tCode\t\t\tCount"
    for ip, count in non_base_10_ip:
        print "{0}\t\t\t\t\t\t\t\t\t{1}\t\t\t\t\t\t\t\t\t{2}\t\t\t\t\t\t\t\t\t{3}".format(ip,gi.country_name_by_addr(ip),gi.country_code_by_addr(ip), count)+ "\r"
    for base10ip,count in base_10_ip:
        print "{0}\t\t\t\t\t{1}\t\t\t\t\t{2}\t\t\t\t\t{3}".format(base10ip,gi.country_name_by_addr(base10ip),gi.country_code_by_addr(base10ip), count)+ "\r"

but my output shows like this:
115.237.36.185                                  China                                   CN                                  2
185.35.62.206                                   Switzerland                                 CH                                  2
74.82.47.34                                 United States                                   US                                  2
114.149.150.237                                 Japan


text:
Q: Within an equation, how would I put text directly above other text? I've seen something a little like this in a textbook I'm reading and I'm not sure how this would be written in LaTeX, can anyone help?

A: Not sure what it means, but…
\documentclass{article}
\usepackage{amsmath}

\newcommand{\sincos}{\mathop{\begin{array}{@{}l@{}}\sin\\\cos\end{array}\Big\}}}

\begin{document}

\[
Z = A \sincos k_1x \sincos k_1y \sincos ckt
\]

\end{document}


text:
Q: How does $ \sum \limits_{n=0}^\infty\left (\frac{1}{z^2}\right)^m = \frac{z^2}{z^2-1}$? This was given by an exercise's answer, but the steps in between was not given, so I was wondering how $$\sum \limits_{n=0}^\infty \left(\frac{1}{z^2}\right)^n=\frac{z^2}{z^2-1}$$ The exercise was related to $z$-transform.

A: Just simplify:
\begin{equation}
\frac{z^2}{z^2-1}=\frac{1}{1-\frac{1}{z^2}}.
\end{equation}
Using the geometric series formula
$$ \sum_{n=0}^\infty ar^n=\frac{a}{1-r}$$
for $\lvert r\rvert<1$, we find that taking $r=\frac{1}{z^2}$, for $\lvert\frac{1}{z^2}\rvert<1$ we have
\begin{equation}
\frac{z^2}{z^2-1}=\frac{1}{1-\frac{1}{z^2}}=\sum_{n=0}^\infty \frac{1}{z^{2n}}.
\end{equation}

A: You may use the infinite geometric series formula:
$$\sum_{k=0}^\infty ar^k=\lim_{n\to \infty}\sum_{k=0}^n ar^k=\lim_{n\to \infty}\frac{a(1-r^{n+1})}{1-r}=\frac{a}{1-r}-\lim_{n\to \infty}\frac{a(r^{n+1})}{1-r}=\frac{a}{1-r}$$
$\because$ $r^{n+1} \to 0$ when $n\to \infty$ since $
\vert r\vert \lt1$
In your case, $a=1$ and $\frac {1}{z^2}$. Hence, assuming $\vert z\vert \gt 1$,
$$\sum_{k=0}^\infty \left(\frac{1}{z^2}\right)^k=\frac{1}{1-\frac{1}{r^2}}=\frac{r^2}{r^2-1}$$


text:
Q: Processing-time billing in Amazon EC2 I think my question is fairly basic, but I would like a clarification: in the Pricing part of AWS we can see that Amazon charges people around .10 by the 'instance computing hour'.
I've seen in a blog post somewhere (can't remember where exactly, and even if I did I think it was in Portuguese anyway) that this way your minimum monthly payment would be $72 (= .10 $s/hour x 24 hours x 30 days). Is this correct? (I don't think it is!)
In my understanding is that this 'virtual computing time' is only used when your machine is actually doing something (serving pages, serving the admin via ssh, whatever), so real billable usage would be less than 720 hours/month in most webserver scenarios. Is my view correct?
If it is, then it leads me to another question: is it economically interesting to buy access to one of these instances for testing? I mean, would I have the 'freedom' to 'forget' about it for a month and receive a very-close-to-zero (as in, a few cents) bill? Do you do it/know of anybody who does? Any thoughts on the matter (as in, "yes, it's a good idea", or "yes, but there's this 'gotcha': ...", or "no, nobody does it because of...")?
PS: sorry for the loong question text. I highlighted the main questions for easy view. Also, I'm not sure if this question is actually more than one and if it's desirable for the community, so, sorry if it is too!
Thanks in advance!

A: Amazon charges you by the time you keep your server 'on' not by the time you actually do something. so $72/month is correct + tax.
Point of Amazon is this: you have 5 servers that you keep on all the time, then your web load increases in between 12pm - 1pm then you write a code that your servers initiate 50 more servers to balance the load, and you turn them off.
so for this operation,  your monthly cost is:
$72*5 = $360 for the first 5 servers
daily cost is
 $0.10*50 = $5
if you did this every day then you would pay $5*30 = $150 extra.
Without Amazon, you'd require 55 dedicated servers which would cost you ~55*$50 = $2750, so you save ~$2250 on server costs.
But if you don't need to fire up 50 servers and turn them off, amazon wont save you a lot, in fact it can be more expensive compared to: bit.ly/PK60k
There you can get $20/month servers with full cloud computing abilities (e.g. increasing server resources without migrating to a new server unlike amazon). They give 4500 GB traffic for free which would also cost you $450/month on Amazon.
We have recently have left Amazon it becomes really expensive once your site is up and running being still less expensive than dedicated setups.
Most irritating thing about Amazon is we paid a certain amount every month for ten months, one day I woke up and saw that our bill is 100 times more than usual, they didn't bother to warn us. So you can basically wake up to a million dollar bill, there is no protection or warning against that. They said we agreed to that on the agreement, it was our responsibility to check by logging in to amazon account everyday.
I hope this explains.

A: Regarding the total monthly bill, the short answer is yes - an instance at $0.10/hour will be about $72 for a month.  However, you can purchase reserved instances which can work out up to about 50% of the price if the server is being run continually.  In the example of the m1.small type of server ($0.10/hour normally), the yearly cost would be $490 with a reserved instance (one year reservation) or $876 on "pay as you go".
The answer to your second question is no.  You are billed for an instance hour, the whole time that the instance is up, running and able to take requests, rather than say, a CPU-hour which might be just the "work" done on the instance.  You will be billed the price for the rounded up number of hours that the instance has been on for.  If you turn it on for 5 minutes and shut it down, you will be charged $0.10.
However, I'd argue that it could be very economical for software testing if it's shut down while you're not using it.  Testing is one of the most common use cases for EC2, where you're able to start up an instance, test software for a few hours and then shut it down, working out much cheaper than leaving it running while you're doing other things/sleeping.


text:
Q: Using JLabel for a background image When I run the code it just opens an empty window
I also important whatever is necessary
relevant parts of the code:
public class Game extends JFrame implements ActionListener,KeyListener{
    private JLabel background;
....
public Game(){
background=new JLabel(new ImageIcon("/graphics/board.gif"));
...
this.add(background);
this.setSize(800,600);
this.setVisible(true);...

I tried adding the JLabel to a JPanel and then add it to the frame but it still shows nothing in the window

A: Originally the code was:
JLabel background = new JLabel("/graphics/board.gif");

This would not set the image at the path described, Suggest that the following method is used (this could be simplified to just use a different JLabel constructor but steps shown for clarity)
Create and load the image and then set the icon for the Label As follows
ImageIcon icon = new ImageIcon("/graphics/board.gif");
JLabel background = new JLabel();
background.setIcon(icon);

Link to ImageIcon Java Doc

A: It is important to set in the layout the order in which the elements are displayed , maybe you have something that is displayed over the label..

A: I'm guessing you have a directory structure something like:

-c:\java
  - source (for source and class files)
    - graphic (for your images)

background=new JLabel(new ImageIcon("/graphics/board.gif"));

Don't specify the leading "/" in the file name. That tells Java to look at the root of the C drive, not at the directory where your class is executing from.
Also, don't use:
this.setSize(800,600);

The image does not stretch to fill the size of the frame. Intead you should be using:
this.pack();

so the frame will be the size of the image.