text:
Q: SDL_SetRenderTarget() hangs for a while if multiple renderer switch occurs There is a problem with rendering target switch on Raspberry Pi. SDL_SetRenderTarget() hangs if multiple renderer switch occurs.
This is a working code that prints milliseconds since application starts before and after a rendering target switch:
#include <stdio.h>
#include "SDL.h"

static SDL_Window* gameWindow = NULL;
static SDL_Renderer* windowRenderer = NULL;
static SDL_Texture* gameTexture = NULL;
static SDL_Texture* texture_1 = NULL;
static SDL_Texture* texture_2 = NULL;
static SDL_Texture* texture_3 = NULL;
static SDL_Texture* texture_4 = NULL;
static SDL_Texture* texture_5 = NULL;
static int row;
static int column;

int main()
{
    // Initialize SDL Video
    if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0)
    {
        printf("%d ms - [INFO] - SDL fails to initialize video subsystem!\n%s", SDL_GetTicks(), SDL_GetError());
        return -1;
    }
    else
        printf("%d ms - [INFO] - SDL Video was initialized fine!\n", SDL_GetTicks());

    // Create window
    gameWindow = SDL_CreateWindow(
                "SDL Render Target Test",
                SDL_WINDOWPOS_CENTERED,
                SDL_WINDOWPOS_CENTERED,
                640,
                480,
                SDL_WINDOW_SHOWN);

    windowRenderer = SDL_CreateRenderer(gameWindow, -1, SDL_RENDERER_ACCELERATED);

    if (windowRenderer == NULL)
        return -1;

    // Set color (this format is RGBA) --> Black, Opaque
    SDL_SetRenderDrawColor(windowRenderer, 0x00, 0x00, 0x00, 0xff);

    // Clear renderer
    SDL_RenderClear(windowRenderer);

    printf("Window and renderer created!\n");

    gameTexture = SDL_CreateTexture(windowRenderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, 320, 240);
    texture_1 = SDL_CreateTexture(windowRenderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_TARGET, 1920, 1080);
    texture_2 = SDL_CreateTexture(windowRenderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_TARGET, 1920, 1080);
    texture_3 = SDL_CreateTexture(windowRenderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_TARGET, 1920, 1080);
    texture_4 = SDL_CreateTexture(windowRenderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_TARGET, 1920, 1080);
    texture_5 = SDL_CreateTexture(windowRenderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_TARGET, 1920, 1080);

    printf("Textures created!\n");

    if (gameTexture == NULL || texture_1 == NULL || texture_2 == NULL || texture_3 == NULL || texture_4 == NULL || texture_5 == NULL)
    {
        SDL_DestroyRenderer(windowRenderer);
        windowRenderer = NULL;

        return -1;
    }

    // Set textures blend mode
    SDL_SetTextureBlendMode(gameTexture, SDL_BLENDMODE_BLEND);
    SDL_SetTextureBlendMode(texture_1, SDL_BLENDMODE_BLEND);
    SDL_SetTextureBlendMode(texture_2, SDL_BLENDMODE_BLEND);
    SDL_SetTextureBlendMode(texture_3, SDL_BLENDMODE_ADD);
    SDL_SetTextureBlendMode(texture_4, SDL_BLENDMODE_BLEND);
    SDL_SetTextureBlendMode(texture_5, SDL_BLENDMODE_MOD);

    printf("Textures blend set!\n");

    // +++ Texture 1 +++ //

    printf("%d ms - [INFO] - Set renderer...\n", SDL_GetTicks());

    // Set target for drawing operation on texture_1
    SDL_SetRenderTarget(windowRenderer, texture_1);

    printf("%d ms - [INFO] - Renderer set!\n", SDL_GetTicks());

    // Set color (this format is RGBA) --> Black, Transparent
    SDL_SetRenderDrawColor(windowRenderer, 0x00, 0x00, 0x00, 0x00);

    // Clear texture_1
    SDL_RenderClear(windowRenderer);

    // Set color (this format is RGBA) --> Black, With some transparency
    SDL_SetRenderDrawColor(windowRenderer, 0x00, 0x00, 0x00, 0x5a); // SDL_BLENDMODE_BLEND

    for (row = 0; row < 1080; row += 4)
        SDL_RenderDrawLine(windowRenderer, 0, row, 1920, row);

    printf("Texture 1 created!\n");

    // +++ Texture 2 +++ //

    printf("%d ms - [INFO] - Set renderer...\n", SDL_GetTicks());

    // Set target for drawing operation on texture_2
    SDL_SetRenderTarget(windowRenderer, texture_2);

    printf("%d ms - [INFO] - Renderer set!\n", SDL_GetTicks());

    for (column = 0; column < 1920; column += 4)
    {
        // SDL_BLENDMODE_BLEND

        // Set color (this format is RGBA)
        SDL_SetRenderDrawColor(windowRenderer, 0x00, 0x00, 0x00, 0xff);
        SDL_RenderDrawLine(windowRenderer, column, 0, column, 1080);

        // Set color (this format is RGBA)
        SDL_SetRenderDrawColor(windowRenderer, 0xff, 0x00, 0x00, 0xff);
        SDL_RenderDrawLine(windowRenderer, column + 1, 0, column + 1, 1080);

        // Set color (this format is RGBA)
        SDL_SetRenderDrawColor(windowRenderer, 0x00, 0xff, 0x00, 0xff);
        SDL_RenderDrawLine(windowRenderer, column + 2, 0, column + 2, 1080);

        // Set color (this format is RGBA)
        SDL_SetRenderDrawColor(windowRenderer, 0x00, 0x00, 0xff, 0xff);
        SDL_RenderDrawLine(windowRenderer, column + 3, 0, column + 3, 1080);
    }

    printf("Texture 2 created!\n");

    // +++ Texture 3 for brightness +++ //

    printf("%d ms - [INFO] - Set renderer...\n", SDL_GetTicks());

    // Set target for drawing operation on texture_3
    SDL_SetRenderTarget(windowRenderer, texture_3);

    printf("%d ms - [INFO] - Renderer set!\n", SDL_GetTicks());

    // Set color (this format is RGBA)
    SDL_SetRenderDrawColor(windowRenderer, 0xff, 0xff, 0xff, 0xd0); // SDL_BLENDMODE_ADD

    // Clear texture_3
    SDL_RenderClear(windowRenderer);

    printf("Texture 3 created!\n");

    // +++ Combine textures to texture_5 +++ //

    printf("%d ms - [INFO] - Set renderer...\n", SDL_GetTicks());

    // Set target for drawing operation on texture_5
    SDL_SetRenderTarget(windowRenderer, texture_5);

    printf("%d ms - [INFO] - Renderer set!\n", SDL_GetTicks());

    // Set color (this format is RGBA) --> Black, Opaque
    SDL_SetRenderDrawColor(windowRenderer, 0x00, 0x00, 0x00, 0xff);

    // Clear texture_5
    SDL_RenderClear(windowRenderer);

    printf("Start texture combination!\n");

    // Render texture_2 to texture_5
    SDL_RenderCopy(windowRenderer, texture_2, NULL, NULL);

    printf("First combination done!\n");

    SDL_DestroyTexture(texture_2);

    // +++ Texture 4 +++ //

    printf("%d ms - [INFO] - Set renderer...\n", SDL_GetTicks());

    // Set target for drawing operation on texture_4
    SDL_SetRenderTarget(windowRenderer, texture_4);

    printf("%d ms - [INFO] - Renderer set!\n", SDL_GetTicks());

    // Set color (this format is RGBA) --> Black, Transparent
    SDL_SetRenderDrawColor(windowRenderer, 0x00, 0x00, 0x00, 0x00);

    // Clear texture_4
    SDL_RenderClear(windowRenderer);

    // Set color (this format is RGBA)
    SDL_SetRenderDrawColor(windowRenderer, 0x00, 0x00, 0x00, 0x15); // SDL_BLENDMODE_BLEND

    for (column = 0; column < 1920; column += 4)
    {
        SDL_RenderDrawLine(windowRenderer, column, 0, column, 1080);
    }

    for (row = 0; row < 1080; row += 4)
    {
        for (column = 1; column < 1920; column += 8)
        {
            SDL_RenderDrawPoint(windowRenderer, column, row);
            SDL_RenderDrawPoint(windowRenderer, column + 1, row);
            SDL_RenderDrawPoint(windowRenderer, column + 2, row);
            SDL_RenderDrawPoint(windowRenderer, column + 3, row);

            SDL_RenderDrawPoint(windowRenderer, column + 4, row + 2);
            SDL_RenderDrawPoint(windowRenderer, column + 4 + 1, row + 2);
            SDL_RenderDrawPoint(windowRenderer, column + 4 + 2, row + 2);
            SDL_RenderDrawPoint(windowRenderer, column + 4 + 3, row + 2);
        }
    }

    printf("Texture 4 created!\n");

    // +++ Combine texture to texture_5 +++ //

    printf("%d ms - [INFO] - Set renderer...\n", SDL_GetTicks());

    // Set target for drawing operation on texture_5
    SDL_SetRenderTarget(windowRenderer, texture_5);

    printf("%d ms - [INFO] - Renderer set!\n", SDL_GetTicks());

    printf("Start texture combination!\n");

    // Render texture_3 to texture_5
    SDL_RenderCopy(windowRenderer, texture_3, NULL, NULL);

    printf("Second combination done!\n");

    SDL_DestroyTexture(texture_3);

    printf("Texture 5 created!\n");

    // +++ Set default rendering target +++ //

    printf("%d ms - [INFO] - Set renderer...\n", SDL_GetTicks());

    // Set target for drawing operation on default rendering target
    SDL_SetRenderTarget(windowRenderer, NULL);

    printf("%d ms - [INFO] - Renderer set!\n", SDL_GetTicks());

    // Set color (this format is RGBA) --> Black, Transparent
    SDL_SetRenderDrawColor(windowRenderer, 0x00, 0x00, 0x00, 0x00);

    // Clear default renderer
    SDL_RenderClear(windowRenderer);

    SDL_DestroyTexture(texture_1);
    SDL_DestroyTexture(texture_4);
    SDL_DestroyTexture(texture_5);

    SDL_DestroyRenderer(windowRenderer);

    SDL_DestroyWindow(gameWindow);

    return 0;
}

This is the ouptut on Ubuntu x86:
108 ms - [INFO] - SDL Video was initialized fine!
Window and renderer created!
Textures created!
Textures blend set!
252 ms - [INFO] - Set renderer...
253 ms - [INFO] - Renderer set!
Texture 1 created!
253 ms - [INFO] - Set renderer...
254 ms - [INFO] - Renderer set!
Texture 2 created!
255 ms - [INFO] - Set renderer...
257 ms - [INFO] - Renderer set!
Texture 3 created!
257 ms - [INFO] - Set renderer...
257 ms - [INFO] - Renderer set!
Start texture combination!
First combination done!
258 ms - [INFO] - Set renderer...
258 ms - [INFO] - Renderer set!
Texture 4 created!
375 ms - [INFO] - Set renderer...
450 ms - [INFO] - Renderer set!
Start texture combination!
Second combination done!
Texture 5 created!
450 ms - [INFO] - Set renderer...
450 ms - [INFO] - Renderer set!

