text:
Q: Parse xml data from xsd data structure? I have to import around 10 000 database entries from a xml file but with xsd file data structure, how can I use correctly xsd file to import xml data? I use PHP.
This is my xsd schema:
<?xml version="1.0" encoding="UTF-8"?>
<!-- edited with XMLSpy v2010 rel. 3 (x64) (http://www.altova.com) -->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
    <xs:element name="shopInformations">
        <xs:annotation>
            <xs:documentation>All products</xs:documentation>
        </xs:annotation>
        <xs:complexType>
            <xs:sequence minOccurs="0" maxOccurs="unbounded">
                <xs:element name="productInformation">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="title" type="xs:string"/>
                            <xs:element name="author" type="xs:string"/>
                            <xs:element name="productcode" type="xs:string" minOccurs="0"/>
                            <xs:element name="content"/>
                            <xs:element name="sections">
                                <xs:complexType>
                                    <xs:sequence maxOccurs="unbounded">
                                        <xs:element name="section">
                                            <xs:complexType>
                                                <xs:sequence>
                                                    <xs:element name="title"/>
                                                </xs:sequence>
                                                <xs:attribute name="id" type="xs:string" use="required"/>
                                            </xs:complexType>
                                        </xs:element>
                                    </xs:sequence>
                                </xs:complexType>
                            </xs:element>
                        </xs:sequence>
                        <xs:attribute name="type" use="required">
                            <xs:simpleType>
                                <xs:restriction base="xs:string">
                                    <xs:enumeration value="public"/>
                                    <xs:enumeration value="reseller"/>
                                </xs:restriction>
                            </xs:simpleType>
                        </xs:attribute>
                        <xs:attribute name="version" type="xs:string" use="required"/>
                        <xs:attribute name="lang" use="required">
                            <xs:simpleType>
                                <xs:restriction base="xs:string">
                                    <xs:enumeration value="en"/>
                                    <xs:enumeration value="es"/>
                                </xs:restriction>
                            </xs:simpleType>
                        </xs:attribute>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

My xml file has around 450MB and I cannot open it...

A: As the details are a bit vague, I've had to guess quite a bit, but to read such a large file, it's better to use XMLReader to do this.  XMLReader allows you to read the file in segments rather than reading the whole file in one go.
The following code show a simple way of reading the data, but as I have had to create some test data from the XSD - it may not be exactly correct.
<?php
error_reporting ( E_ALL );
ini_set ( 'display_errors', 1 );

$xml = new XMLReader;
$xml->open('t1.xml');
while( $xml->read() ) {
    if($xml->name == "productInformation") {
        $product = $xml->readOuterXML();
        $prod = new SimpleXMLElement($product);
        echo "title=".$prod->title.PHP_EOL;
        echo "author=".$prod->author.PHP_EOL;
        echo "productcode=".$prod->productcode.PHP_EOL;
        echo "content=".$prod->content.PHP_EOL;
        foreach ( $prod->sections->section as $section)    {
            echo "section id=".$section['id'].PHP_EOL;
            echo "section title=".$section->title.PHP_EOL;
        }

        echo PHP_EOL;
        $xml->next();
    }
}

If your going to use values returned by SimpleXML, you may need to cast the value, so $prod->title when being assigned to a string field would need to be (string)$prod->title


text:
Q: Tweepy streaming module language filter not working I am trying the following code to extract tweets in french but it returns tweets in english and some other languages. Is there a syntax error ?
import sys
import tweepy
import config as config

consumer_key= config.CONSUMER_KEY
consumer_secret= config.CONSUMER_SECRET
access_key = config.OAUTH_TOKEN
access_secret = config.OAUTH_TOKEN_SECRET

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)

class CustomStreamListener(tweepy.StreamListener):
    def on_status(self, status):
        print status.lang
            #, status.user.location, status.user.description

    def on_error(self, status_code):
        print >> sys.stderr, 'Encountered error with status code:', status_code
        return True # Don't kill the stream

    def on_timeout(self):
        print >> sys.stderr, 'Timeout...'
        return True # Don't kill the stream

sapi = tweepy.streaming.Stream(auth, CustomStreamListener())
sapi.filter(track=["rame", "lent", "long", "beug", "beugg", "beugge", "bug"], languages = ["fr"])

A: a bit of an old post but I've been experiencing the same problem lately : the keyword search does not seem to work properly, it seems to return tweets even if they don't have the keyword. The solution which worked for me was to use twython and the API v2...

A: Try language instead of languages.

redpajama_set_name: RedPajamaStackExchange


text:
Q: HTML - displaying title attributes on page The html below is working properly, but how do I display title attributes on the browser below the video, for each <video> element?
<!DOCTYPE HTML>

<title>Projekktor Version 8 Test</title>
<link rel="stylesheet" href="theme/style.css" type="text/css" media="screen" />

    <video id="player_a" class="projekktor" poster="https://i.scdn.co/image/00d97c99f9fb5872e9a44f06ae7e20fd011de125" title="Faust Arp" width="640" height="360" controls>
        <source src="https://p.scdn.co/mp3-preview/7f8e0f1c60eaa0817e07f48d5954887ca148ef37?cid=null" /></video>
    <video id="player_a" class="projekktor" poster="https://i.scdn.co/image/0d1460c036897175f4631e8480ea4a2217bf5447" title="Daydreaming" width="640" height="360" controls>
        <source src="https://p.scdn.co/mp3-preview/fbf970f6ee1e7d849de08017d3688406107c751a?cid=null" /></video>

A: Try this :
video:after {
   content: attr(title);
   display: block;
}

a:after {
  content: attr(title);
  display: block;
}
a link

The fiddle use a link but it should work with all elements as long as pseudo-element are enabled.
The attr CSS "function" (lack of a better term) can only be used in the content property of a pseudo element.
It allows you to fetch any attribute value by its name.
You can then style it with CSS with minor restrictions.

A: Using jQuery, you can get the title using $.attr(), and you can insert that as text after the video using $.after()

