text:
Q: How to return rows as much as column in table MySql I have one table there are many records. When I select the record by id then I need the result in the row as per column.
Table
ID         field1             field2
1          name1              picture1

Output like:-
ID         field1
1          name1
1          picture1

A: You can do this with a UNION:
(SELECT ID, field1 FROM yourtable)
UNION
(SELECT ID, field2 FROM yourtable)
ORDER BY ID

If you have more than two fields, you would extend the sequence of UNION/SELECT to cover them all. If you want to only get data for a specific ID value (e.g. 1), add a WHERE clause to each SELECT:
(SELECT ID, field1 FROM yourtable WHERE ID=1)
UNION
(SELECT ID, field2 FROM yourtable WHERE ID=1)
ORDER BY ID


text:
Q: Create a generic linked list class to create a chain of objects Please explain what this task is about?
"Create a generic linked list class that enables us to create a chain objects of different types."
Do we need to create a class of type linkedlist and implement list interface?
class LinkedList<T>:IList<T>
{
   //implement interface methods here?
}

Please give example.

A: A linked list is a special list whereby each element (or per-element container object) in the list has a direct reference (the "link") to the next item in the list. This type of list is not implemented using an array.
A singly-linked list usually only has a link to the next item with the final item being null to indicate the end of the list.
A doubly-linked list has a link to both the next and previous items with nulls to indicate each end of the list.
The advantage with a linked list is that inserts and removals are exceedingly quick. Iterating over the entire list also has good performance, but non-linear searching can be slow.
Typically an implementation of a linked list should implement the IEnumerable<T> interface. Implementing IList<T> would promote the use of inefficient linear searches.
The .NET implementation of a linked list has the following declaration (minus some irrelevant cruft).
LinkedList<T> : ICollection<T>, IEnumerable<T>, ICollection, IEnumerable

As with the IList<T> interface I don't see why the ICollection & ICollection<T> interfaces have been implemented, but they have.
The element container object (that has the links) looks like this:
public sealed class LinkedListNode<T>
{
    public LinkedListNode<T> Next { get; }
    public LinkedListNode<T> Previous { get; }
    public T Value { get; set; }
}

How's that?

A: You need to create your own new Class of Generic Linked List. here is the complete solution. according to above comment.. Hope it helps..
class Program
{

    static void Main(string[] args)
    {
       // string linked List
        GenericsLinkedList<string> stringLinkedList = new GenericsLinkedList<string>(); //object 1
        string s1 = "Yes";
        string s2 = "No";
        string s3 = "True";
        string s4 = "False";
        stringLinkedList.AddHead(s1);
        stringLinkedList.AddHead(s2);
        stringLinkedList.AddHead(s3);
        stringLinkedList.AddHead(s4);
        //display List
        foreach (string str in stringLinkedList)
        {
            Console.WriteLine("----"+str);
        }

        //Integer LinkedList
        GenericsLinkedList<int> integerList = new GenericsLinkedList<int>();
        int n1 = 1;
        int n2 = 2;
        int n3 = 3;

        integerList.AddHead(n1);
        integerList.AddHead(n2);
        integerList.AddHead(n3);

        foreach (int Intger in integerList)
        {
            Console.WriteLine("----" + Intger);
        }

        Console.ReadKey();

    }
}

// Generic Linked List
class GenericsLinkedList<T>
{
    class LinkedlistNode
    {
        private LinkedlistNode next;
        private T item;

        public LinkedlistNode(T t)
        {
            next = null;
            item = t;

        }
        public LinkedlistNode Next
        {
            get
            {
                return next;
            }
            set
            {
                next = value;
            }
        }
        public T Item
        {
            get
            {
                return item;
            }
            set
            {
                item = value;
            }
        }
    }
   private LinkedlistNode head;
   public GenericsLinkedList()
   {
       head = null;
   }
   public void AddHead(T t)
   {
       LinkedlistNode node = new LinkedlistNode(t);
       node.Next = head;
       head = node;
   }
   public IEnumerator<T> GetEnumerator()
   {
       LinkedlistNode current = head;
       while(current != null)
       {
           yield return current.Item;
           current = current.Next;
       }

   }

}

A: namespace GenericLinkedList
{

// generic linked list node
public class GenericNode<T>
{
    public T data;
    public GenericNode<T> nextNode = null;

    public GenericNode(T data)
    {
        this.data = data;
    }
}

// generic linked list
public class GenericLinkedList<T>
{
    private GenericNode<T> head = null;

    public void Add(T newListItem)
    {
        if (head == null)
        {
            head = new GenericNode<T>(newListItem);
        }
        else
        {
            GenericNode<T> curr = head;
            while (curr.nextNode != null)
            {
                curr = curr.nextNode;
            }
            curr.nextNode = new GenericNode<T>(newListItem);
        }
    }

    public void DisplayNodes()
    {
        GenericNode<T> curr = head;
        while (curr != null)
        {
            System.Console.WriteLine(curr.data);
            curr = curr.nextNode;
        }
    }
}

class TestGenericLinkedList
{
    static void Main(string[] args)
    {
        GenericLinkedList<System.Object> gll = new GenericLinkedList<System.Object>();
        gll.Add(12);
        gll.Add("string");
        gll.Add(false);
        gll.DisplayNodes();
    }
    }
}
}

A: It can be silly since this code somehow eliminates the meaning of generic, however I think they mean this.
class Generic<T>
{
    public  T t;

}
static void Main(string[] args)
{
    Generic<object>[] genericarray = new Generic<object>[3];
    for (int i = 0; i < genericarray.Length; i++)
        genericarray[i] = new Generic<object>();
    int a = 0;
    double b = 0.515151513163;
    string c = "s.dçfslsfn";
    genericarray[0].t = a;
    genericarray[1].t = b;
    genericarray[2].t = c;
}

A: For a linked list, I wouldn't typically recommend implementing IList, since IList strongly implies constant-time access to any member of the list. I would recommend implementing ICollection, then adding additional methods that are integral to linked lists, such as PushFront, PopBack, etc. You might look at the MSDN documentation for the LinkedList<T> class for comparison (http://msdn.microsoft.com/en-us/library/he2s3bh7.aspx), though you should implement your class separately.

A: This should do it
http://msdn.microsoft.com/en-us/library/0x6a29h6.aspx
// type parameter T in angle brackets

public class GenericList
{
    // The nested class is also generic on T.
    private class Node
    {
        // T used in non-generic constructor.
        public Node(T t)
        {
            next = null;
            data = t;
        }
    private Node next;
    public Node Next
    {
        get { return next; }
        set { next = value; }
    }

    // T as private member data type.
    private T data;

    // T as return type of property.
    public T Data
    {
        get { return data; }
        set { data = value; }
    }
}

private Node head;

// constructor
public GenericList()
{
    head = null;
}

// T as method parameter type:
public void AddHead(T t)
{
    Node n = new Node(t);
    n.Next = head;
    head = n;
}

public IEnumerator<T> GetEnumerator()
{
    Node current = head;

    while (current != null)
    {
        yield return current.Data;
        current = current.Next;
    }
}

}

A:     static void Main()
    {
        var list = new LinkedList<object>();
        list.AddLast("My string");
        list.AddLast(1.5);
        list.AddLast(2);
        list.AddLast(true);

        var en = list.GetEnumerator();
        while (en.MoveNext())
            Console.WriteLine(en.Current);

        Console.ReadKey();
    }

A: More Functionalities with  following implementation
http://msdn.microsoft.com/en-us/library/0x6a29h6.aspx
 public class GenericList<T>
{
   private class Node
    {

        public Node(T t)
        {
            next = null;
            data = t;
        }

        private Node next;
        public Node Next
        {
            get { return next; }
            set { next = value; }
        }

        private T data;

        public T Data
        {
            get { return data; }
            set { data = value; }
        }
    }

    private Node head;
    private Node tail;
    private int count;

    public GenericList()
    {
        head = null;
        tail = null;
        count = 0;
    }

    public void AddHead(T t)
    {
        if (head == null)
            head = tail = new Node(t);
        else
        {
            Node n = new Node(t);
            n.Next = head;
            head = n;
        }
        count++;
    }

    public void AddTail(T t)
    {
        if(tail == null)
        {
            head = tail = new Node(t);
        }
        else
        {
            Node n = new Node(t);
            tail.Next = n;
            tail = n;

        }
        count++;
    }

    public void InsertAt(T t,int index)
    {
        if (index < 0 || index > count)
            throw new ArgumentOutOfRangeException();
        else if (index == 0)
            AddHead(t);
        else if (index == count)
            AddTail(t);
        else
        {
            Node currentNode = head;
            for (int i = 0; i < index - 1; i++)
            {
                currentNode = currentNode.Next;
            }
            Node newNode = new Node(t);
            newNode.Next = currentNode.Next;
            currentNode.Next = newNode;
        }
        count++;
    }

    public void Reverse()
    {
        if (head == null || head.Next == null)
            return;
        tail = head;
       Node previousNode = null;
       Node currentNode = head;
      Node nextNode = head.Next;
        while (currentNode != null)
        {
            currentNode.Next = previousNode;
            if (nextNode == null)
                break;
            previousNode = currentNode;
            currentNode = nextNode;
            nextNode = nextNode.Next;

        }

        head = currentNode;

    }