and this one is the result on Raspberry Pi:
94 ms - [INFO] - SDL Video was initialized fine!
Window and renderer created!
Textures created!
Textures blend set!
242 ms - [INFO] - Set renderer...
242 ms - [INFO] - Renderer set!
Texture 1 created!
243 ms - [INFO] - Set renderer...
286 ms - [INFO] - Renderer set!
Texture 2 created!
288 ms - [INFO] - Set renderer...
386 ms - [INFO] - Renderer set!
Texture 3 created!
386 ms - [INFO] - Set renderer...
386 ms - [INFO] - Renderer set!
Start texture combination!
First combination done!
396 ms - [INFO] - Set renderer...
415 ms - [INFO] - Renderer set!
Texture 4 created!
837 ms - [INFO] - Set renderer...
24786 ms - [INFO] - Renderer set!
Start texture combination!
Second combination done!
Texture 5 created!
24787 ms - [INFO] - Set renderer...
24787 ms - [INFO] - Renderer set!

The application hangs for 23 seconds!!! Any idea? Also on Ubuntu x86 there is a slowdown after message Texture 4 created! during rendering set

A: After further investigation I found that the problem is the use of SDL_RenderDrawPoint(). If we move Texture 4 creation at the beginning of the code the slowdown occurs after that texture creation, so after a massive use of SDL_RenderDrawPoint().
I fixed the problem passing from SDL_RenderDrawPoint() to SDL_RenderDrawPoints().
In my case it is ok because that texture is created only one time at startup and in this way we pass from 23 seconds to 200 milliseconds


text:
Q: How to use Ruby Module? The following code works fine:
class Float
  def round
   self.format.to_f
  end

  def format
    "%.2f" % self
  end
end

However, it seems bad practice to monkeypatch a class like Float because other people are doing the same thing and it causes problems.
Then I installed simplecov and the problem started: simplecov monkeypatches the same methods.
So I created a module and mixed it in to Float.
module MyModule
  def round
   self.format.to_f
  end

  def format
    "%.2f" % self
  end
end

Which I guess works as well. But the problem is that simplecov seems to be overwriting the mixed-in method above.
So, what is the proper way to extend built-in classes so that they do not conflict with other people's code?
Ruby 1.9.3

A: Why not use just argument on the round call?
13.6657.round(2)    # => 13.67

But if you are sure you need module (to possibly adjust the format for all Floats out there, I'd propose you just define format method as such:
module MyModule
  def format
    ("%.2f" % self).to_f
  end
end

And mix this in to Float.
And later in code you call the format method instead of round:
13.6657.format     # => 13.67

This way it does not hurt the core functionality (as your initial code dropped the argument from the round definition).
Even better - if you want (can) pinpoint the monkey-patching, simply extend specific instance:
a = 13.6657
a.extend MyModule

a.format           # => 13.67

This way it wont mess with other Floats, but you can still adjust the format without finding all calls to a.round(2) in your code.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Insert a node before another node in singly linked list in Python? I did see this post here [java] and am attempting a similar solution, but the noted thread did not fully answer my question)
I need to work with singly linked lists and want to try and perform an insertBefore() method. I understand that doubly-linked lists have a previous attribute, while singly linked lists do not, so I understand this might be better accomplished using doubly-linked lists, but this was the requirements of the assignment and I'm trying to solve things.
So far below: I've got my Node class setup along with my SinglyLinkedList class. I've also got my insertBefore() method, which is my goal and where I'm getting stuck.
You'll see in my if statement, I'm hoping to compare node.next.value to my targetNode (note that targetNode is a value) -- why is my node.next.value throwing me the following error? if node.next.value == targetNode: AttributeError: 'NoneType' object has no attribute 'value'
# this is our node object
class Node(object):
    def __init__(self, value, next=None):
        self.value = value
        self.next = next

# this is our singly linked list object
class SinglyLinkedList(object):
    def __init__(self):
        self.head = None
        self.tail = None

    def insertBefore(self, targetNode, value):
        # create new node
        newNode = Node(value)
        # find target node to insert
        node = self.head
        if node == None:
            print 'There aren\'t any nodes to insert before!'
        else:
            found = None
            # search nodes
            while node:
                if node.next.value == targetNode:
                    found = True
                    print node.value + ' <--this was node before target'
                    beforeInsert = node
                    afterInsert = node.next
                    beforeInsert.next = newNode
                    newNode.next = afterInsert # sets new node's next to target node
                    node = node.next # continues through while loop
                else:
                    node = node.next
            if found != True:
                print 'Your target node of {} was not found in the list!'.format(targetNode)

Please note: I was able to get this to work for an insertAfter() method (not included in the snippet above), but am struggling to match up the node.next with the targetNode object.

A: As you suggest yourself, the problem seems to be that you create a new node using your target node, node.next == Node(targetNode) as this will never be true.
I assume that targetNode is a Node object, in which case you should simply use node.next == targetNode.
Another problem with your code is that you do not check if the first node is the target node. Thus, you would not be able to insert a node before the head Node using the insertBefore function.
The following code is a rewrite of your insertBefore function which inserts a new node with the specified value before a given node.
def insertBefore(self, targetValue, value):
    # create new node
    newNode = Node(value)
    # find target node to insert
    node = self.head
    if node == None:
        print 'There aren\'t any nodes to insert before!'
    else:
        # search nodes
        if node.value == targetValue:
          newNode.next = self.head
          self.head = newNode

        while node.next is not None:
            if node.next.value == targetValue:
                print ">>> ",node.value,' <--this was node before target'
                newNode.next = node.next
                node.next = newNode
                return
            else:
                node = node.next
        print 'Your target node of {} was not found in the list!'.format(targetNode.value)

If you want targetNode to be the value of the target node, you will need to compare node.next.value with targetNode. Note that this would insert the value before the first occurrence of the target value. Thus, you might want to turn you list into a set instead.

A: Here's how I was able to find a solution to my question:
    def insertBefore(self, targetValue, value):
    # create new node
    newNode = Node(value)
    # find target node to insert
    node = self.head
    if node == None:
        print 'There aren\'t any nodes to insert before!'
    else:
        found = False
        # search nodes
        while node:
            if node.next == None:
                break
            if node.next.value == targetValue:
                found = True
                newNode.next = node.next
                node.next = newNode
                break
            else:
                node = node.next
        if found != True:
            print 'Your target node of {} was not found in the list!'.format(targetValue)

Note, as Jonas pointed out in his comments, the above mentioned solution only works if there are no duplicates in the node list.

A: This is my solution of your problem.
def addBefore(self, nextData, data):
    newNode = Node(data, None)

    if self.head.data == nextData:
        newNode.next = self.head
        self.head = newNode
        return

    ptr = self.head
    while ptr is not None:
        if ptr.data == nextData:
            newNode.next = ptr
            parPtr.next = newNode
            break
        else:
            parPtr = ptr
            ptr = ptr.next


text:
Q: Cannot write data to struct qq4all.
I have a task - write config parser for syntax like this:
[module]
name = first
imitationType = first

[module]
name = second
imitationType = second

etc.
I found pretty config parser - inih, but I can't force it to work as I want. Here my code, writed over inih example:
typedef struct {
    const char* name;
    const char* imitation_type;
} module_config;

int module_count = 0;

static int handler(void* user, const char* section, const char* name,
                   const char* value)
{
    module_config* pconfig = (module_config*)user;
    pconfig = (module_config *) malloc(module_count*sizeof(module_config));
    #define MATCH(s, n) strcmp(section, s) == 0 && strcmp(name, n) == 0
    if (strcmp(section, "module") == 0) {
        if (MATCH("module", "name")) {
            pconfig[module_count]->version = strdup(value);
        } else if (MATCH("module", "imitationType")) {
            pconfig[module_count]->name = strdup(value);
        } else {
            return 0;  /* unknown section/name, error */
        }
    ++module_count;
    pconfig = (module_config *) realloc(pconfig, module_count * sizeof(module_config));
}

return 1;
}

But, when I trying to compile this, I get next error:

Error! Expression for '->' must be 'pointer to struct or union'

for those lines:
pconfig[module_count]->version = strdup(value);
pconfig[module_count]->name = strdup(value);

I'm newbie in programming, and don't understand, why this happens. Please, help :-)

A: pconfig is a pointer to an instance of the module_config struct.
Using pconfig[module_count] on this pointer is equivalent to dereferencing the pointer (pconfig+module_count), i.e. it is equivalent to *(pconfig+module_count).
Thus, pconfig[module_count] is no longer a pointer. You need to use pconfig[module_count].version or (pconfig+module_count)->version.


text:
Q: Как изменить расположение текста в input
надо сделать так чтоб в input текст сразу начинал вводиться вверху а не по середине, спасибо
html
<input type="text" placeholder="Type your message" class="sub_contacts_message">

css
.sub_contacts_message {
   height: 249px;
   width: 731px;
   margin-top: 46px;
   padding-left: 54px;
   font-size: 16px;
   font-weight: 400;
   border: none;
   border-radius: 7px;
   font-family: 'Open Sans', sans-serif;
   color: #676767;
   background-color: #e5e5e5;
}

A: можно, конечно и через input сделать, но придется JS подключать, самый просто вариант:

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.form-group textarea {
  height: 249px;
  width: 731px;
  margin-top: 46px;
  padding-left: 54px;
  padding-top: 15px;
  font-size: 16px;
  font-weight: 400;
  border: none;
  border-radius: 7px;
  font-family: 'Open Sans', sans-serif;
  color: #676767;
  background-color: #e5e5e5;
  resize: none;
}
<div class="form-group">
  <textarea placeholder="Type your text"></textarea>
</div>


text:
Q: loop through a list of properties I got following problem.
I have a view properties in my class which access a config and can raise a ValueError if the user added garbage to the config.
I would like to write a method to check my config-file for errors, so I thought I look through every property in a list and try to access its value. Therefore I would not need to duplicate the try-except for every property.
I tried the following code, which - of course - calls the properties when creating the list and therefore throws the error outside my try.
Is there an elegant solution to my problem?
import random

def load_config():
    rand_number = random.randint(0, 9)
    if rand_number == 5:
        raise ValueError

    return rand_number

class foo:
    @property
    def bar1(self):
        return load_config()

    @property
    def bar2(self):
        return load_config()

    @property
    def bar3(self):
        return load_config()

    @property
    def bar4(self):
        return load_config()

    @property
    def bar5(self):
        return load_config()

    def check_properties(self):
        properties = [
            self.bar1, //Exceptions are thrown here
            self.bar2,
            self.bar3,
            self.bar4,
            self.bar5,
        ]

        for property in properties:
            try:
                num = property
            except ValueError:
                print("ValueError at " + property.__name__)

my_foo = foo()
my_foo.check_properties()

To make an mve I replaced the property-bodies with a call to a function with creates a random ValueError

A: You can define check_properties with something like this:
def check_properties(self):
        properties = [property_name for property_name, obj in self.__class__.__dict__.items()
                          if isinstance(obj, property)]

        for property_name in properties:
            try:
                getattr(self, property_name)
            except ValueError:
                print("ValueError at " + property_name)