$('video').each(function() {
  $(this).after('
'+$(this).attr('title')+'
');
})

<video id="player_a" class="projekktor" poster="https://i.scdn.co/image/00d97c99f9fb5872e9a44f06ae7e20fd011de125" title="Faust Arp" width="640" height="360" controls>
    <source src="https://p.scdn.co/mp3-preview/7f8e0f1c60eaa0817e07f48d5954887ca148ef37?cid=null" />
</video>
<video id="player_a" class="projekktor" poster="https://i.scdn.co/image/0d1460c036897175f4631e8480ea4a2217bf5447" title="Daydreaming" width="640" height="360" controls>
    <source src="https://p.scdn.co/mp3-preview/fbf970f6ee1e7d849de08017d3688406107c751a?cid=null" />
</video>


text:
Q: Swapping elements with next smaller value Given an array of positive integer, we need to exchange each element with first element which is less than it(current element) as we move from left to right.
Example
{ 3 , 5 , 12, 2 ,11 }
{ 2 , 3 , 5 , 11, 12 }

Brute-force solution simulation for better understanding of the problem
{ 5, 11, 2, 7, 2 }
After first exchange  { 2, 11, 5, 7, 2}
After second exchange { 2, 5, 11, 7, 2}
After third exchange  { 2, 5, 7, 11, 2}
After fourth exchange { 2, 5, 7, 2, 11}

Can anyone think of a solution which is better O(n^2).
I was first thinking of maintaining a double ended queue and as we travel from first element towards right, we can try to maintain next smallest element of other in between.
Like for the First case, I will do something like this
while i am finding next element of 3, I will maintain a curr_next to 5. If before encountering the next small element for 3, i encounter one of 5, then I will enqueue it but it hardly improve the performance and still O(n^2)
EDIT: We have to move from left to right.
Simulation of first example -
{ _3_ , 5 , 12, 2 ,11 }
{ 2,  _5- , 12, 3, 11 }
{ 2,  3, _12_ , 5, 11 }
{ 2, 3, 5, _12_,   11 }
{ 2, 3, 5,  11 ,   12 }

A: I can suggest a solution with O(n*logn) complexity based on usage of Segment Trees.
Algorithm:

*

*Construct an array of pairs (value, index) which is formed from values and corresponding indexes of elements of the initial array. Let's call it array_2

*Sort the obtained array by value.

*Construct a Segment Tree on this array which allows us to find the element with minimal index on a given interval. Let's call it SegmentTree

*Sequentially pass through the values array (the one initially given). For each element array[ i ] fing the element which it has to be swapped with as follows:
4.1. Find the value of the current element in the array_2 using binary search. Let it be found at some position k. After this all elements in the array_2 below position k are the elements in the original array which are smaller than the current one. As you will see later, all of them also have greater indexes than the current one (because we will remove the element with index i from array_2 after i-th step).
4.2. Now we have to find the element with minimal index in array_2 on interval [0, k-1]. This can be done querying the SegmentTree constructed on step 2. After we get the element with minimal index, we perform the corresponding swap in the original array, swap the indexes of these elements in array_2 (because they have been changed in the original array).
4.3. Perform two update operations on the SegmentTree - remove the element with index currently being processed in the original array, and update the value of index of the element which was swapped with the currently processed index.
After performing steps 4.1 - 4.3 n times we will obtain the target array.
Complexity:
We pass through the original array - n iterations. For each iteration we perform a binary search, a SegmentTree query and two SegmentTree updates, each of them taking logn time to perform. Summary O(n*logn).

A: The problem is not stated very well. After we exchange two elements, do we continue from the same position, and move right when no smaller element is found? Or do we move right immediately after the exchange? In the first case we end up with a sorted array.
In the second case I would maintain a balanced search tree of elements and indices. Start at the leftmost element, an repeat these steps:

*

*Set I = 0, N = length A

*Loop until I < N

*

*Add the current element to the tree, with its index

*Set L=-1

*Repeat these steps

*

*Find the smallest element larger than A[I] in the tree.

*If there's such an element A[K] and K > L

*

*swap A[I] and A[K] in the array

*remove A[K] from the tree (it will not be swapped any more)

*update index of the new A[I] in the tree

*set L = K

*If there's no such element, finish and increment I

The complexity of this is probably O(n log n) or something. This is untested and unproved, use at your own risk.


text:
Q: Confusion about Wakimoto's chiral differential operators on $\mathbf{P}^1$ It is a classical result of Wakimoto that the sheaf of chiral differential operators $D_{ch}$ on $\mathbf{P}^1$ has global sections
$$D_{ch}(\mathbf{P}^1)\ \simeq\ L_{-2}(\mathfrak{sl}_2)$$
the simple quotient affine vertex algebra at critical level $-2$. Apparently the map
$$L_{-2}(\mathfrak{sl}_2)\ \to\ D_{ch}(\mathbf{A}^1)\ =\ \mathbf{C}[x_0,x_{-1},...,\partial_{-1},\partial_{-2},...\ ]$$
sends the fields $e(z),h(z),f(z)$ to $\partial(z)$, to $-2:x(z)\partial(z):-2$ and to $:x(z)^2\partial(z):+x'(z)$, where we have the fields
$$x(z)\ =\ \sum_{n\in\mathbf{Z}} x_nz^{-n},\ \ \ \partial(z)\ =\ \sum_{n\in\mathbf{Z}} \partial_nz^{-n-1}.$$
Question: I am having trouble showing that $-2:x(z)\partial(z):-2$, or equivalently just $\alpha=:x(z)\partial(z):$, glues to a global section of $D_{ch}$.
Indeed, the transition function $\tau: D_{ch}(\mathbf{C}^\times)\to D_{ch}(\mathbf{C}^\times)$, where $D_{ch}(\mathbf{C}^\times)=D_{ch}(\mathbf{A}^1)[x_0^{-1}]$, sends
$$x(z)\ \mapsto\ x(z)^{-1}, \ \ \ \partial(z)\ \mapsto \ :x(z)^2\partial(z):+2x'(z)$$
and so it sends
$$\alpha\ =\ :x(z)\partial(z):\ \mapsto\ :x(z)\partial(z):+2x'(z)x(z)^{-1}.$$
Thus $\alpha$ glues to a global section iff $\tau \alpha$ has no pole at $x_0=0$.
But my problem is that $x'(z)x(z)^{-1}$ has a pole! For instance,
$$x'(z)x(z)^{-1}|0\rangle\ =\ -x_{-1}x_0^{-1}|0\rangle \text{ mod }z.$$

A: There are a couple of errors in the statement of the question. First in the transformation formula that I suppose you took from MSV "Chiral de Rham complex". Let us denote $\tilde{x} = x^{-1}$ and $\tilde{\partial} = x^2 \partial + 2 x'$. We assume the standard OPE $\partial(z) \cdot x(w) \sim \frac{1}{z-w}$ as the only non-zero OPE among generators.
In general for a function $f = f(x)$, denoting by $f(z)$ the corresponding field, we have $\partial(z) \cdot f(w) \sim \frac{f'(w)}{z-w}$
Notice that $x(z) \cdot \partial(w) \sim - \frac{1}{z-w}$ and in general $f(z) \cdot \partial(w) \sim - \frac{f'(w)}{z-w}$.
Now we compute $x^{-1}(z) \cdot \partial(w) \sim \frac{x^{-2}(w)}{z-w}$, from where we obtain
$$
\tilde{x}(z) \cdot \tilde{\partial}(w) = x^{-1}(z) \cdot x^2(w)\partial(w) \sim \frac{1}{z-w} \neq - \frac{1}{z-w} \sim x(z) \cdot \partial(w)
$$
So these don't glue to give a sheaf. The second error is that even assuming your transformation formula, the transformation for $\alpha$ is not correctly computed. I assume here that you missed quasi-associativity. Namely
$$
:x^{-1}(z) :x^2(z) \partial(z): :\ \neq\ ::x^{-1}(z) x^2(z): \partial(z):\ =\ :x(z) \partial(z):
$$
When you fix both issues everything will be fine.


text:
Q: Which asymptotics are "better"? I am considering the polynomial
$$
p(c,x):=x^{c+1}-x^c-1
$$
By $x_c$ denote the largest positive real root of $p(c,x)$.
From mathematics we know that $x_c\in (1,1+\frac{\log(c)}{c})$ and that, for large $c$, $x_c$ behaves like $1+\frac{\log(c)}{c}$ which means, in mathematical terms, that $x_c\sim 1+\frac{\log(c)}{c}$ as $c\to\infty$ or more formally:
$$
\lim_{c\to\infty}\frac{x_c}{1+\frac{\log(c)}{c}}=1.
$$
My numerics show that we also seem to have
$$
\lim_{c\to\infty}\frac{x_c}{1+\frac{1}{c}}=1.
$$
In the following picture, the blue curve is the function
$$
f(c)=\frac{x_c}{1+\frac{\log(c)}{c}}
$$
and the orange curve is the function
$$
g(c)=\frac{x_c}{1+\frac{1}{c}}.
$$
It seems that the blue curve reaches the value 1 faster than the orange curve.
Does this mean that it is better to say that
$$
x_c\sim 1+\frac{\log(c)}{c}, c\to\infty
$$
than to say that
$$
x_c\sim 1+\frac{1}{c}, c\to\infty?
$$
Note $\frac{1}{c}\leq\frac{\log(c)}{c}$ for large $c$. So I would have expected that $1+\frac{1}{c}$ is a better approximation.

A:
Note $\frac{1}{c}\leq\frac{\log(c)}{c}$ for large $c$. So I would have expected that $1+\frac{1}{c}$ is a better approximation.

For all you know, $x_c$ could be equal to $1+\frac{1}{c}$, and it could as well be equal to $1+\frac{\log c}{c}$. All of what you said would still hold. Except that obviously the "best" approximation in not the same in both cases. So you should not expect $\frac{1}{c}\leq\frac{\log(c)}{c}$ to tell you anything about which approximation is the best.
Secondly, note that $$\lim_\limits{c\to \infty}\frac{1+\frac{\log(c)}{c}}{1+\frac{1}{c}}=1$$
therefore any sequence equivalent to the numerator is also equivalent to the denominator. Which of these approximations is the "best" depends on the sequence. You can't tell anything more without looking at higher order terms.

A: No
When you say

$$\lim_{c\to\infty}\frac{x_c}{1+\frac{\log(c)}{c}}=1 \text{ and } \lim_{c\to\infty}\frac{x_c}{1+\frac{\log(c)}{c}}=1$$

this is hard a surprise since $x_c \to 1$ as $c$ increases.
The fact that your blue line is closer to the green line than the orange line is suggests that  $1+\frac{\log(c)}{c}$ is a better approximation to $x_c$


text:
Q: How often are values duplicated on the stack? When you have a function that accepts an array as an argument and calls another function with that array and that calls another function with it and so forth the stack will contain many copies of the pointer to that array. I just thought of an interesting way to alleviate this problem but I'm wondering whether or not it is worth implementing.
Does anyone have any idea how often stacks contain duplicate pointers in practice?
EDIT
Just to clarify, I am not optimizing a given program but, rather, am considering writing a new kind of optimization pass for my VM. My benchmarks have indicated that my current solution causes up to 70% of the total running time to be spent in stack manipulations. The optimization pass I am thinking of would generate code at compile time that would perform the same actions but pointers would (potentially) be duplicated on the stack less often. I am interested in any prior studies that have measured the number of duplicates on the stack because this would help me to quantify my optimization's potential. For example, if it is known that real programs do not push pointers already on the stack in practice then my optimization is worthless.
Moreover, these stack manipulations are due to the code generated by my VM making sure locally-held pointers are visible to the garbage collector and not due only to function parameters as both answerers have currently assumed. And they are actually operations on a shadow stack rather than the main stack.

A: First of all, the answer will depend on your application.
Secondly, even with high duplication, I doubt there is much sense in implementing the mechanism you describe, or even that it is possible in a general case. If you call a method and you pass it parameters, you must do it either one way or another.
There may be advantages to doing it in some specific way - for example there are several function calling conventions and many C/C++ compilers (e.g. gcc) let you choose between passing parameters on the stack or via registers. In certain cases, the latter may be faster - you can try and benchmark if it helps your application.
But in a general case, the cost of detecting duplicated values on the stack and "reusing" them would probably much exceed any gains from having a smaller stack. The code for pushing and popping values is really simple (just a few CPU instructions in an optimized case), code for finding and reusing duplicates - hardly so. You would also have to somehow store the information about which values are already on the stack and how to find them - a nontrivial data structure. Except for some really weird cases, I don't think this would be smaller than the actual copied data itself.
What you could do, would be to rewrite your algorithm in such way that some function calls are eliminated. For example, if your function's result only depends on the input arguments, you could somehow cache or memoize the results, thus avoiding repeated calls with the same values. This may indeed bring some gains, though it's usually a memory vs CPU time tradeoff. Getting an advantage both in memory and in CPU time is rarely possible. Also, rewriting your algorithm is not really "avoiding duplication of data on the stack".
Any way, for the original question, I think the idea is not viable and you should look at optimizations elsewhere.
PS: You use case may somewhat resemble tail-call optimization, so perhaps that's a direction worth looking at - but if you implement it yourself, I would also consider this to fall into the "change your algorithm" category. Maybe changing from a recursive algorithm to an iterative one could help also.

A: Can I suggest getting some exposure to actual performance tuning?
(Here's my canonical example.)
Between the time a program starts and the time it ends, of the cycles it uses, it obviously uses 100% of those cycles.
If it goes in and out of functions, and passes pointers to an array, but does nothing else, then there's no surprise that a high percent of time goes into function entry and exit, and passing arguments.
If a program P is written to do task T, there are a multitude of other programs P' which could also do task T. Some of them take fewer cycles than all the others, and those are the optimal ones.
The way the optimal ones differ from the non-optimal ones is that the non-optimal ones are doing things that can be done without.
So, to optimize any program, find out what cycles are being spent that don't have to be, and get rid of those activities. That link shows in great detail how I do it.
Trying to pass fewer arguments to functions might or might not be necessary, depending on what your diagnostics tell you.


text:
Q: Angular 2 objects, properties and variable scope I have a Angular 2 object with the following properties:
export class ThreedViewerComponent implements OnInit {
  private aScene: THREE.Scene;
  private ThreeModel: THREE.Mesh;

and the following method:
private initStage() {

    // create a WebGL scene, camera and raycaster. Raycasting is used for mouse picking (working out what objects in the
    // 3d space the mouse is over) amongst other things.
    this.aCamera = new THREE.PerspectiveCamera(45, this.aSceneSettings.width / this.aSceneSettings.height, 0.1, 2000);
    this.aScene = new THREE.Scene();
    this.aRaycaster = new THREE.Raycaster;
    this.ThreeModel = new THREE.Mesh;

    this.loader = new PLYLoader();

    this.loader.load('assets/data/GuyFawkesMask.ply', function (geometry) {

      // Create 3D model
      this.ThreeModel = new THREE.Mesh(geometry,
        new THREE.MeshPhongMaterial(
          {
            color: 0xFFFFFF,
            //vertexColors: THREE.VertexColors,
            shading: THREE.FlatShading,
            shininess: 0
          })
      );

      this.aScene.add(this.ThreeModel);
    });

I think I am confused about variable scopes.
I can make the code working by getting rid of the references this.ThreeModel and this.aScene inside the this.loader.load function.
I thought that external variables (properties) are visible inside a function in JavaScript but it does not seem to be the case.
The reason why I want to use this.ThreeModel and this.aScene is that I can get old of the current model and scene and do some clean up when loading a new model.
What's wrong in my assumptions?

A: Try using ES6 arrow function:
this.loader.load('assets/data/GuyFawkesMask.ply', (geometry) => {
    // Create 3D model
    this.ThreeModel = new THREE.Mesh(geometry,
    new THREE.MeshPhongMaterial(
        {
            color: 0xFFFFFF,
            shading: THREE.FlatShading,
            shininess: 0
        })
    );
    this.aScene.add(this.ThreeModel);
});

A: You can use static and access it within your class block.
export class ThreedViewerComponent implements OnInit {
  static aScene: THREE.Scene;
  static ThreeModel: THREE.Mesh;

And in the function:
private initStage() {

    // create a WebGL scene, camera and raycaster. Raycasting is used for mouse picking (working out what objects in the
    // 3d space the mouse is over) amongst other things.
    this.aCamera = new THREE.PerspectiveCamera(45, this.aSceneSettings.width / this.aSceneSettings.height, 0.1, 2000);
    ThreedViewerComponent.aScene = new THREE.Scene();
    this.aRaycaster = new THREE.Raycaster;
    ThreedViewerComponent.ThreeModel = new THREE.Mesh;

    this.loader = new PLYLoader();

    this.loader.load('assets/data/GuyFawkesMask.ply', function (geometry) {

      // Create 3D model
      ThreedViewerComponent.ThreeModel = new THREE.Mesh(geometry,
        new THREE.MeshPhongMaterial(
          {
            color: 0xFFFFFF,
            //vertexColors: THREE.VertexColors,
            shading: THREE.FlatShading,
            shininess: 0
          })
      );

      ThreedViewerComponent.aScene.add(ThreedViewerComponent.ThreeModel);
    });


text:
Q: Como implementar um "listener" em javascript para visualização da tela? Eu preciso implementar uma alteração no meu código para que ao mudar de DIV, ou seja, deixar de visualizar a página, o som que está sendo executado pare automaticamente, conforme já acontece com os vídeos do Facebook/Instagram nas plataformas web. Eu fiz o seguinte código:
<audio id="myAudio" src="../media_a/song3.mp3" preload="auto">
</audio>

<script type="text/javascript" charset="utf-8" async defer>
var myAudio = document.getElementById("myAudio");
var isPlaying = false;

function togglePlay() {
if (isPlaying) {
myAudio.pause()
} else {
myAudio.play();
}
};
myAudio.onplaying = function() {
isPlaying = true;
};
myAudio.onpause = function() {
myAudio.currentTime = 0;
isPlaying = false;
};
</script>

O botão ON/OFF está 100% funcional, mas quando eu chamo outra DIV, num sistema de página única, o áudio deve parar de ser executado, porém ele continua. Sendo que cada DIV tem uma audiodescrição diferente, como implemento um "listener" para que ao deixar de visualizar aquela DIV o som pare automaticamente?


text:
Q: stack select() function doesn't work in Visual Studio The following is part of the example code from http://curl.haxx.se/libcurl/c/sendrecv.html:
static int wait_on_socket(curl_socket_t sockfd, int for_recv, long timeout_ms)
{
  struct timeval tv;
  fd_set infd, outfd, errfd;
  int res;

  tv.tv_sec = timeout_ms / 1000;
  tv.tv_usec= (timeout_ms % 1000) * 1000;

  FD_ZERO(&infd);
  FD_ZERO(&outfd);
  FD_ZERO(&errfd);

  FD_SET(sockfd, &errfd); /* always check for error */

  if(for_recv)
  {
    FD_SET(sockfd, &infd);
  }
  else
  {
    FD_SET(sockfd, &outfd);
  }

  ///* select() returns the number of signalled sockets or -1 */
  res = select(sockfd + 1, &infd, &outfd, &errfd, &tv);
  return res;
}

It worked fine on Linux, but when I brought it over Visual Studio 2010, it complains about the select() function. I compiled and linked all the cURL libraries/dlls correctly, and I even downloaded stuff as http request.
But when I tried to use the socket select() function, it complains with the following error:
error LNK2028: unresolved token (0A00034C) "extern "C" int __stdcall select(int,struct fd_set     *,struct fd_set *,struct fd_set *,struct timeval const *)" (?select@@$$J220YGHHPAUfd_set@@00PBUtimeval@@@Z) referenced in function "int __cdecl `anonymous namespace'::wait_on_socket(unsigned int,int,long)" (?wait_on_socket@?A0x7d9db21b@@$$FYAHIHJ@Z)

error LNK2019: unresolved external symbol "extern "C" int __stdcall select(int,struct fd_set *,struct fd_set *,struct fd_set *,struct timeval const *)" (?select@@$$J220YGHHPAUfd_set@@00PBUtimeval@@@Z) referenced in function "int __cdecl `anonymous namespace'::wait_on_socket(unsigned int,int,long)" (?wait_on_socket@?A0x7d9db21b@@$$FYAHIHJ@Z)

Also, it seems that the select() function is compatible with Windows:
http://msdn.microsoft.com/en-us/library/ms740141(VS.85).aspx
Am I missing something? Can someone tell me how to get around this problem?
Thanks, --Rudy

A: You must link with the Microsoft socket library. Tell your linker to use Ws2_32.lib within your project.
In Visual Studio 2010 add this lib to  Project->Properties->Linker->Input->Add. Dependencies.
Or add this lib inside your code with:
#pragma comment(lib, "Ws2_32.lib")


text:
Q: Display titles above each printed table I need your assistant and help in solving the issue while displaying the records in a table. I am looking for a group header to be placed above each printed table for its related category and subcategory, as well as, the no. of the records for each table to be shown at the top of the table.
The table contains columns for category, subcategory, name. ex:
Category    Subcategory     Name
CON         Retail          AAA
CON         Wholesale       BBB
SPEC        Retail          CCC
What I am looking for is the below layout:
Category/Subcategory (No. of records) –similar to a group header
Name – Country ..etc ----Table header
table records
Here is my code below:
<%
//Retrieve the values from the DB
while (rs.next())
{
    category_name1=rs.getString("category_name");
    subcategory_name1=rs.getString("subcategory_name");
    //to compare the existing category with the previous one and to display group header
    if ((category_name1).equals(temp_category_name) ) {
        category_name1="";
%>
<%=category_name1%> / <%=subcategory_name1%> <%=count%>  //Currently it is showing duplicate values many times and the count is wrong
<%
}
if (!(subcategory_name1).equals(temp_subcategory_name)) {
    count=0;
%>

            No.
             Name
            Country

<%
}
%>

<%
    name=rs.getString("name");
    country_name=rs.getString("country_name");
    temp_category_name=category_name1;
    temp_subcategory_name=subcategory_name1;
    count++;
%>

            <%=i%>
            <%=institution_name%>
            <%=country_name%>

<%
}
%>

The problem in the above code is that it is showing the group headers category & sub catgeory multiple times and the count is incorrect. So, please assist me in correcting the above one.

A: Take a look at This code:
    if ((category_name1).equals(temp_category_name) )
    {
       category_name1="";  ///HERE IS YOUR PROBLEM!!!
    }
    ....
    ....
    temp_category_name=category_name1; ///PROBLEM ABOVE MESSES THIS UP.

Setting category_name1 to empty string when its equal to the last category, and then setting the last category for the next iteration to category_name1 which is now empty string, ensures that if the category occurs more than twice, the name is going to get printed again.   Instead of setting category_name1 to empty string you could use an if-statement to print it as an empty string but leave the real value in the variable.
There are other problems with this code, but this is the main one.  Also, someone on here will inevitably tell you "Don't use scriptlets, use JSTL."
As for the record count.  The way you're doing it, you would have to display the record count at the end of the category, not the beginning.


text:
Q: cakephp send and get json i have tag in cakephp like this:
var url_save = "<?php echo $this->Html->url(array('controller' => 'users','action' => 'save_template')) ;?>";
     $.ajax({
    url  : url_save,
    type : "POST",
    data : JSON.stringify(templates),
    dataType : 'json'
     });

how the controller can take the data value?

A: You can use $this->request->data on the Controller the usual way.

A: you can get json data using $this->data in controller, you can check if the request is ajax if you want using $this->RequestHandler->isAjax() but you must also add RequestHandler in component variable.


text:
Q: cakephp: setting routing / pagination options I have a rule which looks like this:
Router::connect('/Hotels', array('controller' => 'gesamtobjekt', 'action' => 'search', 'cat' => 8));

The url looks like this: domain.com/Hotels
My paginations urls like this: domain.com/Hotels/page:2
For language based urls I have a rule like:
Router::connect('/:language/:catname/*', array('controller' => 'gesamtobjekt', 'action' => 'search', 'cat' => 8), array(
'catname' => 'Hotels|Hoteles',
'language' => 'eng|spa|fre|rus'
));

The url looks like this: domain.com/eng/Hotels
In that case I these params available, so I can be sure, that I am in the right rule.
'language' => 'eng',
'catname' => 'Hotels',
'cat' => (int) 8

I wonder why my pagination links look like this:
domain.com/gesamtobjekt/search/language:eng/page:2

What can I do to get a pagination url like domain.com/eng/Hotels/page:2?
What is missing in my rule?
Please advise, thank you so much in advance!

A: Try like this, May be it will help you.
Router::connect('/:language/:catname', array('controller' => 'gesamtobjekt', 'action' => 'search', 'cat' => 8), array(
    'pass' => array('language', 'catname'),
    'catname' => 'Hotels|Hoteles',
    'language' => 'eng|spa|fre|rus'
));

A: funny enough, this works for me:
if($this->Session->read('Config.language') != DEFAULT_LANGUAGE){
$this->Paginator->options(array(
    'url' => array(
        'controller' => $this->Session->read('Config.language'),
        'action' => $this->params['catname'],
    )
));
}


text:
Q: How do I wait for a value in a text box with Selenium in C# I have a text input that is changed by Javascript based on values of other inputs.
How do I get Selenium to wait for it to change?
I currently have tried both
var wait3 = new WebDriverWait(_driver, TimeSpan.FromSeconds(5)).Until(driver => !driver.FindElement(By.Id("gbpAmount")).Equals(""));

and
bool pop= wait.Until<bool>((d) =>
            {
                var populated1 = d.FindElement(By.Id("gbpAmount")).Text != "";
                var populated2 = d.FindElement(By.Id("gbpAmount")).Text != "0";
                if (populated1 && populated2)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            });

However neither of these methods work. Either they just pass through and when I fetch and check the element afterwards it is "" or they just exceed the wait time.
Yet clearly on the screen the value is changed...

A: In Java the approach would be:
(new WebDriverWait(driver, Duration.ofSeconds(5))).until( ExpectedConditions.not(ExpectedConditions.attributeToBe(By.id("gbpAmount"), "value", "")));
String strAmount = driver.findElement(By.id("gbpAmount")).getAttribute("value");

So the equivalent in C# should work.

A: You need to check the value DOM property of text inputs, not the Value property of IWebElement.
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));

wait.Until(d => d.FindElement(By.Id("gbpAmount")).GetProperty("value") != ""
             && d.FindElement(By.Id("gbpAmount")).GetProperty("value") != "0");

This should work for both <input type="X"> and <textarea>.
If the values are numeric in nature, this should wait until there is a non-zero result:
wait.Until(d => decimal.TryParse(d.FindElement(By.Id("gbpAmount")).GetProperty("value"), out decimal result) ? result != 0 : false);

Note that negative numbers will cause this to return true. If you want a positive number, change result != 0 to result > 0.


text:
Q: Rails - user signin to application render a different layout but when signout rails show an error When a user signs in to my application, I render a different layout, for example before sign in i use application.html.erb and when the user logs in, I change the layout to layout2.html.erb in the UsersController I call layout 'layout2', this layout has many other scripts and
stylesheets, but when the user logs out, the application shows an error saying :
Routing Error

No route matches [GET] "/signout"

But... I checked and a /signout route exist, and when I do not change the layout,
this behaves normally, the user signs in and signs out normally.

A: The problem could be with rendering link to your sign_out path, it seems that this link is correct in your layout application.html.erb but in layout2.html.erb you are rendering the link wrongly.
My guess is that your sign_out action uses a destroy or post method while you are rendering it with a get method, so it gives you the error.


text:
Q: When trying to nfs4 mount a share with sec=krb5 I get "not exported" error message on nfs server I run two nfs servers with user home directories and other shares on them. The servers offer kerberized nfsv4 mounts as well as old v3 ones.
Until recently I was able to nfs4-mount a krb5-exported share
from one server on the second without any problems. If I try now
I get an permission denied and in the nfs server log I always see this error shown below. The filesystems with userdata on the nfs servers are located in /export/user1 on host server1.uni-ko.de and /export/user2 on host server2.uni-ko.de (hostnames changed).
The path /export/ is used as common nfs4 export root marked by fsid=0.
## run on host server1.uni-ko.de
# mount -t nfs4 -o sec=krb5 server2.uni-ko.de:/user2 /mnt
mount.nfs4: access denied by server while mounting server2.uni-ko.de:/user2

and in the nfs servers log I see this error:
refused mount request from server1.uni-ko.de for /user2 (/): not exported

The same happens if I try to locally mount a share on the same host
via nfs4 like this:
## on host server1.uni-ko.de
# mount -t nfs4 -o sec=krb5 server1.uni-ko.de:/user1 /mnt
mount.nfs4: access denied by server while mounting server1.uni-ko.de:/user1

A nfs3 mount (mount server1.uni-ko.de:/export/user1 /mnt) is possible without any problems.
The /etc/exports file on host server2.uni-ko.de looks like this:
/export gss/krb5(rw,fsid=0,nohide,no_subtree_check,no_root_squash,async,crossmnt) \
       gss/krb5i(rw,fsid=0,nohide,no_subtree_check,no_root_squash,async,crossmnt) \
       gss/krb5p(rw,fsid=0,nohide,no_subtree_check,no_root_squash,async,crossmnt)
# NFS V3 exports via NIS netgroups
/export/user2   @nfsv3client(rw,async,no_subtree_check,no_subtree_check,fsid=2000)

exportfs -v shows the shares are (krb5-nfs4) exported:
# exportfs -v
....
/export         gss/krb5(rw,async,wdelay,nohide,crossmnt,no_subtree_check,fsid=0,sec=sys,secure,no_root_squash,no_all_squash)
/export         gss/krb5i(rw,async,wdelay,nohide,crossmnt,no_subtree_check,fsid=0,sec=sys,secure,no_root_squash,no_all_squash)
/export         gss/krb5p(rw,async,wdelay,nohide,crossmnt,no_subtree_check,fsid=0,sec=sys,secure,no_root_squash,no_all_squash)
/export/user2   @nfsv3client(rw,async,wdelay,hide,no_subtree_check,fsid=2000,sec=sys,secure,root_squash,no_all_squash)

Things get even more strange since from a default nfs4 client I am still able to nfs4 mount the given directory without any problems exactly as described above and both systems share the same OS in der very same version and patch level which is SuSE SLES15SP3 with the latest patches installed.
On the nfs servers there is a firewall running opening the statically assigned ports needed for NFS like mountd,statd,lockd as well as ports 111 and 2049 (all opened for tcp and udp). This is what I changed recently. Before this change nfs server ports were not static but set by defaults, but I cannot see how this could lead to the strange mount behavior described. I also disabled the firewall completely and tested again with the same result.
Behind the scenes there is a kerberos server running keeping all the principals needed. For the nfs servers and all nfs4 clients there are "nfs" and "host" principals available and each server and client has a /etc/krb5.keytab containing the exported "nfs" and "host" principal for this host. Of course user principals are also stored in the kerberos server. This all worked flawlessly for years and still does, except for the described problem which is new.

A: The problem seems to be solved. My way to the solution that I initially had not expected to be one was in two steps:

*

*I used the rpcdebug-command to debug nfs rpc calls and found that the error "(/): not exported" was the result of the host trying to NFS4 mount the share which failed (for an unknown reason) and then dropped to a NFS3 mount, which also failed because the mount path given for NFS4 did not contain the path  for the NFS4 common root fsid=0 filesystem (/export in my case). So actually nfs4 failed without any visible error and the nfs3 mount failed with a correct error message. So it was clear NFS4 is the culprit and I could forget about the "not exported" error message.

*After digging around I took a closer look at our kerberos server and noticed it got a security update recently which also resulted in a newer version (1.19.2). I read the MIT docs (https://web.mit.edu/kerberos/krb5-latest/doc/admin/enctypes.html) about steps that should be taken after an version upgrade. One part was the update of several possibly  old internal DES- based keys (DES is deprecated and will very soon be dropped). I had one such key on our kerberos server named: kadmin/history . I updated this key as documented  using kadmin and after a while I discovered that the NFS4 mount-problem had gone away. However I never saw any error/warning messages on the kerberos server or on the NFS server or client about any kerberos key problem. So I see that nfs4-mounting is working again, but I still doubt a little if it really was only the kerberos des-key that caused this problem ...


text:
Q: Proof of exponential theorem I am currently reading Joseph Edwards' differential calculus for beginners. I am a beginner, in am in 10th.
$$a^x = 1 + x\ln a + \frac{x^2}{2!} (\ln a)^2 + \frac{x^3}{3!} (\ln a)^3...$$ I know it makes sense because if you plug in $e=a$ you get the maclaurin expansion for $e^x$. But what about a rigorous proof. I have tried messing around with it. I can't see a connection for natural logs be appearing in an exponent like $a^x$ without $e$ being in it? Please help. Thanks in advance.

A: Note that
$$
a^x=e^{x\ln a}=\sum_{k=0}^\infty\frac{x^k(\ln a)^k}{k!}
$$
where the second equality comes from knowledge of the Maclaurin series for $e^x$

A: It comes from the Taylor's expansion for $a^x$ since $(a^x)'=a^x\log a$, $(a^x)''=a^x\log^2 a$ and so on.
Note
$$a^x = e^{x\ln{a}}\implies (a^x)'=(e^{x\ln{a}})'=e^{x\ln{a}}\ln a=a^x \ln a$$

A: Let $a^x = y$.
$x \ln a = \ln y$
$e^{x\ln a}= y$
$\therefore a^x = e^{x\ln a}$
$a^x = {(e^x) }^{\ln a}$
$a^{\frac {x}{\ln a}} = e^x $
Substituting $a^{\frac {x}{\ln a}} = e^x$ into the Maclaurin expansion for $e^x$ should give you the same expansion as your original one.
(Note: this may be wrong so please pardon me. I am also in the $10^{th}$ grade and I am supposed to learn this after $2$ years).

A: By Taylor series we have:
$$f(x)=\sum_{n=0}^{\infty}\frac{f^{(n)}(0)}{n!}x^n$$
with $f(x)= a^x =e^{x\ln a}$ see that
$$f'(x) =\ln a ~e^{x\ln a}= \ln a\cdot f(x),~~f^{(2)}(x)= (\ln a)^{2} f(x)\cdots\cdots , f^{(n)}(x)= (\ln a)^{n} f(x)$$
that is $$f(0) =1,~~f'(0) =\ln a ,~~f^{(2)}(0)= (\ln a)^{2} \cdots\cdots , f^{(n)}(0)= (\ln a)^{n} $$


text:
Q: Necesito convertir un campo de un bindinglist en combobox Este es el código que no está funcionando:
public class DetalleTurnoPersonal
    {
        public string Nombre  { get; set; }
        public DateTime Fecha_Entrada { get; set; }
        public TimeSpan Hora_Entrada { get; set; }
        public DateTime Fecha_Salida { get; set; }
        public TimeSpan Hora_Salida { get; set; }
        public string Sector { get; set; }
        public int IDSeccion { get; set; }
        public int IDEmpresa { get; set; }

    }

y por el otro lado la tomo con un bindinglist
private readonly BindingList<DetalleTurnoPersonal> misDetalles = new BindingList<DetalleTurnoPersonal>();
        public FrmTurnosTransferPersonal()
        {
            InitializeComponent();

        }

DetalleTurnoPersonal miDetalle = new DetalleTurnoPersonal();

 miDetalle.Nombre = NombrePersona;
                miDetalle.Hora_Entrada = TimeSpan.Parse(horaEntradaComboBox.Text);
                miDetalle.Fecha_Entrada = Convert.ToDateTime(FechadateTimePicker.Value.ToShortDateString());
                miDetalle.Hora_Salida = TimeSpan.Parse(HoraSalidacomboBox.Text);
                miDetalle.Fecha_Salida = Convert.ToDateTime(DateTime.Now.AddDays(1).ToShortDateString());
                miDetalle.Sector = Personalxnombre.Sector;
                miDetalle.IDSeccion = personalxnombre.IDSeccion;
                miDetalle.IDEmpresa = UsuarioLogueado.IDEmpresa;
                misDetalles.Add(miDetalle);

el campo que deseo que se visualice en la grilla como combobox es midetalle.sector

A: intenta poniendo algo asi:
combobox1.DataSource=misDetalles;
combobox1.DisplayMember="Sector";

Espero esto pueda ayudarte


text:
Q: Wrapping WriteToText Within DoFn I'm trying to wrap WriteToText within a DoFn to allow for some customization/flexibility in how I write files. Specifically, I want to write different files based on the on an argument/input (based on value provider argument). This is the code I have so far:
class WriteCustomFile(beam.DoFn):
    def __init__(self,input,output):
        self.input = input
        self.output = output

    def process(self, element):

        import re

        def FileVal(path):
            File1Regex = re.compile(r"[^\w](testfile)[\w]+(\.csv|\.txt)$")
            File2Regex = re.compile(r"[^\w](tester)[\w-]+(\.csv|\.txt)$")
            PathStr = str(path)

            if File1Regex.search(PathStr) != None:
                return "file1"
            elif File2Regex.search(PathStr) != None:
                return "file2"

        File1Header = "Header1,Header2,Header3,Header4,Header5"
        File2Header = "Header1,Header2,Header3,Header4,Header5,Header6,Header7,Header8"

        if FileVal(self.input.get()) == "file1":
            yield WriteToText(self.output.get(),shard_name_template='',header=File1Header)
        elif FileVal(self.input.get()) == "file2":
            yield WriteToText(self.output.get(),shard_name_template='',header=File2Header)

When I call this DoFn from within the pipeline, it does not write a file. What can I do to get this DoFn to work or is there a better way to handle this?
Thank you!

A: Here the best thing to do is probably partition your input into multiple PCollections (either using Partition or a DoFn with multiple outputs), and write each one out separate.
More generally one can use Dynamic Destinations, but this is not yet supported for Python.


text:
Q: How can I create a temporary Redirect in .htaccess that all browsers adhere to? Multiple variations of this question have been asked, but I can't seem to find a satisfying answer.
I add the following to my .htaccess file
Redirect 302 /test1 /test

Then browse to the website. I get redirected to /test.
I then remove the redirect, and browse to the website again. In Chrome, Firefox and Internet Explorer (Latest versions on 2017-04-14) the browsers use the cached redirect, and send me to /test. On Edge, I get /test1.
As mentioned in other questions, this is kindof ok, per the RFC:
Since the redirection might be altered on occasion, the client SHOULD continue to use the Request-URI for future requests.

Note that "SHOULD" in RFC lingo means that it is advised, but not obligatory. So it is advised not to cache the redirect (and hence, go to /test1), but it is ok to cache it anyway. I don't understand why browsers would not follow the RFC suggestion here, ...but there's that.
Then there is the 303 Redirect:
The 303 response MUST NOT be cached, but the response to the second (redirected) request might be cacheable.

I have tested this. given the RFC, this redirect MUST NOT (as in ever) be cached. Edge and Firefox play nice here, and don't cache it. Internet Explorer and Chrome seem to decide to bluntly ignore the RFC here, and keep on sending me to /test.
Are these known bugs?
Am I misunderstanding the RFC?
Is there any way, to make sure my Redirects don't get cached?
Is the only solution using a RewriteRule? Browsers can't cache the target URL's there, because they never see them, and tend to not cache the target location, so this works for me. (Thanks to @Olaf Dietsche)
RewriteRule ^test1 /test

(In my use-case, I want to redirect something like website.com/file.pdf to another file. There is no HTML page I can add a no-cache parameter to. Users type this URL into their browsers manually)

A: the RFC (2616) states

This document has been superseded.

Precisely, it is RFC 7231, which explicitly states "Obsoletes: 2616". And in this case the relevant sections are 303 See Other and especially Appendix B. Changes from RFC 2616

The description of the 303 (See Other) status code has been changed
to allow it to be cached if explicit freshness information is given,
and a specific definition has been added for a 303 response to GET.
(Section 6.4.4)

So in some cases, caching a 303 response is allowed.


text:
Q: convert JavaScript multidimensional object into flat array I have this javascript object format
{
  "draw": "",
  "columns": [
    {
      "data": "userid",
      "name": "",
      "searchable": true,
      "search": {
        "value": "",
        "regex": false
      }
    }
  ]
}

and what I need to do is convert it into single dimension object like
{
 "draw" : "",
 "columns[data]": "userid",
 "columns[name]": "",
 "columns[searchable]": "true",
 "columns[searchable][value]": "",
 "columns[searchable][regex]":"true"
}

the primary object can be multiple layers deep and contains objects as well as arrays.
any ideas suggestions much appreciated as JS is not my forte.

A: I would use a recursive function that accepts a property of the original and the path to that object. If the property is not an object, then add the value to the path, if it is, then iterate through its properties and call the recursive function.

var object = {
  "draw": "",
  "columns": [{
    "data": "userid",
    "name": "",
    "searchable": true,
    "search": {
      "value": "",
      "regex": false
    }
  }]
};

console.log(flatten(object));

function flatten(object) {
  var result = {};
  innerFlatten(object, "");
  return result;

  function innerFlatten(object, path) {
    if (typeof object !== "object" || object === null || object instanceof Date) return result[path] = object;
    if (!Object.keys(object).length) return result[path] = object;
    for (var key in object) {
      innerFlatten(object[key], path ? (path + "[" + key + "]") : key);
    }
  }
}

A: I think you want to remove array from columns and set to 0 index value

let test = {
  "draw": "",
  "columns": [
    {
      "data": "userid",
      "name": "",
      "searchable": true,
      "search": {
        "value": "",
        "regex": false
      }
    }
   ]
}

test.columns = test.columns[0]

console.log(test)


text:
Q: Create an angular component without wrapper tag I want to generate a component without its wrapper tag. I read all similar SO questions (e.g. SO1, SO2, SO3), without finding a proper solution.
My existing, simplified component (toggle-button.component.ts):
import {Component} from "@angular/core";

@Component({
    selector: "toggle-button, [toggleButton]",
    template: `<button type="button" class="btn btn-primary">{{ label }}</button>`
})

export class ToggleButtonComponent {

    @Input()
    public label: string;
}

Second component, which I want to create (select-button.component.ts):
import {Component} from "@angular/core";

@Component({
    selector: "select-button",
    template: `

        <ng-container *ngFor="let item of items">
             <ng-container toggleButton [label]="item.label"></ng-container>
        </ng-container>

    `
})

export class SelectButtonComponent {

    @Input()
    public items: {label: string; value: any;};
}

My app.component.html
<select-button [items]="items"></select-button>

The result is an error:

Failed to execute 'appendChild' on 'Node': This node type does not support this method.

What I want to achieve is a HTML structure like this:

    <button type="button" class="btn btn-primary">12 H</button>
    <button type="button" class="btn btn-primary">24 H</button>

Instead of:

    <toggle-button>
        <button type="button" class="btn btn-primary">12 H</button>
    </toggle-button>
    <toggle-button>
        <button type="button" class="btn btn-primary">24 H</button>
    </toggle-button>

Stackblitz link

A: The simpliest way is to avoid toggle-button.component.ts and insert  tag directly in the select-button.component html for example:
 <ng-container *ngFor="let item of items">
         <button type="button" class="btn btn-primary">{{item.label}}</button>
    </ng-container>


text:
Q: Windows Firewall C++ API - How to correctly clean up the COM resources? I am trying to use the COM-based Windows Firewall API for traversing the existing Firewall rules and find out if one specific rule exists among them.
Currently I have difficulties with understanding what is going on in the Cleanup part of this example (https://learn.microsoft.com/en-us/previous-versions/windows/desktop/ics/c-enumerating-firewall-rules):
/********************************************************************++
Copyright (C) Microsoft. All Rights Reserved.

Abstract:
    This C++ file includes sample code for enumerating Windows Firewall
    rules using the Microsoft Windows Firewall APIs.

********************************************************************/

#include <windows.h>
#include <stdio.h>
#include <comutil.h>
#include <atlcomcli.h>
#include <netfw.h>

#pragma comment( lib, "ole32.lib" )
#pragma comment( lib, "oleaut32.lib" )

#define NET_FW_IP_PROTOCOL_TCP_NAME L"TCP"
#define NET_FW_IP_PROTOCOL_UDP_NAME L"UDP"

#define NET_FW_RULE_DIR_IN_NAME L"In"
#define NET_FW_RULE_DIR_OUT_NAME L"Out"

#define NET_FW_RULE_ACTION_BLOCK_NAME L"Block"
#define NET_FW_RULE_ACTION_ALLOW_NAME L"Allow"

#define NET_FW_RULE_ENABLE_IN_NAME L"TRUE"
#define NET_FW_RULE_DISABLE_IN_NAME L"FALSE"

// Forward declarations
void        DumpFWRulesInCollection(INetFwRule* FwRule);
HRESULT     WFCOMInitialize(INetFwPolicy2** ppNetFwPolicy2);

int __cdecl main()
{
    HRESULT hrComInit = S_OK;
    HRESULT hr = S_OK;

    ULONG cFetched = 0;
    CComVariant var;

    IUnknown *pEnumerator;
    IEnumVARIANT* pVariant = NULL;

    INetFwPolicy2 *pNetFwPolicy2 = NULL;
    INetFwRules *pFwRules = NULL;
    INetFwRule *pFwRule = NULL;

    long fwRuleCount;

    // Initialize COM.
    hrComInit = CoInitializeEx(
                    0,
                    COINIT_APARTMENTTHREADED
                    );

    // Ignore RPC_E_CHANGED_MODE; this just means that COM has already been
    // initialized with a different mode. Since we don't care what the mode is,
    // we'll just use the existing mode.
    if (hrComInit != RPC_E_CHANGED_MODE)
    {
        if (FAILED(hrComInit))
        {
            wprintf(L"CoInitializeEx failed: 0x%08lx\n", hrComInit);
            goto Cleanup;
        }
    }

    // Retrieve INetFwPolicy2
    hr = WFCOMInitialize(&pNetFwPolicy2);
    if (FAILED(hr))
    {
        goto Cleanup;
    }

    // Retrieve INetFwRules
    hr = pNetFwPolicy2->get_Rules(&pFwRules);
    if (FAILED(hr))
    {
        wprintf(L"get_Rules failed: 0x%08lx\n", hr);
        goto Cleanup;
    }

    // Obtain the number of Firewall rules
    hr = pFwRules->get_Count(&fwRuleCount);
    if (FAILED(hr))
    {
        wprintf(L"get_Count failed: 0x%08lx\n", hr);
        goto Cleanup;
    }

    wprintf(L"The number of rules in the Windows Firewall are %d\n", fwRuleCount);

    // Iterate through all of the rules in pFwRules
    pFwRules->get__NewEnum(&pEnumerator);

    if(pEnumerator)
    {
        hr = pEnumerator->QueryInterface(__uuidof(IEnumVARIANT), (void **) &pVariant);
    }

    while(SUCCEEDED(hr) && hr != S_FALSE)
    {
        var.Clear();
        hr = pVariant->Next(1, &var, &cFetched);

        if (S_FALSE != hr)
        {
            if (SUCCEEDED(hr))
            {
                hr = var.ChangeType(VT_DISPATCH);
            }
            if (SUCCEEDED(hr))
            {
                hr = (V_DISPATCH(&var))->QueryInterface(__uuidof(INetFwRule), reinterpret_cast<void**>(&pFwRule));
            }

            if (SUCCEEDED(hr))
            {
                // Output the properties of this rule
                DumpFWRulesInCollection(pFwRule);
            }
        }
    }

Cleanup:

    // Release pFwRule
    if (pFwRule != NULL)
    {
        pFwRule->Release();
    }

    // Release INetFwPolicy2
    if (pNetFwPolicy2 != NULL)
    {
        pNetFwPolicy2->Release();
    }

    // Uninitialize COM.
    if (SUCCEEDED(hrComInit))
    {
        CoUninitialize();
    }

    return 0;
}

// Output properties of a Firewall rule
void DumpFWRulesInCollection(INetFwRule* FwRule)
{
    variant_t InterfaceArray;
    variant_t InterfaceString;

    VARIANT_BOOL bEnabled;
    BSTR bstrVal;

    long lVal = 0;
    long lProfileBitmask = 0;

    NET_FW_RULE_DIRECTION fwDirection;
    NET_FW_ACTION fwAction;

    struct ProfileMapElement
    {
        NET_FW_PROFILE_TYPE2 Id;
        LPCWSTR Name;
    };

    ProfileMapElement ProfileMap[3];
    ProfileMap[0].Id = NET_FW_PROFILE2_DOMAIN;
    ProfileMap[0].Name = L"Domain";
    ProfileMap[1].Id = NET_FW_PROFILE2_PRIVATE;
    ProfileMap[1].Name = L"Private";
    ProfileMap[2].Id = NET_FW_PROFILE2_PUBLIC;
    ProfileMap[2].Name = L"Public";

    wprintf(L"---------------------------------------------\n");

    if (SUCCEEDED(FwRule->get_Name(&bstrVal)))
    {
        wprintf(L"Name:             %s\n", bstrVal);
    }

    if (SUCCEEDED(FwRule->get_Description(&bstrVal)))
    {
        wprintf(L"Description:      %s\n", bstrVal);
    }

    if (SUCCEEDED(FwRule->get_ApplicationName(&bstrVal)))
    {
        wprintf(L"Application Name: %s\n", bstrVal);
    }

    if (SUCCEEDED(FwRule->get_ServiceName(&bstrVal)))
    {
        wprintf(L"Service Name:     %s\n", bstrVal);
    }

    if (SUCCEEDED(FwRule->get_Protocol(&lVal)))
    {
        switch(lVal)
        {
            case NET_FW_IP_PROTOCOL_TCP:

                wprintf(L"IP Protocol:      %s\n", NET_FW_IP_PROTOCOL_TCP_NAME);
                break;

            case NET_FW_IP_PROTOCOL_UDP:

                wprintf(L"IP Protocol:      %s\n", NET_FW_IP_PROTOCOL_UDP_NAME);
                break;

            default:

                break;
        }

        if(lVal != NET_FW_IP_VERSION_V4 && lVal != NET_FW_IP_VERSION_V6)
        {
            if (SUCCEEDED(FwRule->get_LocalPorts(&bstrVal)))
            {
                wprintf(L"Local Ports:      %s\n", bstrVal);
            }

            if (SUCCEEDED(FwRule->get_RemotePorts(&bstrVal)))
            {
                wprintf(L"Remote Ports:      %s\n", bstrVal);
            }
        }
        else
        {
            if (SUCCEEDED(FwRule->get_IcmpTypesAndCodes(&bstrVal)))
            {
                wprintf(L"ICMP TypeCode:      %s\n", bstrVal);
            }
        }
    }

    if (SUCCEEDED(FwRule->get_LocalAddresses(&bstrVal)))
    {
        wprintf(L"LocalAddresses:   %s\n", bstrVal);
    }

    if (SUCCEEDED(FwRule->get_RemoteAddresses(&bstrVal)))
    {
        wprintf(L"RemoteAddresses:  %s\n", bstrVal);
    }

    if (SUCCEEDED(FwRule->get_Profiles(&lProfileBitmask)))
    {
        // The returned bitmask can have more than 1 bit set if multiple profiles
        //   are active or current at the same time

        for (int i=0; i<3; i++)
        {
            if ( lProfileBitmask & ProfileMap[i].Id  )
            {
                wprintf(L"Profile:  %s\n", ProfileMap[i].Name);
            }
        }
    }

    if (SUCCEEDED(FwRule->get_Direction(&fwDirection)))
    {
        switch(fwDirection)
        {
            case NET_FW_RULE_DIR_IN:

                wprintf(L"Direction:        %s\n", NET_FW_RULE_DIR_IN_NAME);
                break;

            case NET_FW_RULE_DIR_OUT:

                wprintf(L"Direction:        %s\n", NET_FW_RULE_DIR_OUT_NAME);
                break;

            default:

                break;
        }
    }

    if (SUCCEEDED(FwRule->get_Action(&fwAction)))
    {
        switch(fwAction)
        {
            case NET_FW_ACTION_BLOCK:

                wprintf(L"Action:           %s\n", NET_FW_RULE_ACTION_BLOCK_NAME);
                break;

            case NET_FW_ACTION_ALLOW:

                wprintf(L"Action:           %s\n", NET_FW_RULE_ACTION_ALLOW_NAME);
                break;

            default:

                break;
        }
    }

    if (SUCCEEDED(FwRule->get_Interfaces(&InterfaceArray)))
    {
        if(InterfaceArray.vt != VT_EMPTY)
        {
            SAFEARRAY    *pSa = NULL;

            pSa = InterfaceArray.parray;

            for(long index= pSa->rgsabound->lLbound; index < (long)pSa->rgsabound->cElements; index++)
            {
                SafeArrayGetElement(pSa, &index, &InterfaceString);
                wprintf(L"Interfaces:       %s\n", (BSTR)InterfaceString.bstrVal);
            }
        }
    }

    if (SUCCEEDED(FwRule->get_InterfaceTypes(&bstrVal)))
    {
        wprintf(L"Interface Types:  %s\n", bstrVal);
    }

    if (SUCCEEDED(FwRule->get_Enabled(&bEnabled)))
    {
        if (bEnabled)
        {
            wprintf(L"Enabled:          %s\n", NET_FW_RULE_ENABLE_IN_NAME);
        }
        else
        {
            wprintf(L"Enabled:          %s\n", NET_FW_RULE_DISABLE_IN_NAME);
        }
    }

    if (SUCCEEDED(FwRule->get_Grouping(&bstrVal)))
    {
        wprintf(L"Grouping:         %s\n", bstrVal);
    }

    if (SUCCEEDED(FwRule->get_EdgeTraversal(&bEnabled)))
    {
        if (bEnabled)
        {
            wprintf(L"Edge Traversal:   %s\n", NET_FW_RULE_ENABLE_IN_NAME);
        }
        else
        {
            wprintf(L"Edge Traversal:   %s\n", NET_FW_RULE_DISABLE_IN_NAME);
        }
    }
}

// Instantiate INetFwPolicy2
HRESULT WFCOMInitialize(INetFwPolicy2** ppNetFwPolicy2)
{
    HRESULT hr = S_OK;

    hr = CoCreateInstance(
        __uuidof(NetFwPolicy2),
        NULL,
        CLSCTX_INPROC_SERVER,
        __uuidof(INetFwPolicy2),
        (void**)ppNetFwPolicy2);

    if (FAILED(hr))
    {
        wprintf(L"CoCreateInstance for INetFwPolicy2 failed: 0x%08lx\n", hr);
        goto Cleanup;
    }

Cleanup:
    return hr;
}

In particular, these lines confuse me:
    // Release pFwRule
    if (pFwRule != NULL)
    {
        pFwRule->Release();
    }

The pFwRule pointer gets overwritten on each iteration, so here we are explicitly Releaseing only the last Rule that was obtained via QueryInterface in the while loop above.
Releaseing a pointer obtained from a successfull call to QueryInterface is logical, because QueryInterface calls AddRef before returning (which is explicitly stated in the documentation).
But what I cannot understand, is:

*

*Why don't we Release all the previously traversed Rules before querying a next one in the loop? Have they been released implicitly somewhere? Does QueryInterface call Release undercover in case a non-null pointer is passed to it?

*Why don't we call Release on pFwRules? Doesn't the INetFwPolicy2::get_Rules function give us a new pointer to a COM object, which is AddRef'ed before being returned to us (and thus must be Released by the caller in the end)?

*The same question about the pEnumerator pointer obtained from get__NewEnum: why don't we Release this one as well?

A: The code is indeed leaking COM memory.
Every call to an interface's AddRef() method must have a matching call to its Release() method. ANY function call that outputs an interface pointer must call AddRef() on it before exit, and the caller must then call Release() on it afterwards.
The general rule is, for any function that allocates and returns memory to the caller, the caller must free it when done using it.
So, to answer your questions:

*

*Yes, there are missing calls to Release() in this code, so there are COM interfaces being leaked - specifically: pFwRules, pEnumerator, and pFwRule are not being Release()'d properly.

*DumpFWRulesInCollection() is also leaking COM memory as well. It is not freeing any of the BSTR strings that are output by FwRule's methods.
And also, when it calls SafeArrayGetElement() in a loop, it is not clearing the InterfaceString on each iteration.

*No, QueryInterface() does not implicitly Release() a non-null pointer. Just as SafeArrayGetElement() does not clear the element being written to.

A: It's a reasonable reaction to be confused when studying the sample code. It does indeed leak resources.

Why don't we Release all the previously traversed Rules before querying a next one in the loop? Have they been released implicitly somewhere? Does QueryInterface call Release undercover in case a non-null pointer is passed to it?

No. QueryInterface unconditionally overwrites the value pointed to by its ppvObject argument, either with a NULL pointer, if the COM object does not implement the requested interface, or with a pointer to the requested interface. Not calling Release is a resource leak.

Why don't we call Release on pFwRules? Doesn't the INetFwPolicy2::get_Rules function give us a new pointer to a COM object, which is AddRef'ed before being returned to us (and thus must be Released by the caller in the end)?

Correct again. get_Rules returns a resource the caller is responsible for. Not calling Release on the returned interface is a resource leak.

The same question about the pEnumerator pointer obtained from get__NewEnum: why don't we Release this one as well?

The same rules apply here as well: The caller is responsible for cleaning up the iterator it received. This, too, is a resource leak.

Special note on MSDN samples: Although they are tagged "C++", the majority of code samples for COM are actually written in C. Unlike C++, C doesn't have much to offer with respect to automatic resource management.
If you are using C++, you can take advantage of automatic resource management, and employ one of the provided smart pointer types (e.g. ATL's CComPtr, or Visual C++' _com_ptr_t).


text:
Q: Saving Form Data Based On A Field From Another Model I am building a form that utilizes dynamic question/answers with Question and Answer models so that new questions can be created by non-devs.
Here are my current models (missing some unnecessary information for this question)
models.py
class Question(models.Model):
    question = TextField()
    is_active = BooleanField(default=False)

    def __str__(self):
        return self.question

class Answer(models.Model):
    answer = TextField()
    question = ForeignKey(Question, on_delete=CASCADE, default=None)

In the view I create the form like this.
views.py
def survey(request):
    custom_questions = Question.objects.filter(is_active=True)
    if request.method == "POST":
        formset = []
        for q in custom_questions:
            formset.append(AnswerForm(request.POST))
        ### Here is where I would like to process this data

    else:
      formset = []
      for q in custom_questions:
        answer_form = AnswerForm()
        answer_form.fields['answer'].label = q.question
        formset.append(answer_form)
    return render(request, 'template.html', {'formset': formset})

How would I process this data based on the question that was asked?
Here is what I tried just to see what information was being processed in the form:
for q in custom_questions:
    answer_form = AnswerForm(request.POST)
    if answer_form.is_valid():
        print(answer_form.cleaned_data['answer']

However, when it printed the data it only printed the same answer multiple times.
I would like to:

*

*Use the label that was defined in the GET request to Question.objects.get(question=) in order to set the foreignkey field to the Answer model.

*Get the correct data based on the question that it is answering.

*Create a new Answer model with this information.

Here is my form for reference:
class AnswerForm(ModelForm):
  def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.fields['answer'].required = True

  class Meta:
      model = Answer
      fields = ['answer']


text:
Q: Compare date fields into two datatables I have two DataTables and I need to compare three columns of them.
The first DataTable is created in vb.net with this code:
Using DT1 As DataTable = New DataTable
    With DT1
        .Columns.Add("Type", GetType(String))
        .Columns.Add("In_Date", GetType(Date))
        .Columns.Add("Out_Date", GetType(Date))
        .Columns.Add("RowNum", GetType(Byte))
        .PrimaryKey = {.Columns("RowNum")}
    End With
'...

The other DataTable is created by querying a MySql Database and so all fields are strings.
The query returns an empty string ('') when a date field is NULL:
SELECT IdEv, Type,
       IF(In_Date='0000-00-00'
          OR In_Date IS NULL,'',DATE_FORMAT(In_Date, '%d/%m/%Y')
          ) AS In_Date,
       IF(Out_Date='0000-00-00'
          OR Out_Date IS NULL,'',DATE_FORMAT(Out_Date, '%d/%m/%Y')
          ) AS Out_Date,
       IdLi
FROM MyTable
WHERE IdLi = 1

After many failed attempts, now I'm doing this way:
To make fields comparable I run a loop to change all empty strings into date fields to DBNull.Value :
For x As Short = 0 To DT2.Rows.Count - 1
    If DT2.Rows(x)("In_Date") = "" Then DT2.Rows(x)("In_Date") = DBNull.Value
    If DT2.Rows(x)("Out_Date") = "" Then DT2.Rows(x)("Out_Date") = DBNull.Value
Next

then I compare with this code:
If Not DT1.Rows(x)("Type").Equals(DT2.Rows(x)("Type")) OrElse Not _
   If(IsDBNull(DT1.Rows(x)("In_Date")), 0, CDate(DT1.Rows(x)("In_Date"))).Equals(If(IsDBNull(DT2.Rows(x)("In_Date")), 0, CDate(DT2.Rows(x)("In_Date")))) OrElse _
   If(IsDBNull(DT1.Rows(x)("Out_Date")), 0, CDate(DT1.Rows(x)("Out_Date"))).Equals(If(IsDBNull(DT2.Rows(x)("Out_Date")), 0, CDate(DT2.Rows(x)("Out_Date")))) Then

I made some test and it seems to work but I'm afraid of wrong results.
Can you say me if my code does its work and gives me right answers?

A: If You Have Two Tables , You Can Compare Like Below
For x As Short = 0 To DT2.Rows.Count - 1
    If DT1.Select("In_Date='" & DT2.Rows(x)("In_Date") & "'").Length >=1 Then
    '' Existing
     Else
     '' Not Existing
   End If
Next


text:
Q: Keeping wrapped elements together I have several elements in HTML that I want to keep grouped when they wrap. I think the answer lies with some CSS (or maybe even JavaScript), but I'm not sure. For example, I have several elements laid out like this:
<input A><input B><input C>

What happens is the users sometimes resize the browser window, and we end up with this:
<input A>
<input B><input C>

In the example above, the input B isn't next to its input element. Is there a way to group the label and the input so they wrap together? I've tried divs and putting the elements together in a table with "nowrap", with mixed results. I don't mind the lines wrapping, I just need to keep the label and input element together.

A: The simple answer is to wrap elements into another element that has a display: inline-block as a style. So...

And
.wrapper {
  display: inline-block;
}

A: Put all of those elements in a div like this:

  ...

A: It may also be worth looking at setting parent divs around each pair you wish to keep together - I know you said you tried this but also give them a fixed width and display:inline; and it should work
ALSOO include float:left/right;(choose only one) This way, if the browser window is too small to show them all side by side, it will instead take the end pair and drop it onto the next line but should keep all elements within together and side by side.

A: Try something like this:
First Name:
    <input type="text">

Last Name:
    <input type="text">

and set
label {
    display: inline-block;
}

Demo http://dabblet.com/gist/3145028
Alternative: wrap both  and <input> in a
 with display: inline-block

A: You could put each label/input group in a  and then set the css to display:inline. I am pretty sure this will keep it grouped. Depending on your site layout and previous CSS, you may  have to tweak the span css.

A: Since you said this was in a table, here is probably what you were looking for: http://jsfiddle.net/DX9G7/
HTML:

    <colgroup>
        <col width="30%" />
        <col width="30%" />
        <col width="40%" />
    </colgroup>

                A
                <input type="text" />

                B
                <input type="text" />

                C
                <input type="text" />

You can now modify your css the way you want.


text:
Q: unable to deploy local container image to k8s cluster I have tried to deploy one of the local container images I created but keeps always getting the below error

Failed to pull image "webrole1:dev": rpc error: code = Unknown desc =
  Error response from daemon: pull access denied for webrole1,
  repository does not exist or may require 'docker login': denied:
  requested access to

I have followed the below article to containerize my application and I was able to successfully complete this but when I try to deploy it to k8s pod I don't succeed
My pod.yaml looks like below
apiVersion: v1
kind: Pod
metadata:
  name: learnk8s
spec:
  containers:
  - name: webrole1dev
    image: 'webrole1:dev'
    ports:
      - containerPort: 8080

and below are some images from my PowerShell

I am new to dockers and k8s so thanks for the help in advance and would appreciate if I get some detailed response.

A: When you're working locally, you can use an image name like webrole, however that doesn't tell Docker where the image came from (because it didn't come from anywhere, you built it locally). When you start working with multiple hosts, you need to push things to a Docker registry. For local Kubernetes experiments you can also change your config so you build your image in the same Docker environment as Kubernetes is using, though the specifics of that depend on how you set up both Docker and Kubernetes.


text:
Q: Zend framework admin module and other modules I want to build a CMS based on Zend Framework for my needs which has admin module with authentication and other modules (pages, users, news) which can be used as plugin modules based on the appliaction needs.
I want every module to have specific frontend and backend code, so that it could be accessed like e.g. http://localhost/mycms/pages/view/5 to view a certain page from the pages module by calling Pages controller, view action. The backend for every plugin needs to be tied to the admin and require authentication, it could be accessed like http://localhost/mycms/admin/pages/add.
The problem is that the solution I found involves removing default routes and writing custom routing for every controller action inside the plugin modules like:
  $router->removeDefaultRoutes();

  $route = new Zend_Controller_Router_Route_Static(
      'admin/pages/add',
      array(
       'module' => 'pages',
       'controller' => 'Pages',
       'action' => 'add'
      )
  );

  $router->addRoute('pages_pages_add', $route);

  $route = new Zend_Controller_Router_Route_Regex(
      'pages/view/(\d+)',
      array(
       'module' => 'pages',
       'controller' => 'Pages',
       'action' => 'view'
      ),
      array(
       '1' => 'page_id'
      )
  );

  $router->addRoute('pages_pages_view', $route);

Do you have any ideas how I can avoid this custom routing?

A: Have a look at Front Controller Plugins, they may give you more flexibility...
http://framework.zend.com/manual/en/zend.controller.plugins.html
class Controller_Plugin_Foo extends Zend_Controller_Plugin_Abstract
{
    public function preDispatch( Zend_Controller_Request_Abstract $request )
    {
        $frontController = Zend_Controller_Front::getInstance();
        ...
    }
}


text:
Q: use of ':=' fails in select in stored procedure due to variable definition Why does the use of the assignment operator := fail to parse in this stored procedure (fragment)?    In the update statement, in the set median = [select expression], in the expression, the MySQL 5.6 parser reports the error, "[Check]...for the right syntax to use near ':= row + 1 as row, $vol as $vol from univ_members' ".
delimiter //
  CREATE PROCEDURE m()
BEGIN
  DECLARE row int;
  SELECT row := row + 1 AS row;
END //
delimiter ;

Running the select statement the mysql shell also fails, but says, 'row' is not a system variable or 'row' is not a column, depending on whether I try to define it with 'set'.
Do you know of a limitation in a stored procedure that prohibits this, or of such a bug in MySQL 5.6?  If so, is there a workaround?  Can you suggest an alternative approach?

A: So, after struggling like a man blinded by darkness, I defined the variable @row in the shell using 'set' (the shell's parser does not allow 'row') and it worked.  The parser however does not allow a variable defined in a stored procedure with 'declare' to begin with a '@', but, if defined with 'set', it works, it does allow it to be used as the left-hand value in the :=.
So, it's an issue with variable definition.  Evidently, only 'user variables', which must begin with a '@' and must be defined with 'set', can be assigned values with ':='.  (See User-Defined Variables)
I find such a nuance that all variables don't share a common behavior when it comes to assignment non-intuitive and incredibly irritating.  Am I still missing something?


text:
Q: PAM USB as two factor authenticator Can pamusb be used as two factor authentication? Meaning to require both a password and a token to login?

A: It looks like it can. "Additional mode" requires password and USB.


text:
Q: Count all rows and show a limited number of them in a single json object My query is
select array_to_json(array_agg(row_to_json(t))) from (
    select count(*) over() as total, id,title
    FROM notifications
    WHERE  title ilike '%a%'
LIMIT 5 OFFSET 1)t

and the output is
[
    {
        "title": "Sartaj                                                              ",
        "id": 3,
        "total":16
    }
]

The result includes the total in object, but I want to move it outside the object.
My expected answer is
[
    "total":16,
    "data":[
{
        "title": "Sartaj                                                       ",
        "id": 3
    }]
 ]

I also tried
with tmp_notifications as (
    SELECT id,title,description,img_url,link,created_on from notifications
    where title ilike '%universi%'
    )
    select row_to_json(t) from (
        select count(*) as data_count,
        (json_agg(json_build_object('description',description,'title',title,'created_on',created_on,
        'link',link,'img_url',img_url,'id',id))
         ) as data from tmp_notifications limit 1
        )t

but limit is not working here.

A: Use json_build_object() and json_agg():
select json_build_object('total', count(*), 'data', json_agg(to_json(t)))
from (
    select id, title
    from notifications
    where  title ilike '%a%'
    ) t

See the full example in DbFiddle.

You can use a WITH statement to count all filtered rows but show the limited number of them, e.g.:
with filtered as (
    select id, title
    from notifications
    where title ilike '%a%'
)

select json_build_object(
    'total', (select count(*) from filtered),
    'data', json_agg(to_json(t)))
from (
    select id, title
    from filtered
    order by id
    limit 2
    ) t

DbFiddle.


text:
Q: Execute other SQL query if first one was empty for set of elements to eliminate PHP foreach loop I get row data with query:
SELECT itemNAME FROM item_list WHERE itemID ='$itemID' AND itemSUB ='$itemSUB'

If result is empty I query again with:
SELECT itemNAME FROM item_list WHERE itemID ='$itemID'

Morover it's ran in a loop like:
foreach ($dataBuffor as $dataItem) {
    $query = mysql_query("SELECT itemNAME FROM item_list WHERE itemID ='$itemID' AND itemSUB ='$itemSUB'");
    $fetched_data = mysql_fetch_row($query);
    $itemNAME = $fetched_data[0];

    if ($itemNAME == "") {
        $query = mysql_query("SELECT itemNAME FROM item_list WHERE itemID ='$itemID'");
        $fetched_data = mysql_fetch_row($query);
        $itemNAME = $fetched_data[0];
    }
}

How to redo this query to ask once for a set of data (insead looping for it) and include empty result logic in query itself?
I expect to produce something like:
SELECT itemNAME FROM item_list WHERE itemID ='$itemID' AND itemSUB ='$itemSUB'
if itemNAME == '' (
    SELECT itemNAME FROM item_list WHERE itemID ='$itemID'
)

That will result with array of results to not have to foreach the SQL query itself (which is horribly bad)

A: You can do something like this:
SELECT itemNAME, IF(itemSUB ='$itemSUB', 1, 0) AS `Rank`
FROM item_list
WHERE (itemID ='$itemID')
ORDER BY `Rank` DESC

This will return a query of the elements that match both criteria first, and then those that match just one

A: You could try:
SELECT itemNAME
FROM   item_list
WHERE  itemID = '$itemID'
AND    ( itemSUB ='$itemSUB' OR itemSUB IS NULL )
ORDER BY itemSUB DESC
LIMIT 1

If there's row with a matching itemSUB, it'll be first in the set and therefore returned, if not then the row will be the one with NULL
If you are looking for a list a $itemID, you can use an IN - though it's not trivial.
SELECT itemID, itemNAME
FROM   item_list
WHERE  ( itemID, itemSUB ) IN ( $itemIdAndSubList )
OR     ( itemID IN ( $itemIdList ) AND itemSUB ID NULL )
ORDER BY itemID, itemSUB DESC

Now this is a little bit of an odd one - the first 'IN' you are matching ( $itemIdAndSubList ) is not matching a single column, it's matching a pair of columns (a tuple, to give it it's proper name).
The list needs to be in this form:
( itemID1, itemSUB1 ), ( itemID2, itemSUB2 ), ( itemID3, itemSUB3 )

I'd say you'll need to build it yourself in PHP.
$itemIdList is simpler, in the form:
itemID1, itemID2, itemID3

You will end up with something along the lines of this being sent to mysql (newlines added for format clarity only):
SELECT itemID, itemNAME
FROM   item_list
WHERE  ( itemID, itemSUB ) IN ( ( itemID1, itemSUB1 ),
                                ( itemID2, itemSUB2 ),
                                ( itemID3, itemSUB3 ) )
OR     ( itemID IN ( itemID1,
                     itemID2,
                     itemID3 ) AND itemSUB ID NULL )
ORDER BY itemID, itemSUB DESC

Once you get the results back into PHP you'll need to loop over them and pull out the ones you want.
As they are ordered by itemID, then you can just take the first record for each given itemID and it should be the one you want.
Something along the lines of:
$itemNames = array();
foreach( $fetched_data as $fetched_row ) {
    if (!isset( $fetched_row[ 'itemID' ] ) {
       $itemNames[ $fetched_row[ 'itemID' ] ] = $fetched_row[ 'itemNAME' ];
    }
}

$itemNames will then contain the data you need.
I hope that makes sense - try to put it together and see how far you get.

A: The best way in my opinion. Please try this:
SELECT a.itemNAME
FROM item_list a
LEFT JOIN (SELECT itemNAME
           FROM item_list
           WHERE itemID ='$itemID') b
ON(a.itemSUB=b.itemSUB)
WHERE a.itemID ='$itemID' AND a.itemSUB ='$itemSUB'

A: Final solution, as chained with this question: SQL queries inside IN() clause is as follows. Thank You @RobBaillie and other contributors!
SELECT *
FROM item_list
WHERE itemNAME
= ( SELECT itemNAME
    FROM   item_list
    WHERE  itemID = '17'
    AND    (itemSUB ='1' OR itemSUB ='0')
    ORDER  BY itemSUB DESC
    LIMIT  1)
OR itemName
= ( SELECT itemNAME
    FROM   item_list
    WHERE  itemID = '57'
    AND    (itemSUB ='0' OR itemSUB ='0')
    ORDER  BY itemSUB DESC
    LIMIT  1
)

A: First fix your WHERE clause so you can have itemID='$itemID' OR itemSUB=$itemSUB
You could try using something like:
while($row = mysql_fetch_row($query)) {
    print $row;
}

That way you run the query once, then every time you call fetch_row you get a new row from the mysql cursor.
As soon as your query runs out of results, $row will be null and the while loop will finish.


text:
Q: What does setting a class/module name before a variable definition do in Perl? Whilst working with the Net::SIP module I noticed in some of the functions there is code that defines the class of an argument. For example:
sub can_deliver_to {
    my Net::SIP::Leg $self = shift;
    [...]
    return 1;
}

What purpose does specifying Net::SIP::Leg have on defining $self? Is it just syntactic sugar to aid the developer in knowing what type of variable $self should be?

A: It provokes a compile time error, in cases the structure/object is accessed in some invalid way.
See https://perldoc.perl.org/functions/my.html

my VARLIST
my TYPE VARLIST
my VARLIST : ATTRS
my TYPE VARLIST : ATTRS

A my declares the listed variables to be local (lexically) to the enclosing block, file, or eval. If more than one variable is listed, the list must be placed in parentheses.
The exact semantics and interface of TYPE and ATTRS are still evolving. TYPE may be a bareword, a constant declared with use constant , or __PACKAGE__. It is currently bound to the use of the fields pragma, and attributes are handled using the attributes pragma, or starting from Perl 5.8.0 also via the Attribute::Handlers module.

And if you jump at the documentation on fields at https://perldoc.perl.org/fields.html you get this example:
{
    package Foo;
    use fields qw(foo bar _Foo_private);
    sub new {
        my Foo $self = shift;
        unless (ref $self) {
            $self = fields::new($self);
            $self->{_Foo_private} = "this is Foo's secret";
        }
        $self->{foo} = 10;
        $self->{bar} = 20;
        return $self;
    }
}
my $var = Foo->new;
$var->{foo} = 42;

# this will generate a run-time error
$var->{zap} = 42;

# this will generate a compile-time error
my Foo $foo = Foo->new;
$foo->{zap} = 24;


text:
Q: MySQL query to SUM results if php value is less then result Sorry in advance for a long post...
I have this form where a user inputs a startdate, and a enddate the result will be sent to a PHP file that is making variables of the result like this:
PHP
if(isset($_POST['user_selected_dates'])) {
    $invoice_startdate = $_POST['start_date'];
    $invoice_enddate = $_POST['end_date'];
}

Then there is this nasty MySQL query...
SELECT

  s.student_socialnr, s.student_lastname, s.student_firstname,
  cs.city_name,
  c.customer_name,
  scp.cpl_startdate, scp.cpl_enddate, scp.cpl_coursename, scp.cpl_pricevalue,
  SUM(scpe.scpe_days) AS total_days, scp.cpl_pricevalue * SUM(scpe.scpe_days) AS      total_invoice

 FROM studentcourseplan scp
   INNER JOIN students s ON s.student_id = scp.student_id
   INNER JOIN studentcourseplanelements scpe ON scpe.scpe_cpl_id = scp.cpl_id
   INNER JOIN cityselections cs ON cs.city_id = s.student_city_id
   INNER JOIN customers c ON c.customer_id = s.student_customer_id
 WHERE scp.cpl_startdate BETWEEN '$invoice_startdate' AND '$invoice_enddate'

 GROUP BY scp.cpl_id ORDER BY s.student_lastname ASC

that will output something like this in a table (using a PHP mysql_fetch_array):
+------------------+------------------+-------------------+---------------+---------------+---------------+----------------+----------------+------------+---------------+
| student_socialnr | student_lastname | student_firstname | customer_name | cpl_startdate | cpl_enddate   | cpl_coursename | cpl_pricevalue | total_days | total_invoice |
+------------------+------------------+-------------------+---------------+---------------+---------------+----------------+----------------+------------+---------------+
| 000000-0000      | Doe              | John              | A name        | 2012-06-01    | 2012-06-30    | A coursename   | 620            | 40         | 24800         |
+------------------+------------------+-------------------+---------------+---------------+---------------+----------------+----------------+------------+---------------+
| 000000-0000      | Clerksson        | Lisa              | A name        | 2012-01-05    | 2012-07-30    | A coursename   | 950            | 10         | 9500          |
+------------------+------------------+-------------------+---------------+---------------+---------------+----------------+----------------+------------+---------------+
| 000000-0000      | Derpson          | Derp              | A name        | 2012-04-01    | 2012-04-05    | A coursename   | 620            | 40         | 24800         |
+------------------+------------------+-------------------+---------------+---------------+---------------+----------------+----------------+------------+---------------+

Now I'm looking for a function that will do the following:
Create a value for the amount of days between $invoice_startdate and $invoice_enddate. If this value is smaller then the value of result in column total_days do a calculation:  Column price_value * [the result of the new value] and output it to every row (but only if its smaller then the value from the database...)Perhaps it could be done in the MySQL-query? I would really appriciate some help. This is my first website using PHP and MySQL so bear with me!Thank's.

A: I believe you're looking at using a combination of the MySQL IF() and TO_DAYS() functions.  So something like this:
SELECT IF( TO_DAYS(DATE_DIFF('$invoice_enddate', '$invoice_startdate')) < total_days, price_value * ... ) as total_invoice

A: I solved this myself by adding the following code to my query:
CASE WHEN SUM(scpe.scpe_days) > DATEDIFF('$invoice_enddate', '$invoice_startdate') THEN
 (scp.cpl_pricevalue * DATEDIFF('$invoice_enddate', '$invoice_startdate')) ELSE SUM(scpe.scpe_days) * scp.cpl_pricevalue
END AS to_invoice


text:
Q: How to get more ways of interrogating my data source from subsonic In the below link, Linq-To-Sql produces a range of methods to get data back based on various real-world needs (e.g. recent topics, etc).
How can I get Subsonic to produce me a set of classes which would interrogate and return data back from my data source in such a way? I get classes which really just present CRUD ops.
Thanks

A: The way I would do it with SubSonic is to make a view with the way you want the data to be formatted, and then retrieve it with SubSonic.

A: I don't see a link here but in general I'd say you can use SubSonic 3 in much the same way you can Linq to Sql. Here's some sample code:
http://subsonicproject.com/docs/Linq_Select_Queries
Other than that I'd need more specific examples.


text:
Q: ordonate pagination codeigniter i have a problem with my url. My pagination works very well, but it dont look so nice.
For example i wanna to see page 2 and the link become: localhost/page/9 and page 3 become localhost/page/18
i try this function:
if($this->uri->segment($config['uri_segment']))
    {
        $offset = $this->uri->segment($config['uri_segment']);
        $segment_to_replace = $this->uri->segment(2);
        $new_id = $this->uri->segment(2) / 9 +1;
        $new_url = str_replace ($segment_to_replace, $new_id, current_url());
        redirect($new_url);
    }

But the code is not working.
First, var_dup($new_url) return localhost/page/2 and redirect($new_url) return localhost/page/1.222222222.
Another problem is continous redirect. How can i make the URL to show curent page and not the offset of my code.
COMPLETE CODE:
    $this->load->library('pagination');

    $config['base_url'] = 'http://localhost/page/';

    $config['total_rows'] = $this->product_model->count('active');
    $config['per_page'] = 9;
    $config['num_links'] = 3;
    $config['uri_segment'] = 2;
    $config['cur_tag_open'] = ' <b>';
    $config['prev_link'] = 'Previous';
    $config['next_link'] = 'Next';
    $this->pagination->initialize($config);

    if($this->uri->segment($config['uri_segment']))
    {
        $offset = $this->uri->segment($config['uri_segment']);
        $segment_to_replace = $this->uri->segment(2);
        $new_id = $this->uri->segment(2) / 9 +1;
        $new_url = str_replace ($segment_to_replace, $new_id, current_url());

        var_dump($new_url); die;
        return redirect($new_url);
    }

A: $config['use_page_numbers'] = TRUE;

By default, the URI segment will use the starting index for the items
  you are paginating. If you prefer to show the the actual page number,
  set this to TRUE.

Docs.


text:
Q: Crash on startup between agpcpq.sys and acpi.sys -- Win XP My Dell Latitude D505 laptop is not booting. In normal mode, the Windows XP startup screen displays, and then goes blank and hangs indefinitely. In safe mode, it lists drivers up to agpCPQ.sys, and hangs. The next driver to load would have been ACPI.
("Did not load driver Advanced Configuration and Power Interface (ACPI) PC")
I do not have the XP startup/installation disc(s). In my frustration I may have taken a couple of steps to worsen the situation. Unless otherwise noted, everything I tried was performed in the mini-xp environment included in Hiren's Boot Disc. Here's what I've done so far:
Believing it a video problem, I tried to install the most recent graphics drivers, R111509.EXE and then, when that failed, R78792.EXE, which both hang with the message "Installing version...," but when I try a second time, it complains that they're already installed.
I restored the registry from a backup that I had made, to no avail, and then restored the registry from a backup from when system was first installed, which also flopped.
Booted from XP recovery console CD and ran chkdsk mixing and matching various flags, ran fixboot, ran fixmbr, tried different boot.ini configurations.
Ran rootkit removal tools and other malware/spyware tools with latest updates.
Upgraded to the most recent BIOS.
Disabled acpi.sys (which was next in line to load during the crash), and got a BSOD reading:
STOP: 0X0000007B (0xF78C6528,0xC0000034,0x00000000,0x00000000)
Held the fn key and booted without the battery, performing Dell's pre-boot diagnostic. Everything passed.
Reset the CMOS battery.
The last thing I'd done (before the problem arose) was uninstall Windows Defender using iObit Uninstaller software. Perhaps a lousy idea, but I'd read you can uninstall it and use whatever other program(s) for antivirus/firewall, which I'd already been using.
I'm out of ideas.
Oh -- one more: Is it ok that (what I think is) the boot partition is in FAT format? I think that's what I'm seeing (copied below):
diskpart returns,
57232 MB Disk 0 at Id0 on bus 0 on atapi [MBR]
-: Partition1 [FAT]        47 MB         <    39 MB free>
C: Partition2 [NTFS]    57159 MB     < 36603 MB free>
Is there an easy way to change that without formating the partition? Or would that even be necessary or worhtwhile (or safe, eeee-VUHN)?
Anyway, I think I've exhausted my imagination as to what the problem could be, and turn to the internet for guidance. I imagine it's a lost cause, and even so, I'd love to hear at least how people would find the problem, even if it can't be fixed without reinstall. I'd like to know how to hunt that sort of thing down, being new to Windows. After dozens of Google searches, much learning and much frustration, I throw in the towel and humbly enquire: what to do?

A: I got mine going uninstalling all of the anti-virus (BitDefender free and Malware Bytes anti malware).  It is possible an anti-virus update caused some kind of internal malfunction.  This last thing SEEMED to have fixed it, but I did re-install Windows as a last result just previous to this.
If uninstalling anti-virus doesn't work, do try an "in-place install" / re-install.  One or both of these fixed my Win XP, but I am not sure which.
I'm currently fighting with Genuine Validation as it has asked me to re-enter the key, and now won't accept it as genuine.  This is a separate issue, however.


text: Q: What's the point of modular arithmetics ? In my math 123 class were learning about cryptography and in the 3rd section of cryptography we are learning about modules and modular arithmetic's the book does a poor job of explaining it and also how it relates to cryptography. There's also a table involved that has something to do with a one way function.