    public IEnumerator<T> GetEnumerator()
    {
        Node current = head;

        while (current != null)
        {
            yield return current.Data;
            current = current.Next;
        }
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Interpolate inside cuboid / plane that intersects a point I am trying to implement a trilinear interpolation algorithm for cuboids.
Please excuse my lack of math jargon, this is not my area!
The cuboids can be rotated in any dimension in 3D space. No two faces are guaranteed to face one another precisely or be exactly the same shape. The cuboids are always 'sane' - never twisted to the point where you could consider lines to be crossing, not flat, no two points are in the same position, etc.

(Please note that the eight points have different values - I've coloured the planes in this image simply so it's easier to see)
Let p be the point in 3D space I need to interpolate (p is guaranteed to be inside the cuboid). Let $a_1,b_1,c_1,d_1$ be four points on one face; and $a_2,b_2,c_2,d_2$ be their corresponding points on another face.
Let L be a value between 0 and 1, describing the proportional distance between two corresponding points (e.g. $a_1, a_2$).
I understand that my problem boils down to finding L, so that the plane $a_L,b_L,c_L,d_L$ intersects point p. From here interpolation is simple.
How do I find L?
Is there a simpler way to do this?


text:
Q: Navigating directly to the second tab in tab navigator I have a component mxml in which i have a save button, on click of the save button i need to display another component which will be in a tab navigator, for this I am using the view stack. My problem is, on click of save I need to display the second tab instead of the first tab, but defaultly the first tab will be displayed.
How could this be accomplished?
Thanks!
cheers,
Deena

A: TabNavigator and ViewStack have an attribute "selectedIndex" which you can set to 1.


text:
Q: Why is my styles not loaded in HEAD - Angular This makes my webpage to load without styles which stays for few seconds before the js loads the styles.

I added my css in the angular.json file

    "styles":
        [
            "./node_modules/bootstrap/dist/css/bootstrap.min.css",
            "src/styles.sass"
        ],
    "scripts":
        [
            "./node_modules/jquery/dist/jquery.min.js",
            "./node_modules/bootstrap/dist/js/bootstrap.min.js"
        ]

is it not supposed to be there?

A: Your styles are at the end of the document. nce all the assets in the document were loaded, the browser will load your styles. The browser renders your HTML code without any CSS because it doesn't have the styles yet.
Move the styles include to the <head>, this way, the styles will be loaded first.


text:
Q: An Encoding Issue? I think I have a URL encoding issue. I need to open a window using Javascript and pass a SQL Select query to it. So I have done this:
window.open('view_query.php?sql_query=' + query + '&db_name=' + db_name);

This has worked for me, but I have a query that breaks this:
SELECT a FROM table WHERE field like '%adhoc%'

Now when the new window opens and I print the query received from the URL GET variable it looks like this:
SELECT a FROM table WHERE field like '�hoc%'

Notice the bit %ad has turned into an unrecognised character! Why?
I have tried solving this with URL encoding but since I need the % symbol I can't use many URL encoders since they will turn this into something else?!
Thanks all for any help.

A: Encode your query using http://pl.php.net/urlencode. Then decode it using http://pl.php.net/urldecode (if needed, PHP should do this for you automatically)

A: The % character is used to encode characters in an URL using a character code. The sequence %ad means the character with the hexadecimal character code 0xAD, or decimal 173.
Use the encodeURIComponent function to escape values for the URL:
window.open('view_query.php?sql_query=' + encodeURIComponent(query) + '&db_name=' + encodeURIComponent(db_name));

Just to make sure that you (and anyone reading this) are aware of it, let me also point out the risks of sending SQL code via the browser. Anyone using the system could send anything as a query, including for example drop table.

A: This is because of url encoding - you need to call
window.open('view_query.php?sql_query='+encodeURICompoent(query)+'&db_name...);

and then on php side
$query = rawurldecode($_GET['sql_query']);


text:
Q: Mysql how to get all rows from a table that the a field not having the particular value..? I have a table which contains student_id, course_id and result. The table structure is as follows

I need to get course_id which the result is 0 and another condition is that the result may not be 1 for that course.
In that image the course_id 633 has both result 0 and 1. so that the particular course_id Do not get from that table.
Regards,
John

A: I hope this is what you are looking for:
SELECT student_id,course_id,SUM(CASE WHEN result=1 THEN 1 ELSE 0 END) as 0Count
FROM TableName
GROUP BY student_id,course_id
HAVING 0Count=0

SQL Fiddle
Explanation:
Query will returns students with result=0 and who do not have a result=1 for that course.
Sample Output:
student_id   course_id   result
3061         663         0
3061         663         1
3062         664         1
3063         665         0

The result will be:
STUDENT_ID   COURSE_ID       0COUNT
-----------------------------------
3063         664             0

A:     SELECT course_id FROM table_name WHERE result <> 1

edit: unused selections where kicked

A: Ah I see. I think you are looking for this code
SELECT course_id FROM table_name WHERE result = 0 AND result NOT LIKE "%1%";

Let me know how is it work for you.

A: Try this query:
SELECT DISTINCT t1.course_id
 FROM table_name t1
 WHERE t1.result = 0
   AND NOT EXISTS (
     SELECT 1
     FROM table_name t2
     WHERE t2.course_id = t1.course_id
     AND t2.result = 1);

A: Try this
SELECT *
FROM TABLE_NAME
WHERE course_id NOT IN
    (SELECT course_id
     FROM TABLE_NAME
     WHERE RESULT=0
       AND course_id IN
         (SELECT course_id
          FROM TABLE_NAME
          WHERE RESULT=1))


text:
Q: How to save .PBM image? I open a pgm file, convert it to numPy array and change all pixels to 0 or 1 (or 255, I don't know how to proceed yet).
How can I save it as .PBM using openCV?
Like:
P1
512 512
0 1 0 0 0 . .
0 0 0 1 0 . .
. . . . . . .
. . . . . . .
. . . . . . .

Thanks in advance!

A: vector<int> params;
params.push_back(CV_IMWRITE_PXM_BINARY);
params.push_back(0); // 1 for binary format, 0 for ascii format
imwrite("image.pbm", image, params); // the .pbm extension specifies the encoding format

A: Using OpenCV seems overkill. Just open a file and write the header and image data. Plain PBM is very inefficient. Consider Raw PBM (magic number P4) instead.
E.g. for Python 2.7:
with open('image.pbm', 'wb') as fd:
    fd.write("P4\n%i %i\n" % image.shape[::-1])
    numpy.packbits(image, axis=-1).tofile(fd)

For plain PBM:
with open('image.pbm', 'w') as fd:
    fd.write("P1\n%i %i\n" % image.shape[::-1])
    fd.write("\n".join(" ".join(str(i) for i in j) for j in image))

image is a 2D binary valued numpy array.


text:
Q: Replace and append part of a String - MySQL In my table I have a field "youtube" where the user can add a Youtube or Vimeo link. The Youtube links can be played directly, the Vimeo links which looks like:
https://vimeo.com/22614651XX

needs to be replaced by:
https://player.vimeo.com/video/22614651XX

Can this be done with SQL or should it be done in PHP? In PHP I found the substr() Function where I can split a string, but I have no clue how to deal with the numbers as they can vary in length...

A: thank you for your assistance :-)
UPDATE wp_awa_upload
SET youtube = REPLACE(youtube, 'https://vimeo.com/', 'https://player.vimeo.com/video/')
WHERE youtube like "%vimeo%"

does the trick :-)
Kind Regards,
Stefan


text:
Q: Difficulty reading from stdin I need to make my script usable for UNIX commands, in order to make it possible for example to process 2 input files at once with my script. This script works perfectly well with command line arguments:
newlist = []
def f1()
 ....
  return places
  return persons
  return unknown

def f2(input_file):

  volume_id = sys.argv[3]

  for line in input_data:

    if any(place+'</dfn>' in line.decode('utf-8') for place in places):
      line = line.replace('"person"', '"place"')
      line = line.replace('id="', 'id="'+volume_id)
    elif any(unk+'</dfn>' in line.decode('utf-8') for unk in unknown):
      line = line.replace('"person"', '"undefined"')
      line = line.replace('id="', 'id="'+volume_id)
    elif 'class="person"' in line.decode('utf-8') and '<dfn' not in line:
      line = line.replace('class="person"', '')
      line = line.replace('id="', 'id="'+volume_id)
    elif 'id="' in line:
      line = line.replace('id="', 'id="'+volume_id)

    newlist.append(line)

  return  newlist

def main():
  if len(sys.argv) < 4:
    print 'usage: ./myscript.py [file_in... file_out... volume_id]'
    sys.exit(1)

  else:

   filename = sys.argv[1]
   filename_out = sys.argv[2]

   tree = etree.parse(filename)
   extract(tree)

   input_file = open(filename, 'rU')
   change_class(input_file)

   file_new = open(filename_out, 'w')
   for x in newlist:

   if '\n' in x:
      x = x.replace('\n', '')
      print>>file_new, x

When I tried to add stdin stdout to it, I first had a problem with reading the same input file first, and for this reason made some chages so that it would be actually open only once. I modified the following:
def f2(input_data) #instead of input_file

and I modified main():
        filename = sys.argv[1]
        filename_out = sys.argv[2]

        if filename == '-':
           input_file = sys.stdin
           input_file_open = io.open(input_file, encoding = 'utf-8', mode = 'rb')

           input_data = input_file_open
        else:
            input_file = open(filename, 'rU')
            input_data = input_file

        if filename_out == '-':
            filename_out = sys.stdout
            file_new = filename_out
        else:
            file_new = open(filename_out, 'w')

        tree = etree.parse(input_data)
        extract(tree)

        change_class(input_data)

        for x in newlist:

            if '\n' in x:
               x = x.replace('\n', '')
            print>>file_new, x

I run my script like this:
./myscript.py - - volumeid < inputfile > outputfile

Then I got this error message:
input_file_open = io.open(input_file, encoding = 'utf-8', mode = 'rb')
TypeError: invalid file: <open file '<stdin>', mode 'r' at 0x7f9a2d5ab150>


text:
Q: RExcel with Jdbc I am trying for a jbbc connection through RExcel. The command
install.packages("RJDBC", dep=TRUE)

in RExcel shows downloading package but when run
library(RJDBC)

it shows
Error in library(RJDBC) : there is no package called 'RJDBC'

which means that RJDBC has not been installed.

*

*Is it the proper way to install package in RExcel?

*Is there any way to check what packages are installed there in RExcel as I do not see any library folder in the working directory?

*Any alternate way to achieve JDBC connectivity through RExcel?

Output of install process:
[10] WARNING: Warning: cannot remove prior installation of package 'RJDBC'
[11] NOTE: trying URL 'http://ftp.iitm.ac.in/cran/bin/windows/contrib/3.1/RJDBC_0.2-5.zip'
Content type 'application/zip' length 65639 bytes (64 Kb)
opened URL
downloaded 64 Kb

package 'RJDBC' successfully unpacked and MD5 sums checked

The downloaded binary packages are in
    C:\Users\Leo\AppData\Local\Temp\RtmpOo7HHY\downloaded_packages


text:
Q: Alternate way to organize functions in a NSViewController subclass? (Swift, OSX)
I currently have a view controller (named ViewController) that manages the view of my application with storyboards, consisting of a couple of text boxes for user input. If the user enters something incorrect, it calls a function that alerts the user to their error (with a NSAlert modal), and offers them an option: reset their input, reset their input and previous output, or just dismiss the window.
Problem is, that alert code alone is about 60 lines of code (with functions to display appropriate messages), and I want to move it into another class -- a subclass of ViewController, entitled ErrorResponse, so it can still access the user interface to appropriately reset their input (i.e., clear an input string field), and do the other tasks mentioned above while avoiding a massive wall of functions in the ViewController
I've tried creating a subclass of ViewController so the user interface properties are inherited and I can simply access them, however Xcode wants the subclass to implement an init method with NSCoder. (To my knowledge, this is how Xcode sets up a storyboard or .xib to communicate with the controller, as part of the NSViewController class, but this is unrelated to my implmenetation). When I attempt to pass nil or a default initialized NSCoder() object, I get obscure crashes.
So, is there any way to organize these functions? Or should I just keep them all in the ViewController?
Edit: I also have an existing class called ErrorCheck that performs the check to see if there are any errors. Within the ViewContoller, when the input is entered, there is a guard statement with a method from ErrorCheck, and if the input is invalid in some way, the corresponding methods in ErrorResponse are called.
Code snippet:
class ViewController: NSViewController {

    // Input and output text fields
    @IBOutlet weak var inputStr: NSTextField!
    @IBOutlet weak var outputStr: NSTextField!

    // Input and output conversion selection
    @IBOutlet weak var inputSegments: NSSegmentedControl!
    @IBOutlet weak var outputSegments: NSSegmentedControl!

    @IBAction func outputIsSelected(sender: NSSegmentedControl) {

        // Passing all UI elements in (not shown)
        // Not ideal, want to be global obj (see below code)
        guard ErrorCheck().stringIsNotEmpty(inputStr.stringValue) else {
            ErrorResponse().invalidEmptyInput()
            return
        }

        // 0 = DNA, 1 = mRNA, 2 = English
        if (inputSegments.selectedSegment == 0) {
            checkPossibleConversionAndConvertDNA()
        } else if (inputSegments.selectedSegment == 1) {
            checkPossibleConversionAndConvertmRNA()
        } else if (inputSegments.selectedSegment == 2) {
            checkPossibleConversionAndConvertEnglish()
        }

    }
}

If I don't subclass ViewController, there is another issue: I can't globally define an object for ErrorResponse, as I can't pass the UI values within the same scope as they are being initialized, so currently I have initialized an ErrorCheck object in each corresponding function... and its messy.

A: I ended up just moving the methods into ViewController. Not the prettiest, but it's functional.


text:
Q: Android Studio: emulator won't install I am running Android Studio 3.2.1 on 32-bit Windows Vista. When it came to running a default tryout application and the emulator choosing window popped up I couldn't install am emulator. It asked me which version of Android and dimensions but then the window closes and the app doesn't run. Any ideas about what is going wrong here and how to fix it?
Thanks.

A: I've actually figured out what went wrong. The emulator instances now show up when I run the application but then upon launching the app in the emulator I get the following error messages:
Emulator: emulator: ERROR: Windows 7 or newer is required to run the Android Emulator.
Emulator: Process finished with exit code 1
So no, it's not possible to run the emulator on Windows Vista.

A: Try GenyMotion Android Emulator , it has a lot of features.


text:
Q: exception in release mode and not in debug mode When i run this code in debug mode no exceptions appear but in release mode i get this exception :

Unhandled exception at 0x768b4b32 in RealTimeSLT.exe: Microsoft C++
  exception: cv::Exception at memory location 0x003de734..

why this problem appear only when release ?and how can i fix it ??
FileStorage fs2(fileName, FileStorage::READ);
fs2.open(fileName, FileStorage::READ);
fs2["Mat"] >> Mat;
fs2["dMat"]>> dMat;
fs2.release();

A: Assuming you're running in VS, choose Debug->Exceptions and click on 'Break When Exception is Thrown'
Run the app under the debugger and see why that exception is thrown and what its complaining - it's most likely something different in the environment the app is running under.
If you need to examine variables then release build makes this hard as the optimiser is likely confusing the debugger. You can probably solve this by turning off optimizations in your release build. However, if its a timing issue this may hide the problem.
Another option is catching the exception being thrown and then logging its internal message - this is normally a function called 'what()' or similar. This very likely will point you to the actual problem. Its likely that you'll want to catch this exception anyway.
If its undefined behavior causing the difference between Release and Debug then its likely the above wont be as much use.

A: The code looks odd.
Without knowing any more about your FileStorage object, I can see that you've created one on the stack on the first line.
Assuming release() is some kind of reference counting method, fs2.release() will attempt to delete it since the reference count will be zero.
Not good to delete objects that have been allocated on the stack. You'll get a crash.
Either (1), try this instead (i.e. allocate on the heap)
FileStorage fs2 = new FileStorage(fileName, FileStorage::READ);

(Assuming the object has reference counting semantics built in; check the docs).
Or 2:
remove the last line as fs2 will go out of scope as the stack unwinds.

A: U need to add "*.lib" files to vs project's linker again when U r in release mode.
I think this is a bug for opencv after 2.4.1.

A: In my case, it was because the OpenCV libraries were built with VS2010, and I was using VS2015.
To resolve issue, I changed my Project Properties > General > Platform Toolset to match the toolset used to build the opencv libraries I was linking with.


text:
Q: How to inherit a website and create a child panel I have a website, example.com, which provides some service. Another person wants to have the same site but with another price for the service. I give him a possibility to inherit from my site. He gives me his domain, I set it up and he has the identical site like mine but with another domain, another price for service and there is no possibility to inherit another site from inherited site.
This process is implemented in
https://smmworldpanel.com/services
https://smmstats.com/franchise
And in all smm panels
How can be it implemented?
P. S. I use python, django, drf, for backend


text:
Q: How to extend class? I'm making a change to an API that serves data. Some of the searches require data about an author and take a IAuthor object. The API has an IAuthor interface and a single concrete class that implements IAuthor called Author.
I need to add a boolean property, IsNovelist that will change the semantics of some but not all searches.
I've heard about the open/closed principle and it would seem that changing the IAuthor and/or Author classes would violate this. How then to make this simple change?

UPDATE:
Perhaps I was concentrating on the wrong class. I don't want to add behaviour to Author class (it's just a way of passing parameters to the API). So a Decorated author wouldn't need a boolean flag because it would be isNovelist == true by implication.
I need to change the behaviour of the GetBooks method given an author who is flagged as being a novelist. So something more like this but my thinking is probably wonky because now I'm changing (not extending) the Books class:
//Before
class Books
{
   public Books[] GetBooks(IAuthor author){
       // Call data access GetBooks...
    }
}

//After
class Books
{
   public Books[] GetBooks(IAuthor author){
       // To maintain pre-existing behaviour
       // call data access GetBooks with SQL param @isNovelist = false...
       // (or don't pass anything because the SQL param defaults to false)
    }