It will attempt to evaluate the property in getattr.
This will not work for properties inherited by the base class. You could use a helper function like this instead if you use inheritance:
def get_property_names(cls, follow_inheritance=False):
    property_names = []

    for attr_name, attr in cls.__dict__.items():
        if isinstance(attr, property):
            property_names.append(attr_name)

    if follow_inheritance:
        for parent_class in cls.__mro__:
            if parent_class != cls:
                property_names.extend(get_property_names(parent_class, True))

    return property_names

then define check_properties as:
def check_properties(self):
        properties = get_property_names(self.__class__, follow_inheritance=True)

        for property_name in properties:
            try:
                getattr(self, property_name)
            except ValueError:
                print("ValueError at " + property_name)


text:
Q: List of all elements of $A_4$ - Jamie Mulholland p. 85
p. 72: $m$-cycle $\iff m - 1$ transpositions. Hence 3-cycle $\iff 2$ transpositions.

I condone all the calculations overhead, but I don't understand the proof blueprint.
(1.) How do you envisage and envision to list all elements with cycles of length $\le 2$ and 3-cycles?  Why not list other things? How do you know this is enough? I know $|A_4| = 4!/2 = 12$.
(2.) How do you craftily, indefectibly list all the 3-cycles ?
I keep fretting about if I missed something or listed the same thing more than once.

A: $A_4$ is a subset of $S_4$. There are only 5 kinds of element in $S_4$: $(),(xx),(xxx),(xxxx),(xx)(xx)$. $A_4$ is the even permutations, $(),(xxx),(xx)(xx)$ --- the others are all odd permutations.
A 3-cycle fixes one number.
If it fixes the number $1$, then it must be $(234)$ or $(432)$.
If it fixes the number $2$, then it must be $(134)$ or $(431)$.
And so on.
If there's anything needing clarification, please let me know.

A: A permutation $\in S_n$ is even iff its cycle decomposition contains an even number of 2-, 4-, 6- etc. cycles (because these are odd) whereas the number of 1-, 3-, 5-, etc. cycles doesn't matter (because thy are even by themselves.
So for $n=4$ we have

*

*no 2-cycles and no other cycles (i.e. otherwise only 1-cycles): $e$

*no 2-cycles and one 3-cycle: The eight 3-cycles from above

*no 2-cycles and a 5- or longer cyle: not applicable

*no 2-cycles and at least two 3- or longer cycles: not applicable

*two 2-cycles: The three elements listed above

*two 2-cycles and one or more 3- or longer cycle: not applicable here

*four or more 2-cycles and possibly more: not aplicable here


text:
Q: how to raise a custom exception in main method proper? I am trying to understand how to raise a custom error in main method with action. Below is my sudo code but don't work.
I want to raise a custom exception that will go to except in main method with tag, message value. but the below code output a class:
class 'main.pdv_error_response'
class my_exceptions(Exception):
   """Base class for other exceptions"""
   pass

class pdv_error_response(my_exceptions):
    def __init__(self, tag, message):
        self.tag = tag
        self.tag = message

def tryerror(x):
    if x < 0:
        raise(pdv_error_response('test','output'))

def main():
    try:
        tryerror(-1)
    except:
        if pdv_error_response:
            print(pdv_error_response)

if __name__ == '__main__':
    main()

A: It seems that you are printing an object so it will not print your message for that you have to change in your main().
def main():
    try:
        tryerror(-1)
    except pdv_error_response as e:
        if pdv_error_response:
            print(e)

Now you can get your expected output.
You can refer User Defined Exception for more.


text:
Q: Generic object updater - convert array to list I'm trying to make a generic class, which is capable to update any property of an object.
I made it working for several cases, e.g. single value properties (int, string, bool, etc.). It also works nicely if a property is an IEnumerable<T>, in that case either Lists or Arrays work fine.
But I hit the wall with a scenario if the property is List<T>, but the value to be assigned is an Array (or the other way around). In a "standard" situation I could simply use ToList() or ToArray, but in a generic case, I'm puzzled how to.
Here's the code
public static class ObjectUpdater
{
    public static T Patch<T>(T obj, IEnumerable<KeyValuePair<string, object>> delta)
    {
        if (obj == null || delta == null)
        {
            return obj;
        }
        foreach (var deltaItem in delta)
        {
            Patch(obj, deltaItem.Key, deltaItem.Value);
        }
        return obj;
    }

    private static void Patch<T>(T obj, string propertyName, object value)
    {
        var propertyInfo = obj.GetType().GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
        if (propertyInfo == null || !propertyInfo.CanRead || !propertyInfo.CanWrite)
        {
            throw new ArgumentException($"Property '{propertyName}' doesn't exist or cannot be updated");
        }
        SetPropertyValue(obj, value, propertyInfo);
    }

    private static void SetPropertyValue(object obj, object value, PropertyInfo propertyInfo)
    {
        if (propertyInfo.PropertyType.IsEnum)
        {
            propertyInfo.SetValue(obj, Convert.ToInt32(value));
            return;
        }

        // property parsing is based on the target property's TryParse() method
        // big / small enough float / DateTime values had issues, as the ToString() might lose precision >> they're handled separately
        if (value is float)
        {
            SetPropertyValueAsFloat(obj, (float)value, propertyInfo);
            return;
        }

        if (value is DateTime)
        {
            SetPropertyValueAsDateTime(obj, (DateTime)value, propertyInfo);
            return;
        }

        var systemType = propertyInfo.PropertyType.UnderlyingSystemType;
        var tryParse = systemType.GetMethod("TryParse", new[] {typeof(string), systemType.MakeByRefType()});
        if (tryParse == null)
        {
            propertyInfo.SetValue(obj, value);
            return;
        }
        var parameters = new object[]
                         {
                             value.ToString(),
                             null
                         };
        var canParse = (bool) tryParse.Invoke(null, parameters);
        propertyInfo.SetValue(obj, canParse ? parameters[1] : value);
    }

    private static void SetPropertyValueAsDateTime(object obj, DateTime value, PropertyInfo propertyInfo)
    {
        // code to handle DateTime value
    }
}

// and two test methods
[Fact]
private void Patch_StringListPropertyFromArrayValue()
{
    var sourceObject = new TestClassWithCollectionProperties
                       {
                           StringListProperty = null
                       };
    var expectedResult = new TestClassWithCollectionProperties
                         {
                             StringListProperty = new List<string>
                                                  {
                                                      "abc",
                                                      "def"
                                                  }
                         };
    var delta = new List<KeyValuePair<string, object>>
                {
                    new KeyValuePair<string, object>("StringListProperty",
                        new []
                        {
                            "abc",
                            "def"
                        })
                };

    var result = ObjectUpdater.Patch(sourceObject, delta);

    result.ShouldBeEquivalentTo(expectedResult);
}

[Fact]
private void Patch_StringArrayPropertyFromListValue()
{
    var sourceObject = new TestClassWithCollectionProperties
                       {
                           StringArrayProperty = null
                       };
    var expectedResult = new TestClassWithCollectionProperties
                         {
                             StringArrayProperty = new[]
                                                   {
                                                       "abc",
                                                       "def"
                                                   }
                         };
    var delta = new List<KeyValuePair<string, object>>
                {
                    new KeyValuePair<string, object>("StringArrayProperty",
                        new List<string>
                        {
                            "abc",
                            "def"
                        })
                };

    var result = ObjectUpdater.Patch(sourceObject, delta);

    result.ShouldBeEquivalentTo(expectedResult);
}

But this test fails as ObjectUpdater.Patch throws a System.ArgumentException with the following message

Object of type 'System.String[]' cannot be converted to type 'System.Collections.Generic.List`1[System.String]'.

Any suggestions?

A: Well, you can handle the concrete case somewhere in the code before tryParse attempt with something like this:
if (value != null && value.GetType() != propertyInfo.PropertyType
    // from T[]
    && value.GetType().IsArray && value.GetType().GetArrayRank() == 1
    // to List<T>
    && propertyInfo.PropertyType.IsGenericType
    && propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(List<>)
    && propertyInfo.PropertyType.GetGenericArguments()[0] == value.GetType().GetElementType())
{
    var T = value.GetType().GetElementType();
    var listT = typeof(List<>).MakeGenericType(T);
    // new List<T>(IEnumerable<T> items)
    var enumerableT = typeof(IEnumerable<>).MakeGenericType(T);
    var newListT = listT.GetConstructor(new Type [] { enumerableT });
    var list = newListT.Invoke(new[] { value });
    propertyInfo.SetValue(obj, list);
    return;
}

The above handles assignment form T[] to List<T>. To handle the opposite assignment, add a similar if condition with types swapped and simply call List<T>.ToArray) method via reflection:
if (value != null && value.GetType() != propertyInfo.PropertyType
    // to T[]
    && propertyInfo.PropertyType.IsArray && propertyInfo.PropertyType.GetArrayRank() == 1
    // from List<T>
    && value.GetType().IsGenericType
    && value.GetType().GetGenericTypeDefinition() == typeof(List<>)
    && value.GetType().GetGenericArguments()[0] == propertyInfo.PropertyType.GetElementType())
{
    // List<T>.ToArray()
    var toArray = value.GetType().GetMethod("ToArray", Type.EmptyTypes);
    var array = toArray.Invoke(value, null);
    propertyInfo.SetValue(obj, array);
    return;
}


text:
Q: Using jquery, how can I get this "inner text" of a li element? I have the following html and I am trying to figure out the right selector logic to read in certain part. NOTE: I can't change the html as this is being generated by a plugin.

      ×
    MS Office

      ×
    Photoshop

and I am trying to read out the text inside the

but NOT including the

so for the example above, I am looking to parse out the following text:
 MS Office, Photoshop

A: Try like this
$('.select2-selection__choice').each(function() {
    var text = $(this).clone().children().remove().end().text();
    console.log(text.trim());
});

SNIPPET

$('.select2-selection__choice').each(function() {
    var text = $(this).clone().children().remove().end().text();
    console.log(text.trim());
});

      ×
    MS Office

      ×
    Photoshop

A: Use the .class selector:
$('.select2-selection__choice').each(function() {
    var inneText = $(this).children().text();
});


text:
Q: interface and inheritance in java I have a question of how to relate interface to inheritance, for example:
if class A implements interface X, also class A is the superclass of class B and class C, my question is , does it mean both class B and class c will automatically implement interface X as well?

A: It depends if class A is an abstract class or not.  Assuming that class A fully implements interface X then both B and C will implement X.  For example each line of code would be perfectly fine...
X one = new A();
X two = new B();
X three = new C();

A:
if class A implements interface X, also class A is the superclass of class B and class C, my question is , does it mean both class B and class c will automatically implement interface X as well?

Not if A has an implementation.  Otherwise, yes they need to.
public interface X{ public void stuff();}

public class A implements X {
   // A not abstract, must implement "stuff()"
   // therefore, B and C will automatically have an implementation of "stuff()" too
}

but if A is abstract
public abstract A implements X {
    // not implemented.  B and C will need to implement
    public abstract void stuff(); // not implemented
}

A: no not necessary to implement the functions in the superclass
suppose if the
interface X(){

function A();

function B();

}

class A implements X(){
@override
function A(){
//do something
}

function B(){
//do something
}

}

class B extends A{

}
class C extends A{

}  //-> that time your subclass need to implement the functions.

A: Does it mean both class B and class c will automatically
implement interface X as well?

Not really. It is not compulsory to implement all method in supper class in sub classes if super class is not a fully abstract class. But all attribute in supper class will inherited to sub classes.

A: If X is the interface and A the implementation(not an abstract class). Irrespective of any other class down the hierarchy, Class A needs to implement all its methods.
If X is an abstract class, then class B and class C both should provide the implementation of the methods which are not provided in Class A.
In both the cases, Class B and Class C both will be the implementation of the interface X

A: X : is an interface
A : concrete class implementing X
B : concrete class extending A
C : concrete class extending A
IF A CLASS IMPLEMENTS A CLASS : it means the implementing class has to implement (i.e. define all methods ) from interface
IF A CLASS EXTENDS A CLASS  : it means that all the methods from the parent class is available in child class , unless the child class overrides the methods .
now we conclude , since B,C extend all the methods from A , and A has implemented all the methods from X , thus both B,C have the methods from interface X implemented in A .
but we cant say that B,C implement X because B,C have no constraint to implement all methods from interface , but class A has to implement all the methods


text:
Q: DirectShow video compressors enumeration issue I am trying to find available DirectShow video encoders, using following code:
ICreateDevEnumPtr pEnm(CLSID_SystemDeviceEnum,NULL,CLSCTX_INPROC_SERVER);
// Video Compressor
if(pEnm!= NULL)
{
    IEnumMonikerPtr pEnumMoniker;
    hr = pEnm->CreateClassEnumerator(CLSID_VideoCompressorCategory,&pEnumMoniker,0);
    //......
}

However, some video compressors installed in the system (Windows 10 x64) have different category.
For example "Microsoft MPEG-2 Encoder" and "VisioForge H264 Encoder" have category {083863F1-70DE-11d0-BD40-00A0C911CE86} - CLSID_LegacyAmFilterCategory
If I use CLSID_LegacyAmFilterCategory instead of CLSID_VideoCompressorCategory in my code, I get a lot of irrelevant objects.
Can you suggest the proper way to enumerate the DirectShow video compressors installed in the system ?

A: There is no better way and most likely you don't need any other way. You need this enumeration to eventually check availability of specific codec of interest and instantiate it. It is hard to imagine that you are building an application capable to pick some arbitrary installed codec and be able to use it, you normally deal with compression codecs you are well familiar with, esp. H.264 video compression codecs which have certain specific configuration methods etc. For the codecs you are familiar with you would want to have codec specific instantiation and configuration ways, one might need a discovery through enumeration, another would be available for instantiation via CLSID directly.


text:
Q: How to mark a zlib licensed library as altered/edited by my name? Hey so i've recently taken some pretty old source code from a GUI library, code that has been abandoned and forgotten, and did a massive amount of editing/fixing on it to the point where 50% of the code is now mine.
This library is licensed though, so if I wanted to put out there for others to use, how would i give myself credit for the 50% of code i wrote?

A: IANAL.
This is going to be a partial answer.
According to the zlib license you have to mark altered versions as such:

2 . Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.

However, you may not alter the license notice:

3 . This notice may not be removed or altered from any source distribution.

The question seems to reduce to whether or not the copyright line before the license is part of "This notice". This is a question I can't answer.
However, libpng developers have handled the issue gracefully and if you are lucky, the authors of the original software in question have followed the same route:

If you modify libpng you may insert additional notices immediately following this sentence.

A: I'm not sure what you're asking here. You give yourself credit by giving yourself credit. Just say that portions of the code came from project X that was released under the zlib license. This is exactly what you would normally do if you hadn't modified the code at all.
All the zlib license says is that you can't pretend that you wrote the original, and that if you make alterations, you can't say that it is the original product.


text:
Q: Weird issue on IE (IE9 and lower) with JavaScript (jQuery) I am experiencing a weird problem on IE (IE 9 and lower).
I have a form having a select and a radio. When anyone changes anything in the select or radio, it calculates the total price.
Here is the code: http://jsfiddle.net/Debiprasad/DLQ82/8/
It works fine in all browsers. But when I am testing this on IE: When I am changing the select value, then it works fine. But when I am changing the value radio, then it does not work.
The weird part is, if I added an alert to any of the functions, which executed when the value of radio changes, then it works fine on IE.
What could be the problem and how to fix this?

A: In IE, the change event on radio and checkbox controls only fires when the element loses focus, unlike other browsers.
I think jQuery fixed their change event to use propertychange in IE some time ago, you can see this by changing the jQuery version in jsFiddle to 1.3.2 and observing the different behaviour.  Which version of jQuery are you using locally?


text:
Q: PHP NuSoap Server return array of complex types There are many questions relating to this online which are just unanswered and I am looking for a solution all over the place.
So I have a Soap Server with NuSoap and I am trying to return an array of database rows (modelled here as a hardcoded list of PS4 game entities).
The code below here works (with slight modification) for returning a single array, however I am unable to get more than 1 of them to be returned.
Does anyone have a solution for this as I have spent the day trying various solutions from online as well as the code below:
//Settings

$ns = 'http://'.$_SERVER['HTTP_HOST'].'/index.php/soapserver/';
$this->load->library("Nusoap_library");
$this->nusoap_server = new soap_server();
$this->nusoap_server->configureWSDL("Nusoap Server", $ns);
$this->nusoap_server->wsdl->schemaTargetNamespace = $ns;

//Complex Types and Function registers on server

// Complex Type "Game":
$this->nusoap_server->wsdl->addComplexType(
    'Game', // the type's name
    'complexType',
    'struct',
    'all',
    '',
    array(
        'title' => array('name'=>'title','type'=>'xsd:string'),
        'description' => array('name'=>'description','type'=>'xsd:string'),
        'price' => array('name'=>'price','type'=>'xsd:string'),
    )
);

// Complex Type "Games" (array of Game):
$this->nusoap_server->wsdl->addComplexType(
    'Games',
    'complexType',
'array',
'',
'SOAP-ENC:Array',
array(),
array(
    array(
        'ref'=>'SOAP-ENC:arrayType',
        'wsdl:arrayType'=>'tns:Game[]'
    )
),
'tns:Game'
);

// Get_Games
$this->nusoap_server->register(
    'get_games',
    array('instance_id' => 'xsd:string'),
    array('return'=>'tns:Games'),
    '',
    false,
    'rpc',
    'encoded',
    'Return array of Games'
);

// [REGISTERED METHODS]:
function get_games($instance_id)
{
    // [Hardcoded Games list]:
    $games = array(
        array(
            'title' => 'Killzone: Shadow Fall',
            'description' => 'test desc ',
            'price' => '49.99'
        ),
        array(
            'title' => 'Battlefield',
            'description' => 'blah blah',
            'price' => '54.99'
        )
    );

    return $games;
}

QUESTION:
What changes do I need to make to the above code to get this server to return an array of game entities.
It works fine if I return $games[0] with some minor changes to the code, however I can not seem to get the above code to work.
Any help or advice appreciated...
EDIT:
I consistantly get the following error:
    Error

    XML error parsing SOAP payload on line 10: Invalid document end

    Response

    HTTP/1.1 200 OK
    Date: Sun, 16 Mar 2014 20:35:35 GMT
    Server: Apache/2.4.7 (Win32) OpenSSL/1.0.1e PHP/5.5.6
    X-Powered-By: PHP/5.5.6
    X-SOAP-Server: NuSOAP/0.9.5 (1.123)
    Content-Length: 1688
    Content-Type: text/xml; charset=ISO-8859-1

A PHP Error was encountered

Severity: Notice

Message:  Array to string conversion

Filename: lib/nusoap.php

Line Number: 6132

A PHP Error was encountered

Severity: Notice

Message:  Array to string conversion

Filename: lib/nusoap.php

Line Number: 6132

<?xml version="1.0" encoding="ISO-8859-1"?><SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="http://localhost/index.php/soapserver/"><SOAP-ENV:Body><ns1:get_gamesResponse xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/"><return xsi:type="SOAP-ENC:Array" SOAP-ENC:arrayType="tns:Game[2]"><item xsi:type="tns:Game"><title xsi:type="xsd:string">Killzone: Shadow Fall</title><description xsi:type="xsd:string">test desc</description><price xsi:type="xsd:string">49.99</price></item><item xsi:type="tns:Game"><title xsi:type="xsd:string">Battlefield</title><description xsi:type="xsd:string">blah blah</description><price xsi:type="xsd:string">54.99</price></item></return></ns1:get_gamesResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>

A: This is what I did:
// Complex Array Keys and Types ++++++++++++++++++++++++++++++++++++++++++
$server->wsdl->addComplexType('notaryConnectionData','complexType','struct','all','',
        array(
                'id' => array('name'=>'id','type'=>'xsd:int'),
                'name' => array('name'=>'name','type'=>'xsd:string')
        )
);
// *************************************************************************

// Complex Array ++++++++++++++++++++++++++++++++++++++++++
$server->wsdl->addComplexType('notaryConnectionArray','complexType','array','','SOAP-ENC:Array',
        array(),
        array(
            array(
                'ref' => 'SOAP-ENC:arrayType',
                'wsdl:arrayType' => 'tns:notaryConnectionData[]'
            )
        )
);
// *************************************************************************

// This is where I register my method and use the notaryConnectionArray
$server->register("listNotaryConnections",
                array('token' => 'xsd:string'),
                array('result' => 'xsd:bool', 'notary_array' => 'tns:notaryConnectionArray', 'error' => 'xsd:string'),
                'urn:closingorder',
                'urn:closingorder#listNotaryConnections',
                'rpc',
                'encoded',
                'Use this service to list notaries connected to the signed-in title company.');

// In my function, I query the data and do:
$list = array();
$results = mysql_query($query);
while($row = mysql_fetch_assoc($results)) {
    array_push($list, array('id' => intval($row['na_id']), 'name' => $row['agency_name']));
}

return array("result" => true, "notary_array" => $list);

// The output is:
Array
(
    [result] => 1
    [notary_array] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [name] => Agency 1
                )

            [1] => Array
                (
                    [id] => 3
                    [name] => Agency 3
                )

            [2] => Array
                (
                    [id] => 4
                    [name] => Agency 4
                )

        )

    [error] =>
)

Hope this helps.


text:
Q: How to get the PK_ID of the last inserted row in oracle? I have a scenario where I have to return the pkId of the row which is inserted into the db recently. But i am afraid there is no straight way to achieve it in Oracle. Can any one tell any way to do it?

A: Assuming 10g+, use the RETURNING clause:
INSERT INTO YOUR_TABLE
  (columns...)
VALUES
  (...)
RETURNING <expression> INTO <variables>

For more info, see:

*

*http://www.lattimore.id.au/2006/04/06/oracle-returning-clause/

*http://www.oracle-base.com/articles/misc/dml_returning_into_clause.php


text:
Q: Drawing Signal Flow Graph from Bridged-T Network I am confused about where to place R1. Is it a feed-forward or feedback term? Y1 and Y2 are admittances representing the capacitors.

A: I think is ok as graph nut you have to use Gx=1/Rx in each branch, check this out http://dknollman.50webs.com/k9analysis/Signal_Flow.html