   public Books[] GetBooksForNovelist(IAuthor author){
       // To get new behaviour
       // call data access GetBooks with SQL param @isNovelist = true
    }
}

A: Solution 2 :
class Program
{
    private static void Main(string[] args)
    {

        IAuthor author = new Novelist();
        author.Name = "Raj";

        // i guess u have check if author is a novelist
        // the simple way is by safe typecasting

        Novelist novelist = author as Novelist;

        if (novelist != null)
        {
            Console.WriteLine("Wohoo, i am a novelist");
        }
        else
        {
            Console.WriteLine("Damn,i cant write novel");
        }

    }

Solution 1 :
public enum AuthourType
{
    Novelist,
    Other
}

public interface IAuthor
{
    string Name { get; set; }
    AuthourType Type { get; set; }

}

public class  Novelist : IAuthor
{
    public string Name { get; set; }
    public AuthourType Type { get; set; }
    // incase u dont want it to be set to other value
    /*
    public AuthourType Type
    {
        get { return type; }
        set
        {
            if (value != AuthourType.Novelist)
            {
                throw new NotSupportedException("Type");
            }
            type = value;
        }
    }
    */
}

A: Here is how you do using the decorator pattern
interface IAuthor
{
    void someMethod();
}

class Author:IAuthor{

    public void someMethod(){
        //Implementation here
    }
}

//Class that will add the extra behavior.
class DecoratedAuthor : IAuthor
{
    IAuthor author;
    public bool isNovelist{get;set;}//Add the extra Behavior

    public DecoratedAuthor(IAuthor auth)
    {
        this.author = auth;
    }

    public void someMethod(){
        //Call the Author's version here
        author.someMethod();

        //check if he is a novelist
        isNovelist = true;
    }

}

public class program{
    public static void Main(string[] args)
    {
        IAuthor auth = new Author();
        DecoratedAuthor novAuth = new DecoratedAuthor(auth);

        DecoratedAuthor.someMethod();
        //see if he is a novelist
        Console.WriteLine(novAuth.isNovelist);

    }

}


text:
Q: How to avoid downloading image from firebase if i have already downloaded previously? I am trying to store image from firebase database and named it FirebaseuniqUserID.jpeg.(like buwkgefuikbuifbkc8gfybfy.jpeg). And user can change image anytime.
For getting image link from firebase realtime database i used addListenerForSingleValueEvent.
FirebaseDatabase.getInstance().getReference().child("Users").child(FirebaseuniqUserID).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        //here i am downloading image//
        //and named it FirebaseuniqUserID.jpeg
    }

Now the problem is this when this listener is called every time image is download.
But now i want avoid downloading if current user has latest updated image of user in firebase to reduce firebase downloaded data.

A:
I want avoid downloading if current user has latest updated image of user in Firebase

To solve this, I definitely recommend you to use an image loading and caching library. For Android we have Glide:

Glide is a fast and efficient open source media management and image loading framework for Android that wraps media decoding, memory and disk caching, and resource pooling into a simple and easy to use interface.

A: You can use two different options, first is Glide and 2nd is that, you can save image downloading status in your local database file or SharePreferences. But image cache is the best solution.


text:
Q: How to compare different lengths of a vector? I have two vectors:
A <- 10 10 20 19 24 24 17 18 24 24 24 25 16 16 16 25 25 12 12 12 25 24 24 24 24  2  2

and
B <- 2 4 2 2 2 3 2 3 2 3 2

I would like to compare the first two elements of A (here:10 10). Why? Because B's first entry is two. Then I would like to compare the elements 3 to 6 from A (that is: 20 19 24 24) because B's second element is 4. And so on...
When I say I want to compare them, what I want to do is to see if any element of the chosen range is below a threshold (e.g. below 20) and another element of them larger than another threshold (e.g. 23).
The desired output would be to count how many times this two conditions where
fulfilled (here at max 11 times this could have happened since B is of length 11, which means my vector A has 11 ranges which will be compared). In this example, only the second range would have fulfilled the condition. Therefore the output would be 1. It would also be great, if it were possible to say that it was the second range which fulfilled the condition. Hence the output would be like this:
count: 1     range: 2

Does anyone have any idea how to do this?

A: May be this helps
res <- tapply(A,rep(seq_along(B), B), FUN=function(x)  any(x < 20) &
                    any(x>23))+0L
res
# 1  2  3  4  5  6  7  8  9 10 11
# 0  1  0  0  0  0  0  0  0  0  0

d1 <- data.frame(count=res, range=names(res))
head(d1,3)
#   count range
#1     0     1
#2     1     2
#3     0     3

data
A <- c(10, 10, 20, 19, 24, 24, 17, 18, 24, 24, 24, 25, 16, 16, 16,
   25, 25, 12, 12, 12, 25, 24, 24, 24, 24, 2, 2)
B <-  c(2, 4, 2, 2, 2, 3, 2, 3, 2, 3, 2)


text:
Q: Make table row editable using jQuery, jEditable, jeditable-rails gem or any AJAXy solution I have a table with rows of data on it. I want most of the row to be editable by clicking either the row itself or an edit button.
Let's say I have a table that lists products:

*

*Product Name

*Brand

*Model

*Price

I'm able to accomplish this by using jQuery and jEditable; and also by using the jeditable-rails gem. But I can only edit one cell at a time.
What I need is this: If I click in the Edit button or the row itself. All those four cells in the table should become editable.

A: Try something like this:
$('td:not(.edit)').editable('', {
    onblur: 'ignore',
    submit: 'ok',
    cancel: 'cancel',
    width: 75,
    event: 'edit'
});

$('td').click(function(e) {
    // reset all editables
    var allEditables = $(this).closest('table').find('td:not(.edit)').get();
    $.each(allEditables, function(i, elm) {
        elm.reset();
    });

    // make all cells in this row editable
    $(this).parent().children(':not(.edit)').trigger('edit');
});

Example: http://jsfiddle.net/UMccc/221/

A: I found the right path here: jQuery - Edit a table row inline
It doesn't use jEditable.
It's just a Javascript function, but I think it's launch pad for creativity.

A: Here is an easy to use and flexible jquery inline editable plugin. It let's you to have editable easily anywhere, inside a table or h1 tag, and can covnert anything to anything. actually the idea behind is simple and kinda unique.
Cheers,


text:
Q: Is there a simpler way to implement a JSON REST service with net/http? I am trying to develop a REST service with net/http.
The service receives a JSON structure containing all the input parameters. I wonder if there is an easier and shorter way to implement the following:
func call(w http.ResponseWriter, r *http.Request) {
    if err := r.ParseForm(); err != nil {
        fmt.Printf("Error parsing request %s\n", err)
    }
    var buf []byte
    buf = make([]byte, 256)
    var n, err = r.Body.Read(buf)
    var decoded map[string]interface{}
    err = json.Unmarshal(buf[:n], &decoded)
    if err != nil {
        fmt.Printf("Error decoding json: %s\n", err)
    }
    var uid = decoded["uid"]
    ...
}

As you can see it requires quite a number of lines just to get to the extraction of the first parameter. Any ideas?

A: You don't need to call r.ParseForm if the body of the request will contain a JSON structure and you don't need any URL parameters.
You don't need the buffer either; you can use:
decoder := json.NewDecoder(r.Body)

And then:
error := decoder.Decode(decoded)

Putting it all together:
func call(w http.ResponseWriter, r *http.Request) {

    values := make(map[string]interface{})

    if error := json.NewDecoder(r.Body).Decode(&values); error != nil {
        panic(error)
    }

    uid := values["uid"].(int)

}

It would be much nicer, though, if you could formally define the structure of the input that you're expecting in a struct type:
type UpdateUserInformationRequest struct {
    UserId int `json:"uid"`
    // other fields...
}

And use an instance of this struct instead of a more general map.


text:
Q: Getting fopen/fwrite to write to different directory I need to write text files, i try with this code
public function ResultsTrackingLogs( $event, $message ) {
$logsDir = dirname( __FILE__ ) . "/logs/Results Tracking/$event/";
$fh = fopen( $logsDir . "$event.txt", 'x' ) or die( "can't open file" );
fwrite( $fh, $message );
fclose( $fh );
}

The $logsDir translates into E:\Dropbox\htdocs\Scrapers\this  beyond that the \$event\ makes it so each event has its own subfolder.
Anyway I adjust..  I.E /logs/Results Tracking/ ..  or \logs\Results Tracking\..
still gives me an error fopen(E:\Dropbox\htdocs\Scrapers\this\logs/Results Tracking/event1/event1.txt): failed to open stream: No such file or directory.
the directory is there, I've created a .txt file there too, doesn't find it. the problem is obviously in how I describe my directory structure. how do i fix this? I don't want to create the directory structure before, I need it to create folders as it needs to.

A: Check if the destination dir exists, create it if not.
   if(! is_dir($logsDir) ) { mkdir($logsDir, 0777, true); }

You could use the DIRECTORY_SEPARATOR if you want to describe a path.


text: Q: Can someone do something to my website if I posted a snapped image of the header and covered my logo? (On reddit, when explaining a question) The question is as it states. I don't want to go on reddit to ask this. Might not be the place to ask a question like this, but I am worried. After I posted my question my wordpress started acting up, loading slowly and eventually just not working at all. Can this be the work of someone else? Or just a hosting problem?


text:
Q: jQuery slideDown/slideUp behavior I'm using jQuery slideDown/slideUp functions to create a menu that displays links when you mouseover it.  The menu is an image that contains a menu title and when you mouseover the image it grows vertically displaying the links.  The menu images/links are contained in a div to help position the images.
I'm able to get the menu images to grow vertically displaying all links, but when I attempt to hover over the bottom links jQuery collapses the image prematurely.  What is even more odd is the menus work correctly when at the top of the screen, but quit fully working when I position the menu images where they belong on the background image.
It appears the hover region is not growing vertically with the image, but staying the original height of the collapsed image.
The following are my jQuery functions:
    $( document ).ready
       (
          function()
          {
             $( '.down-list' ).width( $( '.dropdown-menu' ).width() );

             $( '.dropdown-menu' ).hover
                (
                   function()
                   {
                      $( '.menu-first', this ).addClass( 'slide-down' );
                      $( '.down-list', this ).slideDown( 50 );
                   },

                   function()
                   {
                      obj = this;

                      $( '.down-list', this ).slideUp
                         (
                            50,

                            function()
                            {
                               $( '.menu-first', obj ).removeClass( 'slide-down' );
                            }
                         );
                   }
                );
          }
       );

Here is the HTML:

             <map name="navMap">
                <area shape="rect" coords="387,9,717,95" href="http://www.kungfubranson.com" alt="Home" />
                <area shape="rect" coords="833,0,1008,100" href="http://foursquare.com/venue/6109987" target="_blank" alt="Four Square" />
                <area shape="rect" coords="1045,45,1080,79" href="http://twitter.com/KungFuBranson" target="_blank" alt="Twitter" />
                <area shape="rect" coords="1087,45,1122,78" href="http://www.facebook.com/kungfubranson" target="_blank" alt="Facebook" />
                <area shape="rect" coords="1131,45,1167,79" href="http://www.youtube.com/kungfubranson" target="_blank" alt="YouTube" />
                <area shape="circle" coords="1273,56,37" href="https://tickets.kungfubranson.com" target="_blank" alt="Buy Tickets Now!" />
             </map>

                            Show

                            Info

                            Story

                            News

                            Reviews

                            Contact

Here is the corresponding CSS:
    /*-------------------------------*/
    /* Contains every Division Layer */
    /*-------------------------------*/
    body
    {
       margin: 0px;
       padding: 0px;
       background-color: #FFF0E0;
       font-family: Arial, Helvetica, sans-serif;
       font-size: 16px;
       font-style: normal;
       font-variant: normal;
       font-weight: normal;
    }

    /*-------------------------------------------------------------------*/
    /* Primary Division Layer and the ONLY one with a Relative Position  */
    /* permitting entire page to resize according to browser window size */
    /*                                                                   */
    /* Used on Home Page and contains all subsequent Division Layers     */
    /*-------------------------------------------------------------------*/
    #container
    {
       position: relative;
       margin: 0 auto 0 auto;
       width: 1600px;
       height: 1238px;
    }

    /*---------------------------------*/
    /* Contains Menu Image Label Links */
    /*---------------------------------*/
    #menuLinks
    {
       position: absolute;
       top: 200px;
       left: 491px;
       width: 582px;
       height: 200px;
    }

    .dropHolder
    {
       width: 90px;
       float: left;
       height: 1px;
       margin-left: 2px;
       line-height: 1.2em;
       color: #000;
       font-variant: normal;
       font-size: 13.5px;
       font-family: "Trebuchet MS", Helvetica, sans-serif;
       font-weight: bolder;
    }

    .dropHolder html, .dropHolder div, .dropHolder span, .dropHolder applet, .dropHolder object, .dropHolder iframe, .dropHolder blockquote, .dropHolder pre,
    .dropHolder a, .dropHolder abbr, .dropHolder acronym, .dropHolder address, .dropHolder big, .dropHolder cite, .dropHolder code,
    .dropHolder del, .dropHolder dfn, .dropHolder em, .dropHolder font, .dropHolder img, .dropHolder ins, .dropHolder kbd, .dropHolder q, .dropHolder s, .dropHolder samp,
    .dropHolder small, .dropHolder strike, .dropHolder strong, .dropHolder sub, .dropHolder sup, .dropHolder tt, .dropHolder var,
    .dropHolder dl, .dropHolder dt, .dropHolder dd, .dropHolder ol, .dropHolder ul, .dropHolder li
    {
       margin: 0;
       padding: 0;
       border: 0;
       outline: 0;
       vertical-align: baseline;
    }

    .dropHolder ol, .dropHolder ul
    {
       list-style: none;
    }

    .dropdown-menu
    {
       position: absolute;
       width: 90px;
       cursor: pointer;
       z-index: 1000px;
    }

    .dropdown-menu a:link, .dropdown-menu a:visited
    {
       color: #000 !important;
       display: block !important;
       text-decoration: none !important;
       margin: 0 !important;
       width: 90px;
    }

    .dropdown-menu a:hover
    {
       color: #cb0202 !important;
       text-decoration: none !important;
       width: 90px;
    }

    .dropdown-menu .slide-down
    {
       background: url(../images/lanternTop.png) no-repeat;
       width: 90px;
    }

    .menu-first
    {
       background: transparent url(../images/lanternTop.png) no-repeat;
       width: 90px;
       height: 38px;
       text-align: center;
       padding: 0px 0px 0px 0px;
       vertical-align: bottom;
       line-height: 14px;
    }

    .menu-first2
    {
       position: relative;
       bottom: -23px;
       z-index: 100;
    }

    .down-list
    {
       background: url(../images/lanternMiddle.png) repeat-y;
       width: 90px;
       margin-left: 0px;
       z-index: 500;
       font-size: 13px;
    }

    .down-list li
    {
       background: url(../images/lanternMiddle.png) repeat-y;
       width: 90px;
       height: 25px;
       padding: 0px 0px 0px 0px;
       text-align: center;
       line-height: 24px;
       vertical-align: bottom;
    }

    .down-list_OFF .lastLI_OFF
    {
       background: url(../images/lanternMiddle.png) repeat-y;
       width: 88px;
       height: 8px;
       line-height: 12px;
       vertical-align: bottom;
    }

    /*-----------------------*/
    /* Contains Page Content */
    /*-----------------------*/
    #content
    {
       position: absolute;
       top: 316px;
       left: 413px;
       width: 771px;
       height: 825px;
       text-align: justify;
       overflow-x: hidden;
       overflow-y: auto;
    }

I'm using jquery-1.7.2.min.js.
Thanks in advance for any help.
Brandon

A: Replace the #menuLinks css from this
#menuLinks {
  float: left;
  height: 200px;
  margin-left: 491px;
  margin-top: 200px;
  width: 582px;
}


text:
Q: Why is my ArrayList prints the elements as frequent as when it's called I'm doing a project for school supplies store using Java. I've declared the products using a constructor and I've stored the elements in an ArrayList. I have multiple methods which can add, subtract quantities, modify unit price, add and display all products. Every time I want to display the products it displays the list just like how many times it was called in the program. For example, first I call my display all product method, it will display one time. The second I call my display all product method, it will display all the products twice and so on just like this:

This is my display all product method:
public static void displayProducts() {

    inventoryList.add(product);
    inventoryList.add(oslo);
    inventoryList.add(pilot);
    inventoryList.add(mongol);
    inventoryList.add(hbw);
    inventoryList.add(crayola);
    inventoryList.add(fabercastell);
    inventoryList.add(orion);
    inventoryList.add(easywrite);

    for (int i = 1; i < inventoryList.size(); i++)
        inventoryList.get(i).outputDisplay();

}

public void outputDisplay() {
    System.out.println(String.format("|%-21s\t%-18s\t%5.2f\t%8d|", brand, type, price, quantity));
}