text:
Q: Call external JInternalFrame toFront() I need the JInternalFrame that call through a menu / button to always be placed in front of the screen and block the previous ones.
I can not do it and I think it is a mistake in the structure of my application.
Try in every possible way, I must have some misconception.
Calls, like :
    final Estadisticas frameEstadisticas = new Estadisticas();
    JMenuItem mntmEstadisticas = new JMenuItem("Estadisticas");
    mntmEstadisticas.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            if (!frameEstadisticas.isVisible()) {
                contentPane.add(frameEstadisticas);
                frameEstadisticas.setVisible(true);
            }
            else {
                JOptionPane.showMessageDialog(contentPane, "Ya tiene esa aplicacion abierta", "Error Aplicacion",JOptionPane.YES_NO_OPTION);
            }
        }
    });

But the result is like this:
1: JInternalFrame "Agregar Alumno"
2: JInternalFrame "Estadisticas"
"Estadisticas" should be in front.

Sorry for my english.


text:
Q: Geometric series convergence and upper bound of its absolute value
If I know the following: $1/4 \le |X_n| \le 1/2$ for all $n\ge 1$, then I must prove that $$\sum_{n=1}^\infty (X_n)^n$$ converges and that $$ \left|\sum_{n=1}^\infty (X_n)^n\right|\le 1$$

I used comparaison trick to show that $$\sum_{n=1}^\infty \left({\frac{1}{2}}\right)^n$$ converges to ${\frac{1}{1-{\frac{1}{2}}}}=2$, thus $\sum_{n=1}^\infty \left|(X_n)^n\right|$ also converges, since $|X_n|^n \le \left(\frac{1}{2}\right)^n$ so $$ \sum_{n=1}^\infty \left|(X_n)^n\right|\le 2$$

A: Hint: You start from $n=1$ but the geometric series starts from $n=0$. So, you must substract $X^0_n=1$ from the upper bound that you found.

A: $\sum_{n=1}^\infty ({\frac{1}{2}})^n=\sum_{n=0}^\infty ({\frac{1}{2}})^n-1=2-1=1$


text:
Q: Find all the AMIs which do not have an instance associated with it In my aws account, I am having lots of snapshot and ami. I need to find all ami which is not associated instance and need to find all snapshot which is not associated instance.

*

*Find all the AMIs which do not have an instance associated with it.

*Find all the Snapshots which do not have an instance associated with it.

I am not able to find out what is a command between ami and instance...
Please help me....

A: You can get the list of AMIs that your EC2 instances were launched from using:
aws ec2 describe-instances --query "Reservations[].Instances[].ImageId"

You can get the list of AMIs that you own using:
aws ec2 describe-images --owners self --query "Images[].ImageId"

Add some basic scripting to test if the AMI IDs in the second list are absent from the first list.
Add --output text if it helps you parse the results.
Run this in the appropriate regions, by adding --region <region>.


text:
Q: Horizontal Rules Before and After Multicols I am trying to make a document that partially mimics the output of macOS's Calendar.app "List" print format, which looks like this:

The part I am interested in here is connecting the column separating rule to the horizontal rule. This also happens similarly at the bottom of the page.
(Note that although this looks a bit tabular, in my application, there will be varying amounts of text under each heading.)
Here is my attempt so far:
\documentclass[12pt]{article}
\usepackage[vmargin=0.5in, hmargin=0.25in, footskip=0.25in]{geometry}
\usepackage{microtype}
\usepackage{multicolrule}
    \SetMCRule{width=0.4pt, line-style=solid, extend-fill, extend-top=1ex}
    %\setlength{\multicolsep}{0pt}
\usepackage{lastpage}
\usepackage{fancyhdr}
    \fancyhead[L,C,R]{}
    \renewcommand{\headrulewidth}{0pt}
    \fancyfoot[L,C]{}
    \fancyfoot[R]{\footnotesize Page \thepage/\pageref{LastPage}}
    \renewcommand{\footrulewidth}{0.4pt}
    \pagestyle{fancy}

\renewcommand{\familydefault}{\sfdefault}
\setlength{\parindent}{0pt}

\begin{document}
{\LARGE\bfseries Header}

%\rule[-2.5pt]{\textwidth}{0.4pt}
\rule{\textwidth}{0.4pt}

\begin{multicols*}{2}
    {\Large\bfseries Section Head}\\\smallskip
    \textbf{Some details}\\
    \textbf{Location:} Other, less important details\\
    more less important details\\\smallskip

    \textbf{Some details}\\
    \textbf{Location:} Other, less important details\\
    more less important details\\\smallskip
    \hspace{\fill}\rule{0.95\columnwidth}{0.4pt}\hspace{\fill}

    {\Large\bfseries Second Section}\\\smallskip
    etc.
\end{multicols*}
\end{document}

I have used multicolrule's option extend-fill to bring the colseprule to the bottom of the page and its extend-top option to give the initial text a bit of breathing room.
I have used \rule to create the rule at the top of the page and have experimented with different drop values to make the lines intersect, but when I started doing a binary search between 1pt and 5pt I decided that such an approach was too brittle.
For the bottom rule, I've tried to use fancyhdr's foot rule, which unfortunately offers no configuration hooks other than its width. I experimented with redefining the command that typesets the rule but again found myself taking the brittle approach I rejected for the top rule.
Is there a better way to make this happen?

A: You could use the custom-line option of multicolrule to draw the horizontal rules along with the vertical one. This requires using tikz:
\documentclass[12pt]{article}
\usepackage[vmargin=0.5in, hmargin=0.25in, footskip=0.25in]{geometry}
\usepackage{microtype}
\usepackage[tikz]{multicolrule}
\usetikzlibrary{calc}
\usepackage{lastpage}
\usepackage{fancyhdr}
\fancyhead[L,C,R]{}
\renewcommand{\headrulewidth}{0pt}
\fancyfoot[L,C]{}
\fancyfoot[R]{\footnotesize Page \thepage/\pageref{LastPage}}
\pagestyle{fancy}

\renewcommand{\familydefault}{\sfdefault}
\setlength{\parindent}{0pt}

\SetMCRule{width=0.4pt, extend-top=2pt, extend-bot=-2pt, custom-line={
    \coordinate (TOPLEFT) at ($(TOP)-(\columnwidth+.5\columnsep,\columnseprule)$);
    \coordinate (TOPRIGHT) at ($(TOP)+(\columnwidth+.5\columnsep,-\columnseprule)$);
    \coordinate (BOTLEFT) at ($(BOT)-(\columnwidth+.5\columnsep,-\columnseprule)$);
    \coordinate (BOTRIGHT) at ($(BOT)+(\columnwidth+.5\columnsep,\columnseprule)$);
   \draw[line width=\columnseprule] (TOPLEFT) -- (TOPRIGHT)
   (TOP) -- (BOT) (BOTLEFT) -- (BOTRIGHT);}}

\begin{document}
  {\LARGE\bfseries Header}

\begin{multicols*}{2}
    {\Large\bfseries Section Head}\\\smallskip
    \textbf{Some details}\\
    \textbf{Location:} Other, less important details\\
    more less important details\\\smallskip

    \textbf{Some details}\\
    \textbf{Location:} Other, less important details\\
    more less important details\\\smallskip
    \hspace{\fill}\rule{0.95\columnwidth}{0.4pt}\hspace{\fill}

    {\Large\bfseries Second Section}\\\smallskip
    etc.
  \end{multicols*}
\end{document}

Result:


text:
Q: How to get wrapped component instance with recompose? I'm using lifecycle to create a Higher-Ordered Component. I need access to the wrapped component instance. How can I get it?
e.g.
export default function ajaxLoader(options) {
    return lifecycle({
        componentWillMount() {
            // how to get *wrapped* component instance here?
            // `this` refers to an instance of the lifecycle HOC, not the wrapped component
            // i.e., I want the instance of `SomeComponent`
        }
    }) // this returns a function that accepts a component *class*
}

And the usage, if you want to see that too:
class SomeComponent extends React.PureComponent {

    render() {
        return <span/>;
    }
}

const WrappedComponent = ajaxLoader({
    // options
})(SomeComponent);

I think I could have gotten a reference to the wrapped component if I overrode the render() method in my HOC, and rendered the wrapped component with ref=..., but recompose specifically won't let me implement the render method myself.

It supports the entire Component API, except the render() method, which is implemented by default (and overridden if specified; an error will be logged to the console).

A: If you must have access to instance methods you can do something like this:
class ParentComponent extends Component {
  constructor(props) {
    super(props);
    this.childController = null;
  }

  // access child method via this.childController.instanceMethod

  render() {
    return <DecoratedChildComponent provideController={controller => this.childController = controller} />
  }
}

class ChildComponent extends Component {
  componentDidMount() {
    this.props.provideController({
      instanceMethod: this.instanceMethod,
    })
  }

  componentWillUnmount() {
    this.props.provideController(null);
  }

  instanceMethod = () => {
    console.log("I'm the instance method");
  }
}

This is a little convoluted, and in most cases can be avoided, but it you really need to access an instance method, this will work


text:
Q: How to launch program with user permissions instead of active permissions I have a C# application which runs and displays a tray icon. I have an installer for my tray application which launches the application after installation. The installer requires admin permissions whereas the tray icon must be run with normal permissions. My installer currently breaks this - when the installed tray application is launched it inherits admin permissions from the installer process.
As part of my installer I am launching a C# application to perform some custom work. This small application currently launches the tray application by calling:
Process.Start(@"path/to/my/tray/app.exe");

Is there any way to invoke the tray app with the current user's permissions rather than the elevated permissions given to the installer?
I have heard that the recommended way to do this is to have a wrapper EXE around the installer which launches the installer then launches the installed program. I would like to avoid this if possible.
I am using WiX to build an MSI installer so I would also accept solutions which work directly from WiX/MSI.

A: There are two approaches. The simplest is to use a shell exe that first launches the admin task elevated (lots of ways to do this; I prefer a manifest) and then the other task non-elevated. If you refuse to do that for whatever reason then take a look at the blog post and CodePlex project I link to from my blog post on this: http://www.gregcons.com/KateBlog/NonElevatedFromElevatedManagedThisTime.aspx

A: Alternatively, you could use the Windows API CreateProcessAsUser, that seems to do the job.

A: Very good question. The answers I found that ostensibly work are all a bit messy; the most elegant overall is the EXE wrapper.
Have a look at this article: http://www.codeproject.com/KB/vista-security/RunNonElevated.aspx. It describes a method by which you can obtain a native hook to one of the shell windows, which run non-elevated, and ask the shell to start your code for you. Native hooks in C# require very high CAS permissions; to get these permissions, your installer must be strongly named and signed, and the code must demand or assert SecurityPermission with SecurityPermissionFlag.UnmanagedCode.
The ProcessStartInfo class of the .NET Framework also contains a UseShellExecute Boolean property that, when set, tells Process.Start() to give this call to the shell rather than starting the process directly from the current application domain. I don't know if this will do that you need, but it's definitely much easier to try; you just use the ProcessStartInfo overload of Process.Start(), with a declared ProcessStartInfo having the flag set.
Remember that you cannot tell the shell to start an EXE as a user other than the currently logged-in user (UserName and Password must not be set on the ProcessStartInfo). You must also specify the path to the EXE using the WorkingDirectory property.