A: Your displayProducts() method does more than displaying the products. It adds them to the inventory first, then displays them. So the first time you call it, it adds the elements and displays them. The second time you call it, it adds the elements, and since they were already there, it's like it's displaying them twice. But really, what it's doing is displaying what's in the list once. The problem is that you should be adding the elements to the inventory independently of the method that shows them, but you aren't.

A: You should split the method in 2 methods, one that adds the elements and one that displays them, because every time you call your current method you both add and display the elements.

A: Your displayProducts method not only displays the inventory, but it also adds products to the inventory.
The displayProducts method should only display products, otherwise you'll get buggy and confusing behavior.
public static void displayProducts() {
    for (int i = 1; i < inventoryList.size(); i++)
        inventoryList.get(i).outputDisplay();
}

You'll want to have a separate method that adds the products to the inventory. You would call this method only once.
public static void addProducts() {
    inventoryList.add(product);
    inventoryList.add(oslo);
    inventoryList.add(pilot);
    inventoryList.add(mongol);
    inventoryList.add(hbw);
    inventoryList.add(crayola);
    inventoryList.add(fabercastell);
    inventoryList.add(orion);
    inventoryList.add(easywrite);
}


text:
Q: 5 card poker hand contains 3 aces, conditional probability question Really struggling with this question and could use some guidance.
If a poker hand (five cards) is known to contain at least three aces, what is the probability that it contains all four aces?
I have been taking an approach using conditional probability to solve this and am coming up short. Thanks in advance

A: If there are at least three aces in the hand, either it contains exactly three aces or exactly four aces. Thus
$$P(4A|\ge3A)=\frac{P(4A)}{P(3A)+P(4A)}=\frac{\#(4A)}{\#(3A)+\#(4A)}=\frac{48}{\binom43\binom{48}2+48}=\frac{48}{4560}=\frac1{95}$$
where $\binom43\binom{48}2$ consists of choosing three aces from four and two cards from the 48 non-aces.


text:
Q: wxPython matplotlib - detecting which line was clicked on 3D line plot I am using this example code as my starting code
This code generates a bar graph. When the user clicks on an actual bar on the bar graph, an event is triggered and the bounding box coordinates of the individual bar are displayed. This happens in the on_pick function.
I have modified the code so instead of a bar graph, I have a Axes3D line plot. I have several separate lines plotted on this XYZ coordinate system. What I need is to recognize which line was clicked. It appears that the bounding box does not work for the 3D plot as it did with the bar graph.
I have looked into the pick_event documentation but have been unsuccessful in finding a solution. I can simply detect the x,y coordinate of the location clicked, but because the plot can be rotated at any angle, it seems quite difficult to detect which line was actually clicked, especially since they can be overlapping depending on the point of view.
I appreciate your time and help!

A: If you only need to know which curve is clicked, it's not very difficult. You need to create a line_picker() to check whether the mouse position is close enough to the curve or not.
line_picker() need to calculate distance between point and line segments, that's a little difficult, I walk around this problem by using linear interpolation of the curve.
Here is the code, I interpolate the curve by 2000 points, and if the mouse position to the curve is less than 5 pixels, then the curve is selected.
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt

def line_picker(line, me):
    if me.xdata is None: return False, dict()
    x, y = me.x, me.y
    xdata, ydata = line.axes.transData.transform(np.array(line.get_data()).T).T
    index = np.arange(len(xdata))
    index2 = np.linspace(0, index[-1], 2000)
    xdata2 = np.interp(index2, index, xdata)
    ydata2 = np.interp(index2, index, ydata)
    d = np.sqrt((xdata2-x)**2. + (ydata2-y)**2.)
    if np.min(d) < 5:
        return True, {}
    else:
        return False, {}

mpl.rcParams['legend.fontsize'] = 10

fig = plt.figure()
ax = fig.gca(projection='3d')
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
line1 = ax.plot(x, y, z, label='parametric curve', picker=line_picker)[0]

t = np.linspace(-1, 1, 100)
x = 4*np.sin(10*t)
y = 4*np.cos(10*t)
z = t**2*5-3

line2 = ax.plot(x, y, z, label="second", picker=line_picker)[0]

ax.legend()

def onpick(event):
    print [line1, line2].index(event.artist)

fig.canvas.mpl_connect('pick_event', onpick)

plt.show()


text:
Q: svg element attribute y is not getBBox().y Following is my code, attr y is translate y not "y in svg", I expect find attr svgY  to set "y in svg", how to do?
    var it: SVGTextElement
    ReactDOM.render(<svg>
        <text ref={e => it = e} y={10}>pr</text>
    </svg>, document.querySelector("#root"))
    var by = it.getBBox().y
    console.log(`by:${by}`) // by:-4.34375


text:
Q: Simplify template function by passing a template as argument possible? I wrote a smal example illustrating the problem. solve_bs1_y and solve_bs2_y are implemented completely similar. The only difference is the function call: solve_bs*_z. Unfortunately, it seems impossible to pass a template as argument to replace the function call of solve_bs*_z. Consequently, I have to implement for each solve_bs*_z another solve_bs*_y. Is there a way to simplify the code so that I need just one implementation of solve_bs_y?
// Example program
#include <iostream>
#include <string>

template <int x, int y, int offs, class T>
float solve_bs1_z(T mat, float fS, float fT, float fU) {
  return 1; // to keep it simple
}

template <int x, int y, int offs, class T>
float solve_bs2_z(T mat, float fS, float fT, float fU) {
  return 2; // to keep it simple
}

// essentially the same as solve_bs2_y
template <int x, int offs, class T>
float solve_bs1_y(T mat, float fS, float fT, float fU) {
  const float bs_s = 2;

  return    ( solve_bs1_z<x, 0, offs>(mat, fS, fT, fU)
      + solve_bs1_z<x, 1, offs>(mat, fS, fT, fU)
      + solve_bs1_z<x, 2, offs>(mat, fS, fT, fU))
      * bs_s;
}
// essentially the same as solve_bs1_y
template <int x, int offs, class T>
float solve_bs2_y(T mat, float fS, float fT, float fU) {
  const float bs_s = 2;

  return    ( solve_bs2_z<x, 0, offs>(mat, fS, fT, fU)
      + solve_bs2_z<x, 1, offs>(mat, fS, fT, fU)
      + solve_bs2_z<x, 2, offs>(mat, fS, fT, fU) )
      * bs_s;
}

// these are called in the program ..
template<int offs, class T>
float solve_ffd_bs1(T mat, float fS, float fT, float fU) {
  return    solve_bs1_y<0, offs>(mat, fS, fT, fU) +
      solve_bs1_y<1, offs>(mat, fS, fT, fU) +
      solve_bs1_y<2, offs>(mat, fS, fT, fU);
}

template<int offs, class T>
float solve_ffd_bs2(T mat, float fS, float fT, float fU) {
  return    solve_bs2_y<0, offs>(mat, fS, fT, fU) +
      solve_bs2_y<1, offs>(mat, fS, fT, fU) +
      solve_bs2_y<2, offs>(mat, fS, fT, fU);
}

int main()
{
    int mat[3][3][3] = {
        {{1,2,3}, {4,5,6}, {7,8,9}},
        {{11,2,3}, {14,5,6}, {17,8,9}},
        {{21,2,3}, {24,5,6}, {27,8,9}}
        };

  solve_ffd_bs2<0>(mat, 1,2,3);

  return 0;
}

A: The wrapper version without struct templates:
struct s1 {
    template <int x, int y, int offs, class T>
    static float solve_bs_z(T mat, float fS, float fT, float fU) {
      return 1; // to keep it simple
    }
};

struct s2 {
    template <int x, int y, int offs, class T>
    static float solve_bs_z(T mat, float fS, float fT, float fU) {
      return 2; // to keep it simple
    }
};

template <class Wrapper, int x, int offs, class T>
float solve_bs_y(T mat, float fS, float fT, float fU) {
  const float bs_s = 2;

  return    ( Wrapper::template solve_bs_z<x, 0, offs>(mat, fS, fT, fU)
      + Wrapper::template solve_bs_z<x, 1, offs>(mat, fS, fT, fU)
      + Wrapper::template solve_bs_z<x, 2, offs>(mat, fS, fT, fU))
      * bs_s;
}

and then call:
solve_bs_y<s1, 0, 1>(...);


text:
Q: Android: Detecting USB connected on PC Is there any way to detect (programmatically) an USB connection in my PC that let it know my Android phone connected to PC through USB (like the way Autoplay popup appears on a Windows machine)?

A: https://www.autoitscript.com/forum/topic/145233-autoit-autoplay-program/
I use autoit if you're on a windows machine. You're trying to create an event listener for a usb event.
Edit: yay retroscripting for the commenter


text:
Q: how can I program in ASP.net using PHP like methods I am a PHP programmer and I want to develop a website using visual web developer .net
I knew that asp.net has many different approaches in dealing with database. However, I am familer with PHP way in programming for example:
$query = "select * from table where user_id > 2"
$result = mysql_query($query);

while($row = mysql_fetch_array($result)){

echo "username is: ".$row["username"]."
"; }

the question is "can I deal with asp.net in a PHP way?"

A: Sure...learn C# (somewhat similar syntax) Or develop using one of the following:

*

*PHP4Mono

*PHP4Apps

*PHP Sharp

*PHP Mono Extensions

*Phalanger

*IronPHP
Other .NET Powered Languages
My honest suggestion to you is that if you want to develop ASP.NET or .NET in general, you should learn C#. I did, and I am happy having done it.

A: Maybe you should consider the way you are programming. Mixing logic, presentation and data access is not a good idea in any language. The example you showed is not "PHP way". Yes, it is possible to write like that in php but it's not a good practice. I think that by learning asp.net you may also learn a lot about programming and you really shouldn't try to program like that in asp.

A: C# 3.0 offers very powerful syntax that allows you to interact with the database in a way that is both natural and safe (using parameterized queries).  Your query in C# with LINQ2SQL would look like:
var query = from t in context.table
            where t.user_id > 2
            select t;

You'd probably use a Repeater in your view so you could just provide your query as the datasource (there are ways to do this in mark up, too) in your codebehind.
// use ToList so context can be disposed
nameRepeater.DataSource = query.ToList();

Your mark up would look like:
<asp:Repeater runat="server" ID="nameRepeater">
   <ItemTemplate>
   username is:
   <asp:Label runat="server"
              ID="nameLabel"
              Text='<%= Bind("username") %>' />

</asp:Repeater>

(lines split for readability)
Or you could use ASP.NET MVC in which case the selection code would be in your controller and you could use something more like your PHP-syntax in a strongly-typed view.
<% foreach (Table t in ViewData.Model) { %>
   username is: <%= t.username %>

<% } %>

A: There are a lot of ways in asp.net.  It's a little confusing, but they are all basically the same.  The difference is the type of data access you use.
Using Enterprise Library (you need to download this) is probably one of the closest ways:
Database database = DatabaseFactory.CreateDatabase();
string sqlCommand = @"SELECT * FROM Users WHERE UserID=@UserID";
System.Data.Common.DbCommand dbCommand = database.GetSqlStringCommand(sqlCommand);

DataSet dataSetGroup = database.ExecuteDataSet(dbCommand);
DataTable dt = dataSetGroup.Tables[0];

foreach (DataRow dr in dt.Rows)
{
    Response.Write("User name is: " + dr["Username"].ToString() + "
");
}

Enterprise Library is just a Microsoft library that simplifies data access.  If you do not use it you can access the database directly but it takes a few more lines that handle the opening and closing of a data connection and you have to be more careful about opening and closing connections.
Other ways to do it are:

*

*Use strongly typed datasets

*Use LinqToSql or LinqToEntities and the ADO.net Framework

They are all different but similar in structure where you'll query the database and then do a foreach (you can also use while) to loop through your data.
I've been using LinqToSql recently and prefer that method.  Scott Gu's blog has a good series of posts on how to use LinqToSql (linked to the last post so you can see all the previous ones):
http://weblogs.asp.net/scottgu/archive/2007/09/07/linq-to-sql-part-9-using-a-custom-linq-expression-with-the-lt-asp-linqdatasource-gt-control.aspx


text:
Q: How can I view the contents of the Minimongo database in the client with Meteor? I know I can query CollectionName.find().fetch() in the browser's JS console. Are there other tools that are the equivalent of a GUI admin tool for all  the browser's local minimongo storage ?

A: Mongol does this, FTW, thanks to Max Savin.

A: Also I noticed no one has mentioned it but there is also for chrome a 'Meteor DevTools' extension that you can add to chrome tools. Once your meteor project is running you can see in chrome tool a tab called 'Meteor' that will show you what MiniMongo has.

A: You can either use a server-side privileged admin solutions like Houston or any other MongoDB admin interface.
If you want to query data on the client for a quick inspection, you can use console.table:
console.table(Tasks.find().fetch())

A: There is a open source MongoDB management tool called Robomongo — which is very efficient and useful.

A: There is an awesome atmosphere package meteor toys that shows the subscribed data on minimongo. It also allows to add, edit or delete data on the go. very handy.
Also, meteor toys may not work with latest meteor update (1.6.1+). So, I found a light package that does the same called constellation.
You can choose from anyone. It will surely help debugging on minimongo easier.

A: You can use the Chrome plugin Meteor MiniMongo Explorer, it's very useful and show you every collections/documents you have currently on your MiniMongo
Pro compared to Mongol
You don't need to add any package to your meteor project to works

A: Open the console and do it:
Meteor.connection._mongo_livedata_collections[collectionName].find().fetch()

My current Meteor's version is 1.8.1. I don't know it is possible to do the same on the older ones.


text:
Q: How can I check if SQL Server memory caching is enabled on my server? I have few questions about SQL Server 2008.
How can I check is Memory Caching feature in SQL Server 2008 is enabled? Is there a variable to turn memory caching on or off? "I just want to make sure it is on"
Also, when does SQL Server decide that this cached data is outdated so it dumps it and perform a hard disk read again?
Finally, assuming I have this query SELECT * FROM table1 WHERE id = 10 After the record is cached in memory and a process is trying to read it, does SQL Server place a Shared lock on that record in memory or there is no locks in memory?

A: The short answer is no, you can't turn off Memory Caching at the server level. The engine takes care of memory Caching for you and it is very aggressive in how it caches, you basically want all queries returned from memory and not from disk. The buffer is orders of magnitude faster than disk access.
Check out these articles which explain how the caching works - known as buffer pool in SQL Server speak.
https://dba.stackexchange.com/questions/43572/how-to-see-what-is-cached-in-memory-in-sql-server-2008
Also anything by Paul Randal is pretty definitive - http://www.sqlskills.com/blogs/paul/inside-the-storage-engine-whats-in-the-buffer-pool/
In terms of locking, this is a commonly asked question on SO. In simple terms the default behaviour is that SQL Server uses Shared locks for readers. So multiple readers can access the data at the same time. SQL Server uses a dynamic locking strategy which escalates locks as needed typically from page level to table level but may de-escalate to row level locks if it sees fit. However this is done dynamically and is automatically handled by the SQL Server engine.  here is an article on this topic - https://technet.microsoft.com/en-us/library/ms189286(v=sql.105).aspx
Also this question has been asked a lot at SO before so check out this link What are row, page and table locks? And when they are acquired?
and others


text:
Q: React Native ScrollView Sticky View Element I'm trying to get an element in a scrollview to always stay to the left of the screen. Kinda like the number rows in Excel. They stay to the left when scrolling horizontally but scroll also down when scrolled vertically. So far I tried animating the element by hooking up the onscroll element to it. It does work but it feels very choppy. It is fast but not fluid. Almost looks like the element is vibrating.
Are there any other techniques in react native to get the desired result? Here the important lines I'm using.
scrollPositionX: new Animated.Value(0),

scrollEventThrottle={16}
onScroll={Animated.event([{nativeEvent: {contentOffset: {x: this.state.scrollPositionX}}}] )}

<Animated.View style={[styles.times, {
     transform: [{translateX: this.state.scrollPositionX}]
}]}>
   ...
</Animated.View>

A: A crude way to do it is to render the sticky columns outside of the horizontal ScrollView. Just make sure your stick and non sticky cells end up being the same height so everything lines up.
If you want to scroll vertically as well, wrap them both inside of another ScrollView.
<ScrollView>
  <View>
    // render the sticky cells
  </View>
  <ScrollView horizontal={true}>
    // render the non sticky cells
  </ScrollView>
</ScrollView>

The problem is that if you have a lot of rows, especially with more complex components within them, you'll have performance issues.
ListViews are better at handling lots of data, but I haven't found a way to make use of them for this scenario. You'd need one for both the sticky column and normal cells, and there's no way to keep them in sync without watching onScroll as you're doing.
I'm hoping someone has better way to do this though. I really need this functionality as well.


text:
Q: Get subset of array and list from list of index I have a numpy array X and a python list y whose elements correspond. I have a partial list of indexes which I would like to use to form another array refinedX and refinedY.
For example, if the partial list contained 0,1 and X=[[1,2],[3,4],[5,6]] and y=[1,2,1], I want refiendX = [[1,2], [3,4]] and refinedY = [1,2].
How can I do this in python?
Note: The actual variable X is a (2000,5000) matrix and the partial list will contain around 500 items.

A: I've written some code that does the job.
X=[[1,2],[3,4],[5,6]]
Y=[1,2,1]
indexes = [1,2]
refinedX = [X[i-1] for i in indexes]
refinedY = [Y[i-1] for i in indexes]

If you will regularly update indexes this may be resource heavy so in that case I'd suggest to use this instead:
X[indexes[i]-1] #instead of refinedX[i]

for each time you call a certain value.


text:
Q: How can I use OWIN Authentication with Microsoft account? Currently I am using OWIN authentication in my application. I am using Tenant as common. So, it is authenticating any user from azure active directory as well as Microsoft account.
I want to restrict user only for Microsoft account.
Below is my web.config file
<add key="ClientId" value="<client id>" />
<add key="RedirectUri" value="https://localhost:44384/" />
<add key="Tenant" value="common" />
<add key="Authority" value="https://login.microsoftonline.com/{0}/v2.0" />

code from Startup.cs
public class Startup
{
    // The Client ID is used by the application to uniquely identify itself
    //to Azure AD.

    string clientId =
System.Configuration.ConfigurationManager.AppSettings["ClientId"];

    // RedirectUri is the URL where the user will be redirected to after
    //they sign in.
    string redirectUri =
    System.Configuration.ConfigurationManager.AppSettings["RedirectUri"];

    // Tenant is the tenant ID (e.g. contoso.onmicrosoft.com, or 'common'
    //for multi-tenant)
    static string tenant =
    System.Configuration.ConfigurationManager.AppSettings["Tenant"];

    // Authority is the URL for authority, composed by Azure Active
    //Directory v2 endpoint and the tenant name (e.g.
    //https://login.microsoftonline.com/contoso.onmicrosoft.com/v2.0)

    string authority =
    String.Format(System.Globalization.CultureInfo.InvariantCulture,
    System.Configuration.ConfigurationManager.AppSettings["Authority"],
    tenant);

    /// <summary>
    /// Configure OWIN to use OpenIdConnect
    /// </summary>
    /// <param name="app"></param>
    public void Configuration(IAppBuilder app)
    {
    app.SetDefaultSignInAsAuthenticationType
    (CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions());

        //app.UseMicrosoftAccountAuthentication(clientId: "", clientSecret:
   "");

        app.UseOpenIdConnectAuthentication(
        new OpenIdConnectAuthenticationOptions
        {
                // Sets the ClientId, authority, RedirectUri as obtained
                //from web.config
                ClientId = clientId,
            Authority = authority,
            RedirectUri = redirectUri,
                // PostLogoutRedirectUri is the page that users will be
     //redirected to after sign-out. In this case, it is using the home page
                PostLogoutRedirectUri = redirectUri,
            Scope = OpenIdConnectScopes.OpenIdProfile,
                // ResponseType is set to request the id_token - which
   //contains basic information about the signed-in user
                ResponseType = OpenIdConnectResponseTypes.IdToken,
                // ValidateIssuer set to false to allow personal and work accounts from any organization to sign in to your application
                // To only allow users from a single organizations, set ValidateIssuer to true and 'tenant' setting in web.config to the tenant name
                // To allow users from only a list of specific organizations, set ValidateIssuer to true and use ValidIssuers parameter
                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters() { ValidateIssuer = false },
                // OpenIdConnectAuthenticationNotifications configures OWIN
  //to send notification of failed authentications to OnAuthenticationFailed
 //method
                Notifications = new OpenIdConnectAuthenticationNotifications
            {
                AuthenticationFailed = OnAuthenticationFailed
            }
        }
    );

    }

    /// <summary>
    /// Handle failed authentication requests by redirecting the user to the
    //home page with an error in the query string
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>

 private Task OnAuthenticationFailed
 (AuthenticationFailedNotification<OpenIdConnectMessage,
 OpenIdConnectAuthenticationOptions> context)
    {
        context.HandleResponse();
        context.Response.Redirect("/?errormessage=" +
        context.Exception.Message);
        return Task.FromResult(0);
    }
}

How Can I restrict only for Microsoft authentication(for user 'user@outlook.com')?

A: To allows only users with personal Microsoft accounts (MSA) to sign into the application, we need to use consumers instead of common as the value of tenant in the authority.
More detailed about this parameters, please refer the link below:
v2.0 Protocols - OAuth 2.0 Authorization Code Flow
Update
app.UseOpenIdConnectAuthentication(
    new OpenIdConnectAuthenticationOptions
    {
        // The `Authority` represents the v2.0 endpoint - https://login.microsoftonline.com/common/v2.0
        // The `Scope` describes the initial permissions that your app will need.  See https://azure.microsoft.com/documentation/articles/active-directory-v2-scopes/
        ClientId = clientId,
        //Authority = String.Format(CultureInfo.InvariantCulture, aadInstance, "adnewfei.onmicrosoft.com", "/v2.0"),
        Authority = String.Format(CultureInfo.InvariantCulture, aadInstance, "common", "/v2.0"),
        RedirectUri = redirectUri,
        Scope = "openid email profile offline_access Mail.Read User.Read",
        PostLogoutRedirectUri = redirectUri,
        TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = false,

        },
        Notifications = new OpenIdConnectAuthenticationNotifications
        {
            // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
            AuthorizationCodeReceived = async (context) =>
            {
                var code = context.Code;
                string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                ConfidentialClientApplication cca = new ConfidentialClientApplication(clientId, redirectUri,
                   new ClientCredential(appKey),
                   new MSALSessionCache(signedInUserID, context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase));
                string[] scopes = { "Mail.Read User.Read" };
                try
                {
                    AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(scopes, code);
                }
                catch (Exception eee)
                {

                }
            },
            AuthenticationFailed = (notification) =>
            {
                notification.HandleResponse();
                notification.Response.Redirect("/Error?message=" + notification.Exception.Message);
                return Task.FromResult(0);
            },
            SecurityTokenValidated = (context) => {
                if (context.AuthenticationTicket.Identity.Claims.First(claim => claim.Type == "preferred_username").Value == "xxxx@hotmail.com")
                {

                }
                else
                {
                    throw new System.IdentityModel.Tokens.SecurityTokenValidationException();
                }
                return Task.FromResult(0);
            },
        },
    });


text:
Q: Trigger slice mouseover on Google Interactive Chart I'm creating a custom legend for my Google pie chart because I need a little more control.
I would like my legend to interact with the chart exactly the same as the default legend.  I can add listeners to my legend rows that select the corresponding slice like:
myChart.setSelection([{row: selectedIdx]);

That causes the slice to select as if I'd clicked the slice, that is to say, it renders the hard line a few pixels away from the slice.
Which is okay, but what I really want is to replicate the slice mouseover, i.e. just the "highlight" of the slice.
I thought the chart might be listening for a mouseover and then examining the event to determine which slice to highlight, so I attached an onmouseover listener to it.  That seemed correct because when I moused over a pie slice, the even passed in was:
Object {row: 1, column: null}

In my legend row listener, I then triggered the chart mouseover and passed in the same event:
google.visualization.events.trigger(myChart, 'onmouseover', {row: selectedIndex, column: null});

But that didn't work. I also tried by explicitly creating a JS object as well as using parseInt on the selected index.  In the Firefox debugger, both things (actual mouseover, legend trigger) looked exactly the same from the point of view of the listener, but only the actual mouseover caused the slice to highlight.
Which leaves me stumped.  Anyone have an idea how to do this?  Ideally, I'm looking for something like:
var slice = myChart.getSlice(someIndex);
slice.setHighlighted();

Thank you

A: I am afraid this is not possible with Google Charts. However you can write code to explode the slice rather than highlighting. It does the same thing from a user's perspective IMO.


text:
Q: How to make append child write html in seperate line instead of one line? I have a button that appends an input element. Whenever I do this the innerHTML return
<input><input><input>

I'd like it to append each new input on a new line as such
<input>
<input>
<input>

I've tried creating a text node = " "
I've also tried looking for the symbol for the return key so i could append this before the input element but I can't seem to find it
HTML:
<!DOCTYPE html>

  <form id="formID">
    <input type="number">
    <input type="number">
    <input type="button" id="addButton" value="Add Element">
  </form>

JS:
let addButton = document.getElementById("addButton");
let form = document.getElementById("formID");
addButton.onclick = function test() {
  let input = document.createElement("input");
  form.appendChild(input);
};

I'm want an innerHTML similar to the below

instead of

A: You can simply use the
 element to append every input on next line .

Try out the following code ,
    <!DOCTYPE html>

    <title></title>

    <!DOCTYPE html>

  <form id="formID">
    <input type="number">
    <input type="number">
    <input type="button" id="addButton" value="Add Element">
  </form>

A: <!DOCTYPE html>

    <title></title>

    <!DOCTYPE html>

  <form id="formID">
    <input type="number">
    <input type="number">
    <input type="button" id="addButton" value="Add Element">
  </form>

this will output the following in the console
<input type="number">
        <input type="number">
        <input type="button" id="addButton" value="Add Element">

<input>
<input>
<input>

the last line being caused by the button
Is it possible for the innerHTML to appear this way?
<input type="number">
<input type="number">
<input type="button" id="addButton" value="Add Element">

<input>

<input>

A: If you want you can add a div content in order to move down also the button:

   <form id="formID">

          <input type="number">
          <input type="number">

      <input type="button" id="addButton" value="Add Element">
  </form>

and the js is this:
  let addButton = document.getElementById("addButton");
  let contenitor = document.getElementById("contenitor");
  addButton.onclick = function test() {
      let input = document.createElement("input");
      let br = document.createElement("BR");
      contenitor.appendChild(br);
      contenitor.appendChild(input);
   };

you can use P instead of a BR for having more space


text:
Q: "To a sweeter more beautiful girl I could not say 'Merry Christmas'" Does anyone know what "To a sweeter more beautiful girl I could not say 'Merry Christmas'" is meant to mean? I'm guessing "There's no sweeter, more beautiful girl I could say 'Merry Christmas' to" but how doe the logic go? Does it mean if there was a sweeter, more beautiful girl, I wouldn't say 'Merry Christmas' to her?

A: What if it was meant to be a poem of sorts:
To a sweeter, more beautiful girl I could not say,
'Merry Christmas.' Love, Ray

A: It's just putting the prepositional phrase first. A more common (we could say 'normal') word order is

I could not say 'Merry Christmas' to a sweeter more beautiful girl.

The meaning is that no sweeter more beautiful girl exists for me to say 'Merry Christmas' to.
If the speaker is addressing this girl than there is an implied than you in the original, my rewrite, and in the  sentence giving the meaning.


text:
Q: Post-process multi-class predictions for image segmentation? My FCN is trained to detect 10 different classes and produces an output of 500x500x10 with each of the final dimensions being the prediction probabilities for a different class.
Usually, I've seen using a uniform threshold, for instance 0.5, to binarize the probability matrices. However, in my case, this doesn't quite cut it because the IoU for some of the classes increases when the threshold is 0.3 and for other classes it is 0.8.
Hence, I don't have to arbitrarily pick the threshold for each class but rather use a more probabilistic approach to finalizing the threshold values. I thought of using CRFs but this also requires the thresholding to have already been done. Any ideas on how to proceed?
Example: consider an image of a forest with 5 different birds. Now im trying to output an image that has segmented the forest and the five birds, 6 classes, each with a separate label. The network outputs 6 confusion matrices indicating the confidence that a pixel falls into a particular class. Now, the correct answer for a pixel isnt always the class  with the highest confidence value. Therefore, a one size fits all method or a max value method won't work.

A: CRF Postprocessing Approch
You don't need to set thresholds to use a CRF. I'm not familiar with any python libraries for CRFs, but in principle, what you need to define is:

*

*A probability distribution of the 10 classes for each of the nodes
(pixels), which is simply the output of your network.

*Pairwise potentials: 10*10 matrix, where element Aij denotes the "strength" of the configuration that one pixel is of class i and the other of class j. If you set the potentials to have a value alpha (alpha >> 1) in the diagonal and 1 elsewhere, then alpha is the regularization force that gives you consistency of the predictions (if pixel X is of class Y, then the neighboring pixels of X are more likely to be of the same class).

This is just one example of how you can define your CRF.
End to End NN Approach
Add a loss to your network that will penalize pixels that have neighbors of a different class. Please note that you will still end up with a tune-able parameter for the weight of the new regularization loss.


text:
Q: React: Are classes without state still considered stateless/pure? I've been refactoring my app to make more components stateless/pure components; i.e., they're just functions. However, I noticed that some components will need to connect with the redux store via mapStateToProps. Which causes me to do something like this:
const someComp = (props) => {
  const {
    funcFromReduxStore,
  } = props;

  return (
    ...
    <SomeComponent
      func={ funcFromReduxStore(myArgs) }
    ...
  );
};

This will not work because I am executing funcFromReduxStore. An easy solution is to wrap the prop in an arrow function. However, this causes many unnecessary re-renders b/c the function won't be bound.
The question then becomes: How do I bind a function in a stateless component?
Is it still stateless if I make it a class, without a constructor, and create a class instance field as so:
class someComp extends React.Component {
  const {
    funcFromReduxStore,
  } = this.props,

  wrapper = (x) => funcFromReduxStore(x) // equivalent way to bind w/ ES8+

  render() {
    ...
    <SomeCompnent
      func={ wrapper(myArgs) }/>
    ...
  }
}

I don't have a constructor, nor state. I want to keep the comopnent stateless, but I also want to bind the function to avoid unncessary re-renders. I also want to continue to keep it stateless b/c React has stated there will be performance benefits for stateless comopnents. Does this qualify as a workaround?

A: Short answer, no. Stateless functional components need to be simple functions.
You should take a look at the Recompose library for some really cool helpers that allow you to beef up your SFCs.
If you're trying to prevent unnecessary re-renders, you could look into onlyUpdateForKeys() or pure().
EDIT: So, I've been thinking about this a bit more and found this really great article on React component rendering performance. One of the key points in that article that pertains to your question:

Stateless components are internally wrapped in a class without any optimizations currently applied, according to Dan Abramov.

From a tweet in July 2016
So it appears that I was wrong. "Stateless Functional Components" are classes...for now. The confusing thing is that there have been performance improvements theorized:

In the future, we'll also be able to make performance optimizations specific to these components by avoiding unnecessary checks and memory allocations.

At this point, I think the answer to your question becomes largely subjective. When you make a class that extends a React Component, any instances of your class get the setStateprototype method. Meaning you have the ability to set state. So does that mean it's stateful even if you're not using state? Thanks to @Jordan for the link to the code. SFCs only get a render method on the prototype when they are wrapped in a class by React.
To your point about wanting to bind functions, there's only two reasons I can think of that you'd want to bind the function:

*

*To give the function access to this (the instance of the component). From your example, it doesn't seem like you need that.

*To ensure that the function passed as a prop to a child component always retains the same identity. The wrapper function in your example seems unnecessary. The identity of the function is determined by the parent component (or mapStateToProps, or whatever HOC).

You should also take a look at React's PureComponent which does the same kind of shallow checking that the pure() HOC from recompose does.


text:
Q: boto s3 bucket object filter with prefix and delimiter I have a bucket with the following key structure:
path/to/file1
path/to/file2
path/of/file3
path/of/file4

And I would like to be able to get the list of "folders" inside path. The actual use case has many "subfolders", so I need to filter the listing. Ideally, I only want to receive two entries: to and of.
Using boto3, I was expecting the two following calls being basically equal, i.e. that the listing of both yields the same result:
Using the bucket returned by the S3 resource
s3 = boto3.resouce('s3')
bucket = s3.Bucket('bucketname')
bucket.objects.filter(Prefix='path/', Delimiter='/').all()

and the underlying client
s3 = boto3.resouce('s3')
s3.meta.client.list_objects(Bucket='path', Prefix='', Delimiter='/')

However, the first returns an emtpy list, while the second returns a JSON with the CommonPrefixes key having the two entries.
Question: What do I miss?

A: from https://github.com/boto/boto3/issues/134#issuecomment-116766812

The reason that it is not included in the list of objects returned is
  that the values that you are expecting when you use the delimiter are
  prefixes (e.g. Europe/, North America) and prefixes do not map
  into the object resource interface.


text:
Q: document.form[0] does not work on Firefox function func(){
    with (document.forms[0]){
        inputid.value = "text"; //Works!
        spanid.innerHTML = "text"; //Err, spanid is not defined.
    }
}

This is not working in Firefox but it is in IE7. I debug in Firebug, spanid is not defined, but I can use document.getElementById("spanid") to select this element. I just don't know why? The input element works fine!

A: Shouldn't it be document.forms[0] (notice the s on form)
**EDIT**
Since the answers aren't rolling in on this one, here's my suggestion. Simply it. Use the methods you're familiar with and don't waste time trying to get this to work.
function YourFunction()
{
    var objSpan = document.getElementById([Insert Element ID]);
    var objInput = document.getElementById([Insert Element ID]);

    objSpan.InnerHTML = "text";
    ...
}

A: IE sticks all elements with IDs as properties on the global scope.  Firefox does not do that in standards mode (but does in quirks mode).


text:
Q: rpy2 convert Matrix -> DataFrame I am having difficulty with this seemingly simple operation that I'd assume has been solved previously but I cannot find any examples.
In the R environment @data is of type DataFrame but rpy2 (2.2) is returning a Matrix.  Is there a convirent way to either convert m to a DataFrame or to have the robjects.r(query)  return a DataFrame?
from rpy2.robjects.packages import importr
import rpy2.robjects as robjects

fimport = importr('fImport')

yahooImport = robjects.r('function(x) yahooImport(x)@data')
qqq = yahooImport("QQQ")

print type(qqq)

A: You can try explicitly casting to a data.frame in your yahooImport function.
The following worked for me:
>>> yahooImport = robjects.r('function(x) as.data.frame(yahooImport(x)@data)')

>>> print type(qqq)
<class 'rpy2.robjects.vectors.DataFrame'>
>>> qqq
<DataFrame - Python:0x102412680 / R:0x103c2b310>
[Float..., Float..., Float..., Float..., Float..., Float...]
  Open: <class 'rpy2.robjects.vectors.FloatVector'>
  <FloatVector - Python:0x10241a638 / R:0x1048f1c00>
[58.970000, 58.660000, 59.180000, ..., 102.250000, 102.870000, 102.250000]
  High: <class 'rpy2.robjects.vectors.FloatVector'>
  <FloatVector - Python:0x10241acf8 / R:0x104916000>
[59.700000, 59.320000, 59.190000, ..., 102.310000, 103.470000, 102.310000]
  Low: <class 'rpy2.robjects.vectors.FloatVector'>
  <FloatVector - Python:0x10241add0 / R:0x10491c200>
[58.920000, 58.340000, 58.500000, ..., 99.310000, 100.620000, 100.560000]
  Close: <class 'rpy2.robjects.vectors.FloatVector'>
  <FloatVector - Python:0x10241aef0 / R:0x10486f800>
[59.600000, 58.990000, 58.600000, ..., 100.120000, 102.620000, 102.120000]
  Volume: <class 'rpy2.robjects.vectors.FloatVector'>
  <FloatVector - Python:0x10241d050 / R:0x104875a00>
[43540100.000000, 70148800.000000, 57085500.000000, ..., 8743600.000000, 9688600.000000, 5232000.000000]
  Adj.Close: <class 'rpy2.robjects.vectors.FloatVector'>
  <FloatVector - Python:0x10241d170 / R:0x10485a000>
[59.600000, 58.990000, 58.600000, ..., 48.110000, 49.320000, 49.080000]

yahooImport returns a timeSeries object which is represented internally as a matrix, which is what is causing your return values in rpy2 to be a matrix.


text:
Q: How do I access objects created during the runtime of a method in rspec? I have a class with a Klass::save method.  This method will create a new instance of Klass, and then call either inst.create or inst.update depending.
I want to write an rspec test like this:
expect(instance_created_within_class_method).to receive(:create)
Can I access an object that is created during the running of the method I'm testing?

A: expect_any_instance_of(Class).to receive(:create) may be what you're looking for.
To call through the method you can add .and_call_original to the end of it.
Check out the RSpec documentation surrounding mocks and expectations: https://relishapp.com/rspec/rspec-mocks/v/2-14/docs/message-expectations/expect-a-message-on-any-instance-of-a-class!


text:
Q: Copy files from Amazon s3 to hadoop I found similar questions, but none of them answers my question: Where should I store the credentials when moving files between Hadoop and S3 using hadoop distcp or s3-dist-cp?
I created a new Amazon EMR cluster and now I want to copy files from a S3 bucket. The following approaches do not work:

*

*Using hadoop distcp
I encoded the credentials within the url like that: hadoop distcp s3n://<awsaccesskey>:<awssecrectkey>@<backetname>/path hdfs://<path> but it seems like the software is not able to handle aws secret keys containing a + or a /, which is quite often the case. Encoding the keys using url encode does not work, but yields to another error like:

java.lang.IllegalArgumentException: Bucket name must not be formatted as an IP Address

or

java.lang.IllegalArgumentException: Bucket name should not contain uppercase characters

*Using s3-dist-cp
So I used the "better" approach, but with the same result.

How can I encode the credentials or where to store them if they contain special chars? I also tried ENV variables (e.g. AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY) without success. Some tutorials mention a core-site.xml file, but no location. So I searched for it and there are multiple matches. The tutorials say that it's mandatory to copy this files to all nodes, but why?

A: Did you try URL encoding the key with special characters?

A: Try below:
AWS_ACCESS_KEY_ID=<awsaccesskey>
AWS_SECRET_ACCESS_KEY=<awssecrectkey>
hadoop distcp -Dfs.s3a.access.key="${AWS_ACCESS_KEY_ID}" -Dfs.s3a.secret.key="${AWS_SECRET_ACCESS_KEY}" s3a://<bucketname>/<path> <hdfs_path>


text:
Q: Rename all files in a Unix Directory with a different date format Can u please let me know how i can change all  Filenames in a Unix Directory as follows:
From : *_mmddyyyy.xls
To  : *_yyyymmdd.xls
Thanks,

A: ls *.xls | while read f; do
  base=${f%_*}
  mdy=${f#*_}
  mdy=${mdy%.xls}
  y=${mdy#????}
  md=${mdy%????}
  mv $f $base_$y$md.xls
done

or:
ls *.xls > old
sed 's/_\(....\)\(....\)/_\2\1/' old > new
paste old new | while read b n; do mv $b $n; done

A: for i in *_mmddyyyy.xls ; do mv "$i" `echo "$i" | sed -e 's/^\(.*_\)\([0-9][0-9][0-9][0-9]\)\([0-9][0-9]\)\([0-9][0-9]\)\(\.xls\)$/\1\4\2\3\5/'` ; done

Use "echo" instead of "mv" until you are sure the loop is producing the correct results -- either of us could have typos.


text:
Q: Unity2D - Non Uniform Jump, Jumping Too High I'm building a 2D platforming game in Unity 5 for school using C#. Sometimes, when my character goes to jump the jump is incredibly high. It doesn't happen with any regularity or in any particular placement. At first I was using AddForce and then I tried to just change the Y velocity on the rigidbody2D but it didn't fix the problem. I moved the jump code from Update to FixedUpdate but that only made the jump less responsive. I'm using GetKeyDown so that the force is not applied the entire time the key is down. I've used Debug.Log and run several tests to make sure that the jump code is not executing multiple times per key press. I read that it could have something to do with how the ground is detected but I can set grounded to false in several places in the jump code but it still does not help. I've moved the code used to detect ground from FixedUpdate to Update to LateUpdate but to no avail. Below is my jump code and the code I am using to detect ground.
in LateUpdate() grounded = Physics2D.OverlapCircle(GroundCheck.position, groundRadius, whatIsGround);               //Use proper variables to check for ground and set grounded bool accordingly

in Update()//JUMPING-----------------------------------------------------------------------
    if (grounded &&                                     //If the player is on the ground,
        Input.GetKeyDown(KeyCode.Space) &&              //and the jump button is pressed,
        RanaAnim.GetBool("Blocking") == false &&        //and Rana is not blocking,
        !attacking)                                     //or performing an attack
        //&& GameManager.InputAllowed)                  //and the game is not paused...
    {
        if (GameManager.characterSwitch)                                    //If Rana is the active character...
        {
            gameObject.GetComponent<AudioSource>().clip = RanaJump;         //Prime Rana's jump audio clip
            gameObject.GetComponent<AudioSource>().Play();                  //Play Rana's jump audio clip
        }
        else                                                                //If Haroun is the active character...
        {
            gameObject.GetComponent<AudioSource>().clip = HarounJump;       //Prime Haroun's jump audio clip
            gameObject.GetComponent<AudioSource>().Play();                  //Play Haroun's jump audio clip
        }

        HarounAnim.SetBool("Ground", false);            //Communicate jumping to Haroun's Animator
        RanaAnim.SetBool("Ground", false);              //Communicate jumping to Rana's Animator

        GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, 0);                //Zero out vertical velocity
        GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, jumpForce));                                             //Assign jump strength via AddForce on Y axis (Jumpforce Settings: Haroun|1670 Rana|4000)
        //GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, jumpForce);      //Jump Strength via velocity on Y axis (Jumpforce Settings: Haroun|25 Rana|75)
    }

A bit more background on this: The player has two playable characters that are interchangeable at any time. One is named Haroun and the other Rana, hence the multiple character references. Haroun and Rana are their own separate objects with their own sprite renderers and colliders which are switched off and on with a boolean. Both the Rana and Haroun objects are child objects to the Character object that this script is attached to.


text:
Q: Swift Admob reward based video ad integration and testing I've successfully been able to integrate both banner ads and image based interstitial ads into my applications with no problems.
I'm considering adding a reward based video ad however I'm not sure if I can simply set up the code as per the interstitial ad but change the adUnitID to that of the rewarded video ad I set up in Admob?
When I do just that the test ad showing an interstitial therefore I can't tell if a video would display.
I'm finding very little guidance to follow online with regard to setting it up this way.
This is what I currently use:
    func loadAndShow3() {

    let request = GADRequest()
    request.testDevices = [kGADSimulatorID, "XXXX"]
    myAd = GADInterstitial(adUnitID: "XXXX")
    myAd.delegate = self
    myAd.load(request)

}

func interstitialDidReceiveAd(_ ad: GADInterstitial) {

    if (self.myAd.isReady) {

        myAd.present(fromRootViewController: self)

    }
 func displayAd() {

    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "loadAndShow"), object: nil)

}

A: Your current code would not work. You would have to make a new request for a GADRewardBasedVideoAd instead of the GADRequest(). There is a really good tutorial made by Google at how to do that attached below. If you follow the tutorial it's a rather straight forward solution. Best of luck to you.
Google's tutorial.