text:
Q: Nested email distribution groups not receiving mail to a particular DL in Exchange 2010 We have a distribution list (called "MasterDL", for example) that has sub-DLs inside it, as well as normal personal user email accounts alongside those nested DLs. For some reason, only the individual accounts are receiving any mail sent to MasterDL. Any members inside the sub-DLs do not receive anything sent to MasterDL in their inbox.
The server is Exchange 2010. The client being used is Outlook 2010.
How might this be occurring?
EDIT: It should be worth noting that the way the email is sent is through a VB/.NET SharePoint 2010 solution with the following relevant (pseudo)code:
System.Net.Mail.SmtpClient s;
System.Net.Mail.MailMessage m;
s.Port = 25;
s.Host = *our exchange server name*;
s.Send(m);


text:
Q: Layout depends on "resize direction" I'm having certain problem with my responsive layout. Lets say I have some intermediate width version (supposedly for phone landscape view), if page is loaded in this mode everything is layed out as desired/designed. And if user switches to portrait mode, portrait mode also looks good (with all responsive stuff applied correctly and all). However when switching from portrait to landscape, landscape layout gets somewhat messed up. Refreshing the page fixes everything. Same can be reproduce by simply scaling browser window down and then up. So this basically gives non-deterministic layout with regards to page width. This seems to be only present on webkit browsers. So this seems like a browser bug... Still considering the prevalence of webkit, I wonder maybe there is something that can be done about it? Anyone has encountered similar problems maybe and if so how did you solve them?

A: So after digging for whole day and trying various things, like additional markup to contain layout errors, I managed to implement a solution. Namely force redraw on resize, code used to force redraw (found somewhere on the net, maybe even SO; page here is here is body element):
document.getElementById('page').style.display='none';
document.getElementById('page').offsetHeight;
document.getElementById('page').style.display='block';

As this was needed only for orientation change from mobile portrait to landscape, it was natural to assume that window orientationchange event would work, but WebKit however does not take creative layout lightly, and when forcing redraw on orientation change it instead finds third way of laying out content... So I had to bind redraw on window resize event, of course to prevent huge performance hit checks are used to only redraw page when size changed from mobile/portrait width to tablet/landscape width.


text:
Q: How to change mainwindow's color to a specific color in pyqt/pyside? I want a light blue color in my application, precicely #99ccff in html color codes. In my application, I have:
palette = QtGui.QPalette()
palette.setColor(QtGui.QPalette.Background, QtCore.Qt.blue)
self.setPalette(palette)

Althought that changes the color to blue, it is not the type of blue that I want.

A: Use:
palette.setColor(QtGui.QPalette.Background, QColor("#99ccff"))


text:
Q: Using Url Parameters in Rewrite Rule Well, I have tried to create a temporary redirect with wildcards:
http://www.example.com/index.php?topic=1578.0 to http://www.example.com/demo/showthread.php/1578
This is my htaccess:
RewriteEngine on
RewriteBase /

# Rules for topics:
RewriteRule ^index.php\?topic=([0-9\.0]+)$ /demo/showthread.php/$1

# Rule for homepage
RewriteRule ^index.php$ /demo/forum.php

My problem is with the rules for topics. Simply it does not redirect. Can you guide me the right direction?

A: A Query String Cannot be Matched Directly in the RewriteRule.
Use this instead:
RewriteCond %{QUERY_STRING} topic=([^&\s]+)
RewriteRule ^index.php /demo/showthread.php/%1? [L,R]


text:
Q: XYPointerAnnotation in TimeSeries JFreeChart I'm trying to implement XYPointerAnnotation to TimeSeries chart. However I don't know, how does chart finds my y values to plot. Code:
final TimeSeries series = new TimeSeries("asdfas");
Hour hour = new Hour();
series.add(2,hour), 123);
TimeSeriesCollection collection = new TimeSeriesCollection();
collection.addSeries(series);
double temp = Double.parseDouble(
    series1.getTimePeriod(series1.getItemCount()-1).toString());
XYPointerAnnotation pointer1 = new XYPointerAnnotation(
    series1.getValue(series1.getItemCount() - 1).toString(), temp, 00.0);
JFreeChart chart = ChartFactory.createTimeSeriesChart(
    "1", "2", "3", collection, true, true, false);

How can I parse y values from TimeSeries to the XYPointerAnnotation?

A: Given a TimeSeries,
TimeSeries series = new TimeSeries("Data");

find the item of interest,
TimeSeriesDataItem item = series.getDataItem(series.getItemCount() - 1);

create an annotation based on the period and value,
double x = item.getPeriod().getFirstMillisecond();
double y = item.getValue().doubleValue();
XYPointerAnnotation a = new XYPointerAnnotation("Bam!", x, y, 5 * Math.PI / 8);

and add it to the plot,
XYPlot plot = (XYPlot) chart.getPlot();
plot.addAnnotation(a);


text:
Q: Vuetify v-dialog to stop playing video on close I have a playlist that plays a combo of audio and video files. For the video I use a v-dialog to to play an embedded Youtube or Vimeo player. What I would like to do is when I close the v-dialog for the video the video stops playing. Is there a simple way to force the video to stop playing? Currently the dialog closes but the video sound is still playing in the background?
  <v-list>
    <v-list-item
      v-for="media in media"
      :key="media.id"
      class="mb-2"
    >
      <v-list-item-content
        class="pa-4"
      >
        <v-list-item-title
          class="title"
          v-text="media.title"
        />
      </v-list-item-content>

      <v-list-item-action>
        <div>
          <v-btn
            icon
            @click="pause"
          >
            <v-icon>pause</v-icon>
          </v-btn>
          <v-btn
            v-else
            icon
            @click="play(media)"
          >
            <v-icon>play_arrow</v-icon>
          </v-btn>
        </div>
        <div v-else>
          <v-dialog
            v-model="media.show"
            persistent
            width="800px"
            :retain-focus="false"
          >
            <template v-slot:activator="{ on, attrs }">
              <v-btn
                icon
                v-bind="attrs"
                v-on="on"
              >
                <v-icon>mdi-open-in-new</v-icon>
              </v-btn>
            </template>
            <v-card>
              <Video
                :video-url="media.url"
              />
            </v-card>
            <v-card-actions>
              <v-spacer />
              <v-btn
                color="primary"
                text
                @click="media.show = false"
              >
                Close
              </v-btn>
            </v-card-actions>
          </v-dialog>
        </div>
      </v-list-item-action>
    </v-list-item>
  </v-list>

.. and below I have a media array with a combo of audio and video files
media: [
  {
    id: 0,
    title: 'Audio 1',
    url: 'https://mcdn.podbean.com/abc.mp3',
  },
  {
    id: 1,
    title: 'Video 1',
    show: false,
    url: 'https://vimeo.com/347119375'
  },
  {
    id: 2,
    title: 'Audio 2',
    url: url: 'https://mcdn.podbean.com/edf.mp3',
  },
  {
    id: 3,
    title: 'Audio 3',
    url: 'url: 'https://mcdn.podbean.com/ghi.mp3'
  },
  {
    id: 4,
    title: 'Video 2',
    show: false,
    url: 'https://youtu.be/LtpGLNRlwA0'
  }
],

A: your dialog needs a v-if as well, like this:
<v-dialog
  v-model="media.show"
  v-if="media.show" <-------
  persistent
  width="800px"
  :retain-focus="false"
>

v-if removes the element from your DOM if its false.


text:
Q: What is the correct way of integrating Jquery Image Zoom Plugin with angular js? I have made a directive to integrate elevate zoom plugin
.directive('ngElevateZoom', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      element.attr('data-zoom-image',attrs.zoomImage);
      $(element).elevateZoom();
    }
  };
});

and the html code is

The plugin is working fine in this page but when i navigate to other pages the plugin is still initialized and causing some problems. Can you provide me some suggestion how to remove this plugin from other pages or some solution regarding this usage of plugin.I have also attached screen shot of other pages after this plugin has been initialized.

A: ya it can be solved with destroying the instantiated object on destroy of your directive scope like given below example.
.directive('ngElevateZoom', function() {
  return {
    restrict: 'A',
    scope:{}
    link: function(scope, element, attrs) {
      element.attr('data-zoom-image',attrs.zoomImage);
      $(element).elevateZoom();
      // destroy your objects
      scope.$on('$destroy', function() {
           $('.zoomContainer').remove();
      });
    }
  };
});


text:
Q: It is not the case, however, that the XXX can do LLL There is a phrase that from an article:

It is not the case, however, that XXX can always be constructed using
  LLL.

Can I interpret as: XXX can always be constructed using LLL; or XXX can't always be constructed using LLL?

A: Try to break down the sentence into two parts to make it simpler:

It is not the case, however,

and

That XXX can always be constructed using LLL

Sentence 2 says that XXX can always be constructed using LLL and sentence 1 tells you that this is not always the case.
So your second interpretation is correct: XXX can't always be constructed using LLL.


text:
Q: How to display a dropdown options when clicking in a button? I need to display the dropdown options of a select when I click on a button.
I tried with the ref and focus or click but it's not working.

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App() {
  const [value, setValue] = React.useState(false);
  const selectRef = React.useRef();
  const handleClick = () => {
    // selectRef.current.focus();
    selectRef.current.click();
  };
  return (

      <button onClick={handleClick}>click me !</button>
      <select
        open
        ref={selectRef}
        value={value ? "activate" : "deactivate"}
        onChange={e => setValue(e.target.value === "activate")}
      >
        <option value="activate">Activate</option>
        <option value="deactivate">Deactivate</option>
      </select>

  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

I need when I click on the button the select show me the dropdown options

A: I recommend you to see the below link. I think that's what which you are looking for:
https://medium.com/@wwayne_me/how-to-manually-open-select-in-react-1169967eb33b
In summary it talks about an attribute named size which with setting it to non-zero value you can set the select open and with setting it to zero it will be closed.
So your code would be like this:
const handleClick = () => {
    selectRef.size=10;// optional number based on you
};

Try it and let me know if it works out.

A: This is one way of doing it:
See if that works for you.

function App() {

  const [openDrop,setOpenDrop] = React.useState(false);

  function toggleDrop() {
    setOpenDrop((prevState)=>!prevState);
  }

  return(
    <React.Fragment>
      <button onClick={toggleDrop}>Drop</button>

        App
        {openDrop && <Dropdown/>}

    </React.Fragment>
  );
}

function Dropdown() {

  function doSomething() {
    console.log('Let me handle this...');
  }

  return(

Item 1

Item 2

  );
}

ReactDOM.render(<App/>, document.getElementById('root'));
.main {
  background-color: lightblue;
}

li {
  cursor: pointer;
}


text:
Q: Type information of a proc() cannot be inferred if not passed into spawn() This compiles:
use std::num::pow;

pub fn main() {
    let (tx, rx): (Sender<u64>, Receiver<u64>) = channel();
    let square_tx = tx.clone();

    let square = proc() {
        let mut x = 1u;
        loop {
            square_tx.send(pow(2u64, x));
            x += 1;
        }
    };

    let printer = proc() {
        loop { println!("Received: {}", rx.recv()); }
    };

    spawn(square);
    spawn(printer);
}

But if I comment out spawn(square), the following error is raised:
error: unable to infer enough type information about `_`; type annotations required
let square = proc() {
                    ^

What is special about spawn() such that the type information of a proc() cannot be inferred without spawning?

A: spawn takes a proc() i.e. a procedure with no arguments and return value (), so the compiler can infer that square must have that type for the program to be valid.
The last expression in the proc is loop {}, without a break or return, so the compiler can see that the closure never returns properly. That is, it can pretend to have a return value of any type. Since the return type is unrestricted, the compiler has no way to tell which one is wanted and so complains.
It is possible to see similar behaviour with just a plain loop {}.
fn main() {
    let x = loop {};

    // code never reaches here, but these provide type inference hints
    // let y: int = x;
    // let y: () = x;
    // let y: Vec<String> = x;
}

<anon>:2:9: 2:10 error: unable to infer enough type information about `_`; type annotations required
<anon>:2     let x = loop {};
                 ^

playpen
(The same thing happens with anything that the compiler can tell doesn't let control flow continue, e.g. let x = panic!();, let x = return;.)
Uncommenting one of the y lines will let the program compile.


text:
Q: Only use certain fields from json in nuxt app By using asyncdata and axios I am grabbing a json object from a database called Knack.
Working great however the whole response is huge and in some pages I'm only using say 10 fields from sometimes 50+.
So I'm grabbing records from knack and then using v-for to loop through and output 10 of the 50+ fields from say 200 records.
By looking in console I can see the whole json object.
Is there a way to get the json object as I am and rather than returning it all, loop through and create a smaller object with the fields I need and returning that to then do a v-for in my template? Basically resulting in only the required fields being visible in console and to the public?
Thanks so much if someone can help with a code sample.

A: You can do it this way.
Sample data model
 data() {
  return {
    // Required fields to filter data
    requiredFields: ["name", "phone", "email"],
    fields: {
      name: "Wade Mckenzie",
      phone: "1-278-483-8300",
      email: "ac.mattis.velit@magnisdisparturient.net",
      address: "971-2324 Id, Av.",
      list: 7,
      country: "Australia",
      postalZip: "422625",
      region: "Campania",
      text: "malesuada augue ut lacus. Nulla tincidunt, neque vitae semper egestas,",
      numberrange: 5,
      currency: "$9.91",
      alphanumeric: "TXQ00DEL5RP",
   },
  };
 }

Computed prop
computed: {
  filteredData() {

    // Create an empty object
    let requiredData = {};

    // Loop over the entries
    for (const [key, value] of Object.entries(this.data)) {

      // Check if the property is a required field
      if (this.requiredFields.includes(key)) {
        requiredData[key] = value;
      }
    }

   return requiredData;
  },
}

Template

  {{ name }}: {{ value }}

You can check out the working example.

A: You can do that in a computed property.
computed(){
    getCustomObject(){

        let customObject = {};
        for(let property in yourJsonObject){
            if(property == 'the field you want'){
                customObject[`${property}`] = yourJsonObject[property]
            }
        }

        return customObject;
    }
}

In this way you can get specific fields that you want. But you will have to specify them by placing || in the if statement.
In template you can simply render it like this: -

    //Render data...

Or if you just want a specific number of fields like 10 fields from 50, you can do it like this: -
computed(){
    getCustomObject(){

        let customObject = {};
        Object.entries(yourJsonObject).forEach(([key,value],index) => {
            if(index<10){
              customObject[`${key}`] = value;
            }
        })

        return customObject;
    }
}


text:
Q: IOS Add observer for delegate function (like ) scrollViewDidEndDecelerating: Do you know how to add an observer (or a notification) to a standard delegate method call ? (I know this is a little weird/ not what observers were intended for)
I'm ultimately trying to catch the page change of a scrollview in a uiscrollview category method.
I can observe the content offset of a scrollview like this
[self addObserver:self forKeyPath:@"contentOffset" options:(NSKeyValueObservingOptionNew) context:NULL];
,but rather than being notified when the contentOffset is changed, I'd prefer to be notified when scrolling has ended or deceleration will begin.
I'm working on some advanced functionality for scrollviews (meaning I already know I can catch delegate call by just assigning a delegate)
any ideas ?

A: If you really need a notification for some reason, why not implement the delegate methods for which you want to be notified and fire off your own notifications from them?


text:
Q: How can I find the full file path given a library name like libfoo.so.1? Without implementing a linker or using ldd, how can I find the full path to a library? Is there a standard library available for that on Linux? (POSIX maybe?)
Using ldd and grep on a file that is knowingly using libGL.so.1, it looks like:
$ ldd /usr/bin/glxinfo | grep libGL
libGL.so.1 => /usr/lib/libGL.so.1 (0x00007f34ff796000)

Given a library name like libGL.so.1, how can I find the full path /usr/lib/libGL.so.1?. Preferably accepting an option for finding 32-bit and 64-bit libraries. If no library does that, does a program exist to do this? Something like find-library-path libGL.so.1. The locate libGL.so.1 command does not count.
I don't want to actually load the library using dlopen or something if it executes code from that library.

A: Use ldconfig which is the tool that manages link space.
The -p flag lets you browse all available linkable libraries.

A: If you don't mind actually loading the library and using some nonstandard but widely-available functions, calling dladdr on any symbol from the library will return information containing the full pathname that was loaded.

A: Expanding on Honky Tonk's answer, the command echo "$(ldconfig -p | grep libGL.so.1 | tr ' ' '\n' | grep /)" will give you the path alone.

A: For systems with GNU libc and Python the following is the closest I found. It uses LD_DEBUG (described in the man page of ld.so(8)).
LD_DEBUG=libs python3 -c "import ctypes; ctypes.CDLL('libssl.so.1.0.0')" 2>&1 | \
    grep -A 1000 "initialize program: python" | grep -A 3 "find library"

The output (for libssl.so.1.0.0) is the following:
 15370: find library=libssl.so.1.0.0 [0]; searching
 15370:  search cache=/etc/ld.so.cache
 15370:   trying file=/lib/x86_64-linux-gnu/libssl.so.1.0.0
 15370:
 15370: find library=libcrypto.so.1.0.0 [0]; searching
 15370:  search cache=/etc/ld.so.cache
 15370:   trying file=/lib/x86_64-linux-gnu/libcrypto.so.1.0.0
 15370:

A: I implemented such a script here:
#!/usr/bin/env python3

"""
Like `type` but for libs.
"""

import sys
import os
from argparse import ArgumentParser
from glob import glob

def parse_ld_conf_file(fn):
    paths = []
    for l in open(fn).read().splitlines():
        l = l.strip()
        if not l:
            continue
        if l.startswith("#"):
            continue
        if l.startswith("include "):
            for sub_fn in glob(l[len("include "):]):
                paths.extend(parse_ld_conf_file(sub_fn))
            continue
        paths.append(l)
    return paths

def get_ld_paths():
    # To be very correct, see man-page of ld.so.
    # And here: http://unix.stackexchange.com/questions/354295/what-is-the-default-value-of-ld-library-path/354296
    # Short version, not specific to an executable, in this order:
    # - LD_LIBRARY_PATH
    # - /etc/ld.so.cache (instead we will parse /etc/ld.so.conf)
    # - /lib, /usr/lib (or maybe /lib64, /usr/lib64)
    paths = []
    if "LD_LIBRARY_PATH" in os.environ:
        paths.extend(os.environ["LD_LIBRARY_PATH"].split(":"))
    paths.extend(parse_ld_conf_file("/etc/ld.so.conf"))
    paths.extend(["/lib", "/usr/lib", "/lib64", "/usr/lib64"])
    return paths

def main():
    arg_parser = ArgumentParser()
    arg_parser.add_argument("lib")
    args = arg_parser.parse_args()

    paths = get_ld_paths()
    for p in paths:
        fn = "%s/%s" % (p, args.lib)
        if os.path.exists(fn):
            print(fn)
            return

    print("Did not found %r in %r." % (args.lib, paths), file=sys.stderr)
    sys.exit(1)

if __name__ == "__main__":
    main()


text:
Q: Mongoose nested alias I have the following field in the MongoDB and I can NOT change the schema of DB
phoneNumbers: [
    { phoneNumber: '15141234567', type: 'WORK' },
    { phoneNumber: '15142233667', type: 'CELL' },
    { phoneNumber: '1517654321', type: 'HOME' }
  ],

Schema is
const schemaPhoneNumber = new Schema({
  type: {
    type: String,
    enum: ["WORK", "CELL", "HOME"],
    alias: "phoneType",  /////////////////////////////////// I have alias the field name
  },
  phoneNumber: String,
});

const GraphQLPhoneType = new GraphQLEnumType({
  name: "PhoneType",
  values: {
    WORK: {
      value: "WORK",
    },
    CELL: {
      value: "CELL",
    },
    HOME: {
      value: "HOME",
    },
  },
});
const GraphQLPhoneNumber = new GraphQLObjectType({
  name: "PhoneNumber",
  fields: () => ({
    phoneType: { ////////////////////////////////////// it is not finding by this name
      type: GraphQLNonNull(GraphQLPhoneType),
    },
    phoneNumber: {
      type: GraphQLNonNull(GraphQLString),
    },
  }),
});

Problem: when I run a query, it is showing the "phoneNumber" but the "phoneType" return null.
If I change "phoneType" to "type", the query shows the correct type (WORK, CELL, etc.), but I have to use "phoneType" in graphQL and "type" is DB.
what is the issue, when I have changed by an alias, that it is not available in fields of "GraphQLPhoneNumber", is it a problem of nested JSON or shall I call alias in different way?

A: The alias is correct, the issue was I did not call schemaPhoneNumber when I create the upper-level schema.
phoneNumbers: [schemaPhoneNumber],


text:
Q: R - Importing a text file which includes information in header lines above the main data table I'd like to import a text file which contains a table of results with two 'header' lines of text above it. The contents of the header lines needs to be included as extra columns in the resulting data.frame.
In the following example text file, the Region and Month lines are the header lines, and the remainder of the file is the results table.
Region  South Africa
Month   July
Sepal.Length    Sepal.Width Petal.Length    Petal.Width Species
1   5.1 3.5 1.4 0.2 setosa
2   4.9 3   1.4 0.2 setosa
3   4.7 3.2 1.3 0.2 setosa

needs to become a data.frame which includes columns for Region and Month:
wanted.df<-structure(list(Sepal.Length = c(1, 2, 3), Sepal.Width = c(5.1,
4.9, 4.7), Petal.Length = c(3.5, 3, 3.2), Petal.Width = c(1.4,
1.4, 1.3), Species = c(0.2, 0.2, 0.2), Region = c("South Africa",
"South Africa", "South Africa"), Month = c("July", "July", "July"
)), row.names = c(NA, -3L), class = c("spec_tbl_df", "tbl_df",
"tbl", "data.frame"))

I've managed to do it by creating two data.frames, one containing the header info, the second containing the result table and then merging them, but this seems to me a bit ungainly:
#Create data frame from first two lines of text (the header)
header <- scan('example.txt', nlines = 2, what = character(),sep = "\n")
header.df<-data.frame((sapply(header,function(x){str_split(x, "\t")})),stringsAsFactors=FALSE)
colnames(header.df) <- as.character(header.df[1,])
header.df<-header.df[-1,]

#Create data frame from first remainder of the file which contains the results table
results.df<-read_tsv('example.txt',col_names = T,skip=2)

#helper column added to both data frames for merging
results.df$helper.col<- "match"
header.df$helper.col<-"match"
df.example<-inner_join(results.df,header.df, by = "helper.col", copy = FALSE)
wanted.df<-select(df.example,-helper.col)

Is there a more elegant way?

A: Assuming @H 1's comment is correct that it is a tab-separated file. We can do
df1 <- read.table('example.txt', nrows = 2, sep = "\t")
df2 <- data.frame(matrix(df1$V2, ncol = nrow(df1), dimnames = list(NULL, df1$V1)))
df3 <- read.table(text = 'example.txt', skip = 2, header = TRUE)
cbind(df3, df2)

#  Sepal.Length Sepal.Width Petal.Length Petal.Width Species       Region Month
#1          5.1         3.5          1.4         0.2  setosa South Africa  July
#2          4.9         3.0          1.4         0.2  setosa South Africa  July
#3          4.7         3.2          1.3         0.2  setosa South Africa  July

A: I would do it in this way:
header <- readLines('file.txt', n = 2)
header <- stringi::stri_split_regex(header, '\\W+', n = 2)

dat <- read.table('file.txt', skip = 2, stringsAsFactors = FALSE)
for(i in header){ dat[ i[1] ] <- i[2] }

# > dat
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species       Region Month
# 1          5.1         3.5          1.4         0.2  setosa South Africa  July
# 2          4.9         3.0          1.4         0.2  setosa South Africa  July
# 3          4.7         3.2          1.3         0.2  setosa South Africa  July


text:
Q: same height Bootstrap columns with vertical align I am using Bootstrap 3, I need to have same height of the columns with vertical align able in the content of the columns

     vertical align top

     vertical align middle

     vertical align bottom

Please check here https://jsfiddle.net/4d2m74nc/4/

A: This is achievable but will take away from some of bootstrap's built in functionality.  Mainly, the media queries for mobile rendering of the grid system.
The best way to achieve this is probably with the flexbox approach.  Demo.

         vertical align top

           vertical align middle

         vertical align bottom

CSS
.row-eq-height {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display:         flex;
}
.vcenter{
  display:flex;
  flex-direction:column;
  justify-content:center;
  }
.vbottom{
  display:flex;
  flex-direction:column;
  justify-content:flex-end;
}

Second way is to use absolute positioning for the vertical alignment and flexbox for matching heights.
Check out the demo.

         vertical align top

           vertical align middle

         vertical align bottom

CSS
.row-eq-height {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display:         flex;
}
.vcenter {
  position: absolute;
  top: 50%;
}

Another option would be to use JavaScript to fix the heights and vertical align for you.  You could use matchHeight.js.
It's fairly simple to use.  You just wrap all of your column content that you want to match in height with another
 with the class .box

            Content

            Content

            Content

and then instantiate it on document load in your JavaScript file or  tags after your JQuery link.
$('.box').matchHeight();
Sticking with JavaScript for the vertical align you could add .vcenter to the .box element you want vertically aligned and do something like:
var height = $('.vcenter').height();
$('.vcenter').css('margin-top', (height/2));
$('.vcenter').css('margin-bottom', -(height/2));

var $window = $(window);
var windowsize = $window.width();
function checkWidth(){
  if (windowsize < 440) {
    $('.vcenter').removeAttr("style");
  }
}

 $(window).resize(checkWidth);

Which calculates the height of the .box and then divides by 2 to determine a top and bottom margin for the content.  We then determine the width of the window and on resize we remove the margins.  This part is untested but I believe will work in theory.  Here's a demo of matchHeight.js.  And here's a useful blog on column height matching in bootstrap.
The last two approaches to vertical alignment are poor but should work.

A:

        vertical align top

        vertical align middle

        vertical align bottom

CSS that support the boxes the flex item properties it just give for your understanding
.flex-container {
    display: -webkit-flex;
    display: flex;
}

.flex-item {
    border: 1px solid #000;
    padding: 20px;
}


text:
Q: Tango with Django : URLconf defined in tango_with_django_project.urls. Page not found Started learning Django a few days ago, came across this book "Tango with django" and started following it. But I am stuck here..might be a silly error with the pattern matching..
When I click a category, the relevant Category pages should be shown snapshot
But the following error is shown : Error image
/urls.py
from django.conf.urls import url
from django.contrib import admin

from django.conf.urls import url,include
from rango import views
from django.conf.urls.static import static

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^rango/', include('rango.urls')),

]

rango/urls.py
from django.conf.urls import url
from rango import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^about/', views.about, name='about'),
url(r'^add_category/$', views.add_category, name='add_category'),
url(r'^category/(?P<category_name_slug>[\w\-]+)/', views.show_category, name='show_category'),
url(r'^category/(?P<category_name_slug>[\w\-]+)/add_page/', views.add_page, name='add_page'),
]

views.py
   from django.http import HttpResponse
    from django.template import RequestContext
    from django.shortcuts import render_to_response
    from rango.models import Category
    from rango.models import Page
    from rango.forms import CategoryForm
    from django.shortcuts import render

    def show_category(request, category_name_slug):
        context_dict = {}
        try:

            category = Category.objects.get(slug=category_name_slug)

            pages = Page.objects.filter(category=category)

            context_dict['pages'] = pages

            context_dict['category'] = category
        except Category.DoesNotExist:

            context_dict['category'] = None
            context_dict['pages'] = None

        return render(request, 'rango/category.html', context_dict)

index view
   def index(request):
    context = RequestContext(request)

    category_list = Category.objects.order_by('-likes')[:5]
    page_list = Page.objects.all()

    context_dict = {'categories':category_list, 'pages': page_list}

    for category in category_list:
        category.url = category.name.replace(' ', '_')

    return render_to_response('rango/index.html', context_dict, context)

models.py
from django.db import models
from django.template.defaultfilters import slugify

class Category(models.Model):
    name = models.CharField(max_length=128, unique=True)
    views = models.IntegerField(default=0)
    likes = models.IntegerField(default=0)
    slug = models.SlugField(unique=True)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Category, self).save(*args, **kwargs)

    class Meta:
        verbose_name_plural = 'Categories'

    def __unicode__(self):
        return self.name

    def __str__(self):
        return self.name
class Page(models.Model):
    category = models.ForeignKey(Category)
    title = models.CharField(max_length=128)
    url = models.URLField()
    views = models.IntegerField(default=0)
    def __unicode__(self):
        return self.title

    def __str__(self):
        return self.title

category.html
<!DOCTYPE html>

 <title>Rango</title>

 {% if category %}

{{ category.name }}

 {% if pages %}

 {% for page in pages %}

{{ page.title }}

 {% endfor %}

   Would you like to add more
            pages
            ?
 {% else %}
 No pages currently in category.
 {% endif %}
 {% else %}
 The specified category does not exist!
 {% endif %}

index.html
<!DOCTYPE html>
{% load staticfiles %}

<title>Rango</title>

Rango says...hello world!

Most viewed Categories!

{% if categories %}

{% for category in categories %}

{{ category.name }}

{% endfor %}

{% else %}
There are no categories present.
{% endif %}
Add a New Category

Most Viewed Pages!

{% if pages %}

    {% for page in pages %}

{{ page.title }}

    {% endfor %}

{% else %}
There are no pages present!
{% endif %}
About

A: Change this line in your index.html,
{{ category.name }}

to,
{{ category.name }}


text:
Q: Inserting at arbitrary position in list in Scheme I have a list with me, for example: (B D F)
I want to insert an element at an arbitrary position in the list. For example, if the element is A, I want to insert it before B and if the element C, I want to insert it after B but before D.
Is there any way to insert elements at an arbitrary position in a list in Scheme?

A: It's easy to implement a function for this:
(define (insert-at new k lst)
  (cond ((null? lst)
         (list new))
        ((zero? k)
         (cons new lst))
        (else
         (cons (car lst)
               (insert-at new (sub1 k) (cdr lst))))))

For example:
(insert-at 'B 1 '(A))
=> '(A B)

(insert-at 'A 0 '(B D F))
=> '(A B D F)

(insert-at 'C 2 '(A B D F))
=> '(A B C D F)


text:
Q: Element width of a dropdown not available at document.ready I'm trying to get the width of a dropdown list and set the width of a div accordingly.  The problem is that when I try to get the width of the dropdown it comes up as -2.
$(document).ready(function() {
  var ddWidth = $("#drdTypes").width();
  alert(ddWidth);
}

<%=Html.DropDownList("drdTypes", new SelectList(Model.TypeList, "text", "text"))%>

If I run that same code in a button I get a reasonable value.  I thought that the DOM was available when document.ready fires.

A: Try
$('#drdTypes').load(function () {
    console.log($(this).width());
});

Basically wait for the drop down to load and log the width in the console. Make sure it gets put inside the ready callback.


text:
Q: Zapi API - Getting error Expecting claim 'qsh' to have value I just try to fetch general information from zapi api, but getting error
Expecting claim 'qsh' to have value '7f0d00c2c77e4af27f336c87906459429d1074bd6eaabb81249e1042d4b84374' but instead it has the value '1c9e9df281a969f497d78c7636abd8a20b33531a960e5bd92da0c725e9175de9'
API LINK : https://prod-api.zephyr4jiracloud.com/connect/public/rest/api/1.0/config/generalinformation
can anyone help me please.

A: I can definitely help you with this. You need to generate the JWT token in the right way.
package com.thed.zephyr.cloud.rest.client.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.thed.zephyr.cloud.rest.ZFJCloudRestClient;
import com.thed.zephyr.cloud.rest.client.JwtGenerator;

public class JWTGenerator {

                public static void main(String[] args) throws URISyntaxException, IllegalStateException, IOException {
                                String zephyrBaseUrl = "https://prod-api.zephyr4jiracloud.com/connect";

                                String accessKey = "TYPE YOUR ACCESS KEY-GET IT FROM ZEPHYR";
                                String secretKey = "TYPE YOUR SECRET KEY-GET IT FROM ZEPHYR";
                                String userName = "TYPE YOUR USER - GET IT FROM ZEPHYR/JIRA";

                                ZFJCloudRestClient client = ZFJCloudRestClient.restBuilder(zephyrBaseUrl, accessKey, secretKey, userName).build();
                                JwtGenerator jwtGenerator = client.getJwtGenerator();

                                String createCycleUri = zephyrBaseUrl + "/public/rest/api/1.0/cycles/search?versionId=<TYPE YOUR VERSION ID HERE>&projectId=<TYPE YOUR PROJECT ID HERE>";

                                URI uri = new URI(createCycleUri);
                                int expirationInSec = 360;
                                String jwt = jwtGenerator.generateJWT("GET", uri, expirationInSec);
                                //String jwt = jwtGenerator.generateJWT("PUT", uri, expirationInSec);
                                //String jwt = jwtGenerator.generateJWT("POST", uri, expirationInSec);

                                System.out.println("FINAL API : " +uri.toString());
                                System.out.println("JWT Token : " +jwt);

                }
 }

Also clone this repository: https://github.com/zephyrdeveloper/zfjcloud-rest-api which will give you all methods where respective encodings are there. You can build a Maven project to have these dependencies directly imported.
*I also spent multiple days to figure it out, so be patient and it's only the time till you generate right JWT.

A: The query string parameters must be sorted in alphabetical order, this will resolve the issue.
Please see this link for reference:
https://developer.atlassian.com/cloud/bitbucket/query-string-hash/