text:
Q: Ruby 1.8.7: intercepting chained methods for object I have a class that is wrapping cells of arbitrary data; sort of a filter.  The cells live in a backend datastore. but that should be as transparent as possible.
Writing straightforward accessors is simple enough:
def foo
  # fetch backend cell value and return it
end
def foo=(val)
  # store val in backend cell
end

The part I'm finding tricky is intercepting and tracking methods that would ordinarily affect the data if it weren't wrapped.  For instance, if the data is an array, obj.foo << 17 would add an element to the array in situ.  I want to maintain that behaviour on the data stored in the backend (i.e., obj.foo << 17 results in the stored value having an element added as well).  I thought perhaps a method_missing would help:
def method_missing(meth, *args)
  methsym = meth.to_sym
  curval = self.get
  lastval = curval.clone
  opresult = curval.__send__(methsym, *args)
  if (curval != lastval)
    self.set(curval)
  end
  return opresult
end

but in combination with the reader accessor, control of the operation has moved beyond me because the thing it returns is not the thing itself.  (I.e., if the backend data is an array, I'm returning a copy of it, and it's the copy that's being modified and never sent back to me.)
Is this possible?  If so, how can I do it?  (It's probably painfully obvious and I'm just missing it because I'm tired -- or maybe not. :-)
Thanks!
[edited]
To put it another way..  #method_missing allows you to hook into the invocation process for unknown methods.  I'm looking for a way to hook into the invocation process similarly, but for all methods, known and unknown.
Thanks!

A: You'd need to wrap each object returned by your class inside a meta object which is aware of the  backend, and could update it as needed.
In your example, you'd need to return an array wrapper object which could handle inserts, deletes, etc.
--- Edit ---
Instead of creating lots of wrapper classes, you may be able to add a 'singleton method' to the returned objects, especially if you can easily identify the methods that might need special handling.
module BackEndIF
  alias :old_send :__send__
  def __send__ method, *args
    if MethodsThatNeedSpecialHandling.include?(method)
       doSpecialHandling()
    else
      old_send(method,args)
    end
  end
end

#in your class:
def foo
   data = Backend.fetch(query)
   data.extend(BackEndIF)
   return data
end

I don't think anything based on method-missing will work, since the objects you are returning do have the methods in question.  (i.e. Array does have an operator<<, it's not missing)
Or, maybe you can do something with a method_missing like the one you outline.
Create a single meta_object something like this:
class DBobject
   def initialize(value, db_reference)
      @value = value
      @ref = db_reference
    end
   def method_missing(meth, *args)
     old_val = @value
     result = @value.__send__(meth, *args)
     DatabaseUpdate(@ref, @value) if (@value != old_val)
     return result
   end
end

Then foo returns a DBObject.new(objectFromDB, referenceToDB).

A: I solved this by borrowing from the Delegator module.  (Code that follows is not guaranteed to work; I've edited out some details by hand.  But it should supply the gist.)

*

*On a fetch (reader accessor), annotate the value to be passed back with modified methods:
def enwrap(target)
  #
  # Shamelessly cadged from delegator.rb
  #
  eigenklass = eval('class << target ; self ; end')
  preserved = ::Kernel.public_instance_methods(false)
  preserved -= [ 'to_s', 'to_a', 'inspect', '==', '=~', '===' ]
  swbd = {}
  target.instance_variable_set(:@_method_map, swbd)
  target.instance_variable_set(:@_datatype, target.class)
  for t in self.class.ancestors
    preserved |= t.public_instance_methods(false)
    preserved |= t.private_instance_methods(false)
    preserved |= t.protected_instance_methods(false)
  end
  preserved << 'singleton_method_added'
  target.methods.each do |method|
    next if (preserved.include?(method))
    swbd[method] = target.method(method.to_sym)
    target.instance_eval(<<-EOS)
      def #{method}(*args, &block)
        iniself = self.clone
        result = @_method_map['#{method}'].call(*args, &block)
        if (self != iniself)
          #
          # Store the changed entity
          #
          newklass = self.class
          iniklass = iniself.instance_variable_get(:@_datatype)
          unless (self.kind_of?(iniklass))
            begin
              raise RuntimeError('Class mismatch')
            rescue RuntimeError
              if ($@)
                $@.delete_if { |s|
                  %r"\A#{Regexp.quote(__FILE__)}:\d+:in `" =~ s
                }
              end
              raise
            end
          end
          # update back end here
        end
        return result
      end
    EOS
  end
end                         # End of def enwrap

*On a store (writer accessor), strip the singleton methods we added:
def unwrap(target)
  remap = target.instance_variable_get(:@_method_map)
  return nil unless (remap.kind_of?(Hash))
  remap.keys.each do |method|
    begin
      eval("class << target ; remove_method(:#{method}) ; end")
    rescue
    end
  end
  target.instance_variable_set(:@_method_map, nil)
  target.instance_variable_set(:@_datatype, nil)
end                        # End of def unwrap

So when the value is requested, it gets 'wrapper' methods added to it before being returned, and the singletons are removed before anything is stored in the back end.  Any operations that change the value will also update the back end as a side-effect.
There are some unfortunate side-side-effects of this technique as currently implemented.  Assume that the class with the wrapped variables is instantiated in backend, and that one of the variables is accessed via ivar_foo:
backend.ivar_foo
=> nil
backend.ivar_foo = [1, 2, 3]
=> [1,2,3]
bar = backend.ivar_foo
=> [1,2,3]
bar << 4
=> [1,2,3,4]
backend.ivar_foo = 'string'
=> "string"
bar
=> [1,2,3,4]
backend.ivar_foo
=> "string"
bar.pop
=> 4
bar
=> [1,2,3]
backend.ivar_foo
=> [1,2,3]

But that's more of a curiousity than a problem for me at the moment. :-)
Thanks for the help and suggestions!


text:
Q: segmentation fault (core dumped) in binary search tree I am trying to implement a r&b tree, but firstly I want a simple binary tree (which does not save content on its leaves) and then implement r&b properties. Problem is I get segmentation fault I cannot explain.
Program is as follows:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <stdbool.h>

typedef struct node
{
    unsigned long int val;
    bool black;
    struct node* parent;
    struct node* lchild;
    struct node* rchild;
}mynode;

mynode* createNode(unsigned long int ival, mynode* father);
mynode* createLeaf(unsigned long int ival, mynode* father);
mynode* search (unsigned long int ival, mynode *root);
void insert ( unsigned long int ival, mynode *root);

int main()
{
    mynode root;
    mynode *rootptr;
    mynode *leafptr;
    FILE *fp;
    int ch;
    unsigned long long lines=0, i=0;
    unsigned long *myArr;
    unsigned long int ival;

   fp = fopen("integers.txt","r");
   if(fp == NULL)
   {
      printf("Error in opening file.");
      return(-1);
   }

    while(!feof(fp))
    {
    ch = fgetc(fp);
    if(ch == '\n')
    {
        lines++;
    }
    }
    lines++;
    printf("lines = %lu", lines);
    myArr = (unsigned long*)calloc(lines, sizeof(unsigned long));

    fseek(fp, 0, SEEK_SET);
    while(!feof(fp))
    {
          fscanf(fp, "%lu,", &myArr[i] ); // des ta pos k giati tou input.
          i++;
    }
    fclose(fp);

    root.val = myArr[0];
    root.parent = NULL;
    root.lchild = NULL;
    root.rchild = NULL;
    root.black = true;
    rootptr = &root;
    leafptr = createLeaf(rootptr->val, rootptr);
    rootptr->lchild = leafptr;
    leafptr = createLeaf(rootptr->val, rootptr);
    rootptr->rchild = leafptr;
    for(i=1; i<lines; i++)
    {
        ival = myArr[i];
        insert(ival, rootptr);
    }

    return 0;
}

mynode* createNode(unsigned long int ival, mynode* father)
{
  mynode* nodeptr;
  mynode node;
  nodeptr = &node;
  nodeptr->val = ival;
  nodeptr->lchild = NULL;
  nodeptr->rchild = NULL;
  nodeptr->parent = father;
  nodeptr->black = true;
  return nodeptr;
}

mynode* createLeaf(unsigned long int ival, mynode* father)
{
  mynode* nodeptr;
  mynode leaf;
  nodeptr = &leaf;
  nodeptr->val = ival;
  nodeptr->lchild = NULL;
  nodeptr->rchild = NULL;
  nodeptr->parent = father;
  nodeptr->black = true;
  return nodeptr;
}

mynode* search (unsigned long int ival, mynode *rootptr)
{
    mynode* myptr;

    myptr = rootptr;

    while ( ( (myptr->lchild) != NULL) && ( (myptr->rchild) != NULL))
    {
        if ( ival < myptr->val)
        {
            myptr = myptr->lchild;
        }
        else
        {
            myptr = myptr->rchild;
        }
    }
    return myptr;
    }

void insert (unsigned long int ival, mynode *root)
{
    mynode * current;
    mynode * leafptr;
    mynode * father;
    unsigned long int max, min;
    unsigned long int num;

    current = search(ival, root);
    num = current->val;
    if((current->val) == ival)
    {
        return ;
    }
    else
    {
        if(ival>(current->val))
        {
            max = ival;
            min = current->val;
        }
        else
        {
            max = current->val;
            min = ival;
        }
        father = current->parent;
        current = createNode(min, father);
        if(num == (father->lchild)->val)
        {
            father->lchild = current;
        }
        else
        {
            father->rchild = current;
        }
        leafptr = createLeaf(min, current);
        current->lchild = leafptr;
        leafptr = createLeaf(max, current);
        current->rchild = leafptr;
       return ;
    }
}

I open a file. Count the number of lines, because I know each line has one number. Create an array using the above information. I then create the root and its 2 leaves. And then I insert (there I get segmentantion fault) rest of the array to my data structure. I think problem lies in the functions.
Here is the text file with numbers.

A: mynode* nodeptr;
mynode node;
nodeptr = &node;

Here node lives on the stack in memory that will be reclaimed at function exit. You're returning a pointer to memory that you do not own! You'll want to use the function malloc(), like so:
mynode* nodeptr = malloc(sizeof(mynode));

This will allocate memory on the heap that nodeptr will point to. This memory will not be reclaimed on function exit. To reclaim this memory, you will need to call free().

A: Just too many bugs and issues to go thorough.
Let us instead look at a proper example, with error checking, that outputs the generated binary search tree in Graphviz DOT format.
First, you'll want to keep the pointers at the beginning of the structure, because they are most used, and require proper alignment. (If you do not put the biggest members first, the compiler may insert padding into your structures, wasting memory. No, the compiler is not allowed to reorder the structure members in C, so it cannot do that for you.)
#include <stdlib.h>
#include <stdio.h>

struct node {
    struct node *parent;
    struct node *left;
    struct node *right;
    double       value;
};

Next, we need a function for creating a new node. It is a good idea to check for malloc() returning NULL, and if so, abort the program:
struct node *new_node(const double value)
{
    struct node *n;

    n = malloc(sizeof (struct node));
    if (!n) {
        fprintf(stderr, "Out of memory.\n");
        exit(EXIT_FAILURE);
    }

    n->parent = NULL;
    n->left = NULL;
    n->right = NULL;
    n->value = value;

    return n;
}

Next, you need a function that will insert a node into a tree. The tree itself is just the handle to its root member, and since the new node can be the new root, we need to pass a pointer to the pointer to the root element:
void insert_node(struct node **root, struct node *leaf)
{
    struct node *parent;

    /* Make sure we have a pointer to the root pointer, and a leaf node. */
    if (!root) {
        fprintf(stderr, "insert_node(): root == NULL!\n");
        exit(EXIT_FAILURE);
    }
    if (!leaf) {
        fprintf(stderr, "insert_node(): leaf == NULL!\n");
        exit(EXIT_FAILURE);
    }

    /* Make sure leaf pointers are all NULL. */
    leaf->parent = NULL;
    leaf->left = NULL;
    leaf->right = NULL;

The above code is just sanity checks, but I wanted to include them for completeness.  Anyway, if the tree is empty, the root pointer points to a NULL pointer, i.e. *root == NULL. In this case, the leaf is the new (sole) node in the tree:
    /* Is this a new root node? */
    if (!*root) {
        /* Yes. */
        *root = leaf;
        return;
    }

Otherwise, we need to descend into the tree. I've decided that left means "less than or equal to", because it is easy to remember. If we are going left, and parent's left node is empty, that is where we'll put the new leaf node. Similarly, if we are going right, and parent's right node is empty, we put the leaf there. Otherwise we descend.
    /* Find the parent node where leaf belongs. */
    parent = *root;
    while (1)
        if (parent->value >= leaf->value) {
            if (parent->left) {
                parent = parent->left;
                continue;
            }

            /* This belongs at parent->left. */
            parent->left = leaf;
            leaf->parent = parent;
            return;

        } else {
            if (parent->right) {
                parent = parent->right;
                continue;
            }

            /* This belongs at parent->right. */
            parent->right = leaf;
            leaf->parent = parent;
            return;
        }
}

To traverse the tree, and print its structure in DOT language, one needs just two functions: a recursive function to print the node, and a main function to print the boilerplate, and to call the recursive function. I use %p or node pointer value as the node identifiers, because it is simple and reliable:
static void dot_recurse(FILE *out, struct node *one)
{
    fprintf(out, "    \"%p\" [ label=\"%.3f\" ];\n", (void *)one, one->value);

    if (one->parent)
        fprintf(out, "    \"%p\" -> \"%p\";\n", (void *)one, (void *)(one->parent));

    if (one->left) {
        dot_recurse(out, one->left);
        fprintf(out, "    \"%p\" -> \"%p\" [ label=\"≤\" ];\n", (void *)one, (void *)(one->left));
    }

    if (one->right) {
        dot_recurse(out, one->right);
        fprintf(out, "    \"%p\" -> \"%p\" [ label=\">\" ];\n", (void *)one, (void *)(one->right));
    }
}

void dot(FILE *out, struct node *tree)
{
    if (out && tree) {
        fprintf(out, "digraph {\n");
        dot_recurse(out, tree);
        fprintf(out, "}\n");
    }
}

Above, arrows to parent will be unlabeled, arrows to left child will be labeled ≤, and arrows to right child will be labeled > near the middle of the arrow.
Note that for dot(), the first parameter is the stream the file will be emitted to, and the second parameter is a pointer to the root node. Because we do not modify the tree, the pointer to the root node suffices; we do not need a pointer to a pointer to the root node here.
Finally, we need to read values from a stream (here, standard input), and construct a tree node from each parsed value, and insert them to the tree. There is absolutely no reason to read the file twice, as the number of values is irrelevant: we can simply read values until we cannot!
int main(void)
{
    struct node *tree = NULL;
    double       value;

    while (scanf(" %lf", &value) == 1)
        insert_node(&tree, new_node(value));

    /* Dump tree in DOT format. Use Graphviz to visualize the output. */
    dot(stdout, tree);

    return EXIT_SUCCESS;
}

The latter part of main() just dumps the tree in DOT format to standard output, and exits (successfully).  It is not necessary to free dynamically allocated memory prior to exiting, as the operating system will do that automatically.
Let's say we have an input file in.txt containing
4.695 5.108 3.518 4.698 8.496
7.956 9.435 5.341 0.583 7.074
7.661 5.966 0.557 4.332 1.436
6.170 7.936 4.630 7.694 0.220

and we executed our program, piping that file to its standard input, and piping the output to say out.dot. (In Linux, Mac OS, and BSDs, this would be just ./binary < in.txt > out.dot, after compiling the above C source to an executable named binary in the current directory.)
The out.dot will then contain
digraph {
    "0x13dd020" [ label="4.695" ];
    "0x13dd080" [ label="3.518" ];
    "0x13dd080" -> "0x13dd020";
    "0x13dd1a0" [ label="0.583" ];
    "0x13dd1a0" -> "0x13dd080";
    "0x13dd260" [ label="0.557" ];
    "0x13dd260" -> "0x13dd1a0";
    "0x13dd3b0" [ label="0.220" ];
    "0x13dd3b0" -> "0x13dd260";
    "0x13dd260" -> "0x13dd3b0" [ label="≤" ];
    "0x13dd1a0" -> "0x13dd260" [ label="≤" ];
    "0x13dd2c0" [ label="1.436" ];
    "0x13dd2c0" -> "0x13dd1a0";
    "0x13dd1a0" -> "0x13dd2c0" [ label=">" ];
    "0x13dd080" -> "0x13dd1a0" [ label="≤" ];
    "0x13dd290" [ label="4.332" ];
    "0x13dd290" -> "0x13dd080";
    "0x13dd350" [ label="4.630" ];
    "0x13dd350" -> "0x13dd290";
    "0x13dd290" -> "0x13dd350" [ label=">" ];
    "0x13dd080" -> "0x13dd290" [ label=">" ];
    "0x13dd020" -> "0x13dd080" [ label="≤" ];
    "0x13dd050" [ label="5.108" ];
    "0x13dd050" -> "0x13dd020";
    "0x13dd0b0" [ label="4.698" ];
    "0x13dd0b0" -> "0x13dd050";
    "0x13dd050" -> "0x13dd0b0" [ label="≤" ];
    "0x13dd0e0" [ label="8.496" ];
    "0x13dd0e0" -> "0x13dd050";
    "0x13dd110" [ label="7.956" ];
    "0x13dd110" -> "0x13dd0e0";
    "0x13dd170" [ label="5.341" ];
    "0x13dd170" -> "0x13dd110";
    "0x13dd1d0" [ label="7.074" ];
    "0x13dd1d0" -> "0x13dd170";
    "0x13dd230" [ label="5.966" ];
    "0x13dd230" -> "0x13dd1d0";
    "0x13dd2f0" [ label="6.170" ];
    "0x13dd2f0" -> "0x13dd230";
    "0x13dd230" -> "0x13dd2f0" [ label=">" ];
    "0x13dd1d0" -> "0x13dd230" [ label="≤" ];
    "0x13dd200" [ label="7.661" ];
    "0x13dd200" -> "0x13dd1d0";
    "0x13dd320" [ label="7.936" ];
    "0x13dd320" -> "0x13dd200";
    "0x13dd380" [ label="7.694" ];
    "0x13dd380" -> "0x13dd320";
    "0x13dd320" -> "0x13dd380" [ label="≤" ];
    "0x13dd200" -> "0x13dd320" [ label=">" ];
    "0x13dd1d0" -> "0x13dd200" [ label=">" ];
    "0x13dd170" -> "0x13dd1d0" [ label=">" ];
    "0x13dd110" -> "0x13dd170" [ label="≤" ];
    "0x13dd0e0" -> "0x13dd110" [ label="≤" ];
    "0x13dd140" [ label="9.435" ];
    "0x13dd140" -> "0x13dd0e0";
    "0x13dd0e0" -> "0x13dd140" [ label=">" ];
    "0x13dd050" -> "0x13dd0e0" [ label=">" ];
    "0x13dd020" -> "0x13dd050" [ label=">" ];
}

and if visualized (using e.g. dot -Tsvg out.dot > out.svg), will look like this:

As you can see, each left child is equal to or less than its parent, and each right child is greater than its parent. Using DOT language output like this is an excellent method of debugging tree functions, too; you can even use node shape (oval or rectangle, for example) to indicate red/black -- or use actual colors. The DOT attribute list is here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Stop CSV import into Excel from converting text to time I have a CSV file that contains headers in the format of "1 A", "2 A", "3 A", etc. When I import the file they get converted to 1:00 AM, 2:00 AM, 3:00 AM and so on.
What can I do to prevent this? Do I have to change the format of the text in some way so that Excel will leave it as is? If so what do I need to add?

A: I agree with David, enclosing values in double quotes should make Excel treat column Values as text, but with a Column Header - who knows.
One possible solution:
During the import wizard you might try changing the value for "Start import at row" =2, and then ensuring the "Column data format" is Text. Then you can manually enter the column header names.
From: http://office.microsoft.com/en-us/excel-help/text-import-wizard-HP010102244.aspx

A: I am also facing same problem and I get rid off by following funda
First Convert in into UTF - 8
If user is using windows add BOM(Byte Order Mark)
If user using MAC or other OS (Remove BOM)
var is_Mac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;
if (is_Mac) {
    var csvData = csv;
}
else {
    var BOM = "\uFEFF";
    var csvData = BOM + csv;
}
var csvFile = new Blob([csvData], { type: "text/csv;charset=utf-8" });
var urlHref = URL.createObjectURL(csvFile);

Hope this will resolve your issue


text:
Q: Setting custom control properties I though it would be very simple but I can not get it today.
I have a user control, with a grid control contained in it.
public Unit Width
{
    get
    {
        return CustomerGrid.Width;
    }
    set
    {
        CustomerGrid.Width = value;

    }
}

I expose the width property and when I set it in the designer it works at run-time but not design time.
What class do I inherit from or method to override to get my controls to function at design time.
Note I tried to inherit from WebControl but got the message
Make sure that the class defined in this code file matches the 'inherits' attribute, and that it extends the correct base class

A: I understand you're talking about user controls (ascx) and not about custom controls (no ascx). If this is the case, you should inherits from UserControl and you would have the property available on design time without any other addition.
In case you're talink about custom controls, here you have a good article about adding design time support to custom controls
http://msdn.microsoft.com/en-us/library/aa478960.aspx


text:
Q: DataTable auto generated serial numbering not working properly.. for every pages DataTable paging procedure not  showing continuous index numbers...! Now am showing 10 items per page, For the first page the Data-table serial numbering generates correctly from 1-10.. But every pages shows from 1 to 10 numbering, need to display continuous numbering from the second page, like 11,12... Am using the following code for Datatable.
Any help would be appreciable,
Thank you
<script>

            $(document).ready(function(){
                var t = $("#table_details").DataTable({

                    "pagingType" : "full_numbers",
                    "processing" : true,
                    "searching"  : true,
                    "serverSide" : true,
                    "ajax" :{"url" : "../dataTable/serversideContacts.php",
                             "type": "post",
                             "data": { "uid" :'.$uid.',"gid" :'.$group_id.',"sid" :'.$site_id.'},

                            },

                    "columnDefs": [ {"searchable": false,"orderable": false,"targets": [0,3,4]} ],
                    "order": [[ 1, "asc" ]],
                    "language": {
              "info": "Showing page _PAGE_ of _PAGES_"
                          }

                });

                t.on( "order.dt search.dt processing.dt", function (){

                    t.column(0,{ search:"applied", order:"applied" }).nodes().each( function (cell, i)
                    {cell.innerHTML = i+1; });
                }).draw();
            });
        </script>

A: Answer is based on the following: Alert the page no. on jQuery dataTables page change event
(assuming per page = 10)
dTable.on( 'order.dt search.dt processing.dt page.dt', function () {
    dTable.column(1, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
        cell.innerHTML = i+1;
        var info = table.page.info();
        var page = info.page+1;
        if (page >'1') {
            hal = (page-1) *10;  // u can change this value of ur page
            cell.innerHTML = hal+i+1;
        }
    } );
} ).draw();

Hope this helps.

A: For DataTables >= 1.10.4,
"fnCreatedRow": function (row, data, index) {
                $('td', row).eq(0).html(index + 1);
            }

hope this will help :)


text:
Q: Decrypting RSA using OpenSSL.NET with Existing Key I have the following code below to generate an OpenSSL RSA public and private key using OpenSSL.Net. However, I can't seem to find a way to decrypt data with a given private key. I know if I call generate keys and then the corresponding methods to encrypt and decrypt the data it works fine. However, if I am trying to decrypt something from an external source given a public key, how can I decrypt using that key.
Note: Please do not give examples that don't use OpenSSL.NET. The Microsoft Cryptographic providers are far slower than OpenSSL and do not meet my speed requirements.
Thanks!
public class AsymmetricKeyResult
{
    public string PublicKey { get; set; }
    public string PrivateKey { get; set; }

    public AsymmetricKeyResult(string publicKey, string privateKey)
    {
        this.PublicKey = publicKey;
        this.PrivateKey = privateKey;
    }
}

public static AsymmetricKeyResult GenerateAsymmetricKeys(int keyLength)
{
    RSA rsa = new RSA();
    rsa.GenerateKeys(keyLength, 0x10021, null, null);
    AsymmetricKeyResult kResult = new AsymmetricKeyResult(rsa.PublicKeyAsPEM, rsa.PrivateKeyAsPEM);

    return kResult;
}

A: I ended up figuring it out through the object browser on the Managed Wrapper for OpenSSL.NET. This works:
    public static byte[] AsymmetricEncrypt(string publicKeyAsPem, byte[] payload)
    {
        CryptoKey d = CryptoKey.FromPublicKey(publicKeyAsPem, null);
        RSA rsa = d.GetRSA();
        byte[] result = rsa.PublicEncrypt(payload, RSA.Padding.PKCS1);
        rsa.Dispose();
        return result;
    }

    public static byte[] AsymmetricDecrypt(string privateKeyAsPem, byte[] payload)
    {
        CryptoKey d = CryptoKey.FromPrivateKey(privateKeyAsPem, null);
        RSA rsa = d.GetRSA();
        byte[] result = rsa.PrivateDecrypt(payload, RSA.Padding.PKCS1);
        rsa.Dispose();
        return result;
    }

A: I found this and thought it was the answer to my prayers. However using openssl (1.0.0e Mac os x) to generate pub/priv keys, i cannot get the clear text back again from the encrypted text - is there a GetBytes/Baseencode type step I'm missing? did you come across this?
EDIT: no sooner had i posted i then came across a different example using UTF8 encoding not ASCII, which works!
Ben
namespace testopenssl2
{
class Program
{

    public static byte[] AsymmetricEncrypt(string publicKeyAsPem, byte[] payload)
    {
        CryptoKey d = CryptoKey.FromPublicKey(publicKeyAsPem, null);
        RSA rsa = d.GetRSA();
        byte[] result = rsa.PublicEncrypt(payload, RSA.Padding.PKCS1);
        rsa.Dispose();
        return result;
    }

    public static byte[] AsymmetricDecrypt(string privateKeyAsPem, byte[] payload)
    {
        //CryptoKey d = CryptoKey.FromPrivateKey(privateKeyAsPem, null);
        CryptoKey d = CryptoKey.FromPrivateKey(privateKeyAsPem, "pass");
        RSA rsa = d.GetRSA();
        byte[] result = rsa.PrivateDecrypt(payload, RSA.Padding.PKCS1);
        rsa.Dispose();
        return result;
    }

    static void Main(string[] args)
    {
        String t = @"-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCbhcU+fhYmYLESZQAj1hKBXsNY
si0kYHNkxpP7ftxZiTFowWUVXHzQgkcYiCNnp3pt1eG6Vt0WDzyFYXqUUqugvX41
gkaIrKQw/sRiWEx49krcz7Vxr3dufL6Mg3eK7NyWDGsqwFrx/qVNqdhsHg12PGNx
IMY4UBtxin2A8pd4OwIDAQAB
-----END PUBLIC KEY-----";
        String p = @"-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,0A128C2617BD2EB1

pTDtXB+mockO7fvVqn4fwGnSb1Zv3HaMAALtpiB7Rn64eAHL7psKQIIM3qoshDWF
XgXDdTnMOGO7wtYkd9R7iJYxgt19EuEdtu2SLLXQuN4ll+JSR2R/34dF19iMXI30
d3pe7obTIwKdyRGuu8GgEm6bGai4pkqptP0HRA6qdMI2+Qfl9+VqUuvIm7tfpIRd
/ZLENe756IrGDvI7lGx39Md/H2sgAJsWkSYubhmtxVJ0IEvbPuKDC5V5oLyTOoy+
6sc6ly57C4XHaTLhAKnYEvZAddnXg/e/VtfmTpqKx3n7D6FAKo1RjAjeZqEvefZd
XAhh19YhZq3mdZNYUt7ojUarf/q3zrtTMLUxHdR0Be/VaQC5AE0d6quKyUQgxiti
XNRS8xk9IJJqJLFSHO3ET+oTfcs+kLPuUDHqq0hY/OgW/THcDgPY1cDwtOX9yuI3
YDoFTb3SXzRTmk2ui33f96wNPwzIAp9+TJzITxJYbF233Pz4YWuabrFuoNWZnwtT
E/o6wcGfvAXTQkAKzwfLbTDmg5SSiGokoEcgm7qpfmQxKdmV1LmbW88DuAgdWggm
Qf3ydZ2IrrtD1o+XP7JraeVOql0OK77pJh/bcr3bLiAT8YtsQUZLnOjkbDc3F1zW
BGr6eeqUHxY6cqKieokhl9cBBjWuxJQL2h997svBufWdNOjTA4+32lXzDzi7bUxC
xzIqZ7nm3YC2zUjla/l3Smz5KitqU5Y3Q9URpXOW+qMiPxmTHYOEcRDy9yh2U4iA
CoTD6q0ZNJLEo3EVcDB+26O663/mQLuR69xstUgqHpSzGvXbqrmezA==
-----END RSA PRIVATE KEY-----";

        System.Text.Encoding enc = System.Text.Encoding.ASCII;
        String s = "hello";
        byte[] payload = enc.GetBytes(s);
        Console.WriteLine("s: {0}", s);

        byte[] byte_encData = AsymmetricEncrypt(t,payload);

        String res;
        res = Convert.ToBase64String(byte_encData);
        Console.WriteLine("encypted: {0}", res);

        byte[] byte_decrypted = AsymmetricDecrypt(p, byte_encData);
        String res_unenc;
        res_unenc = Convert.ToBase64String(byte_decrypted);

        // works!
        Console.WriteLine("decrypted: {0}", res_unenc);

    }
    }
}


text:
Q: can $httpbackend be called with different url I have a service that calls a REST URL that returns data.
My sample code would be
$http('POST', '/mockUrl/resource/'+resourceValue).then(...);

My service works fine and it returns data. My problem is how do I test this in karma. Right now I have a different resourceValue to be tested for the mockUrl being called. Before coming to stackoverflow, in each test i was defining $httpBackend with the expected URL.
eg:
it('testing for status 200', function(){
        $httpBackend.when('POST', '/mockUrl/resource/'+1234)
           .respond(function (method, url, data, headers) {
               return [200, data1];
           });

       MyService.serviceMethod(1234).then(function(){
      //test the returned data
      });
   });

it('testing for status 201', function(){
    $httpBackend.when('POST', '/mockUrl/resource/'+4567)
        .respond(function (method, url, data, headers) {
           return [201, data2];
          });

    MyService.serviceMethod(1234).then(function(){
       //test the returned data
    });
 });

I am being told that I should not be writing my karma tests in the above manner. But I am not sure how to avoid that.
I have tried
$httpBackend.when('POST',url)
      .respond(function (method, url, data, headers) {
        return data[option];
      });

But this 'url' never gets called in any test. I am not sure how to proceed further.

A: it seems that you never call $httpBackend.flush(); that is needed to simulate async operations... Plus, you also never use
afterEach(() => {
  $httpBackend.verifyNoOutstandingExpectation();
  $httpBackend.verifyNoOutstandingRequest();
});

Probably you need to have a more in-deep view at https://docs.angularjs.org/api/ngMock/service/$httpBackend


text:
Q: How can I create a jsk file from a pepk file? I left my .jsk file in my other computer, now I only have a .pepk (Keystore) file. Is there a way to get the jsk file back?

A: It depends on what you want to do with the .jsk file, now.
One way could be to generate a new one.
Another obvious way could be to get it back from the other computer, when you can.
But if right now you want to update an app that is already on the Google play console-then you need to get that .jsk file back. There are things that you can do with that .pepk file without having the .jsk file , see here [https://developer.android.com/studio/publish/app-signing]. I just dont think getting back that .jsk file is one of them.


text:
Q: jquery datatables scrollx and multiple-select filter css I use datatables from website : www.datatables.net and multiple-select (http://wenzhixin.net.cn/p/multiple-select/docs/) filter in my datatables. I wrote this code to do this :
this.api().columns().every(function () {

var column = this;

var select = $('<select multiple="multiple" style="width:inherit"><option value=""></option></select>')

.appendTo($(column.header()).empty())

select.append('<option value="value1">value1</option>');
select.append('<option value="value1">value1</option>');
select.append('<option value="value1">value1</option>');
select.append('<option value="value1">value1</option>');
select.append('<option value="value1">value1</option>');
select.append('<option value="value1">value1</option>');

select.multipleSelect({
});
});

I uploaded picture to : http://postimg.org/image/ys0q3ajxx/
which exactly describes my problem.
Sorry for the link, but I am not able to insert a picture because I got error : "You need at least 10 reputation to post images."
Everything is fine and works like a charm.
But problem appears when I use 'scrollX' = true option -> It is needed because I have more than 20 columns to display sometimes !
Problem appears that when I click on this "select" -> the list appears but it is covered by "datatables body rows". This problem does not occur when I use "standard select".
I suppose that this problem is connected with "Css styling", but I do not know how to correct this.
When I turn off "scrollX" option, my multiple-select works fine -> List appears "on the top" of the datatables body, but when "scrollX" is turned on -> this list is covered by "datatables body".
Could you help me how to fix it ?


text:
Q: Mocking SqlQuery with where condition I've been following the answer from this link about how to mock sqlquery call, but when I try to replace the query string with a where condition, it return the all of the object in the list instead of the expected filtered list, is it not possible to filter the object by its property name?
var myObjects = _context
                    .Set<myObject>()
                    .SqlQuery("select * myObject where id = '1'")
                    .AsNoTracking()
                    .ToList();


text:
Q: Is it fine to define a variable after it is used in Less and not before? So, the question actually is if it is just fine to use:
.mytest {
  border:1px solid @black;
}
@black: #000;

instead of
@black: #000;
.mytest {
  border:1px solid @black;
}

I don't see any warnings when I do this and it works fine - the result is
.mytest {
  border: 1px solid #000;
}

for both cases.
Demo

A: Yes, it is absolutely fine to use it that way because Less does lazy loading of variables and so it is not mandatory to declare the variables before they are used. Because of lazy loading, the Less compiler will not throw any errors or warnings for such cases.
As per Less website:

Variables are lazy loaded and do not have to be declared before being used.

In fact, I would even go on to say that declaring variables at the end is more beneficial because all the variables are maintained at one place and it leaves no room for some stray declaration accidentally overriding the expected or intended setting.

A: Yes, you can as Harry said. And i suggest you to create a file just for storing all your variables definitions and import it. In that way you could have differents themes (files) and configure yout project just replacing one file


text:
Q: DLL load failed for pygame When I choose to run the code, I get an error message saying:
Traceback (most recent call last):
  File "C:/Users/MarkKenny/Desktop/GamTut.py", line 4, in <module>
    import pygame, sys
  File "C:\Python33\lib\site-packages\pygame\__init__.py", line 127, in <module>
    from pygame.base import *
ImportError: DLL load failed: %1 is not a valid Win32 application."
>>>

I'm using Python 3.3.4 64bit and using the latest available version of Pygame.
All suggestions/answers would be extremely appreciated.

A: Are you using the 64-bit version of Pygame? You say that you are using 64-bit Python, but you don't state which version of Pygame you are using other than "the latest available version".
Try typing the following into a python shell:
import pygame

If there is no result, pygame is probably installed correctly.
If this error appears, then you have not installed the correct version of pygame for your OS:
ImportError: No module named pygame

There are some unofficial 64-bit pygame binaries here: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame I'm not sure how good they are because I don't have any experience with them, I just use the standard 32-bit version of pygame available here: http://pygame.org/download.shtml


text:
Q: Get value where variable name stored in another variable Without using eval ... I'm trying to see if I can get a value from a variable where the value is stored in another variable. Such as get value of 'ValueC' from varA where varA='varB' and varB='ValueC'
The user will enter a string, simulated below as the variable named 'UserSpecified'.  They could enter any character and if doesn't match an existing variable ... well I'll just return null.
I realize I can do this with an eval(), but evals seem to be frowned upon I'm trying to do it in a better way.
I've tried the ES2015+ accepted answer from "Variable" variables in Javascript? but I'm not having any success.  Am I missing something or should I stick with an eval?

let a  = "aye";
let b = "be";
let c = "sea";

let userSpecified="a";
let obj = {userSpecified};
let parm='userSpecified';

console.log(eval(userSpecified));  // This displays 'aye'

console.log(obj[parm]); // This displays 'a' but I would like it to display 'aye'

A: If you can restructure your code so that an object holds the values, then it's just basic obj.key = val syntax (exactly: obj[key] = val).

const obj = {
  a: "aye",
  b: "be",
  c: "sea"
}

const userSpecified = "a";

console.log(obj[userSpecified]); // expected: aye

If not, then use var instead of let:

// pay attention that it's var not let
var a = "aye";

let userSpecified = "a";

console.log(window[userSpecified]) // expected: aye

A: It is not possible to get the value of a local variable dynamically (aside from eval).
But you can use an object to store data (not the names of local variables), and access that data with dynamic keys.
I think this is what you want:
const data = {
  a: "1",
  b: "2",
  c: "3",
}

// Take the name of an object property and return its corresponding value.
function getValue(userSpecified) {
  return data[userSpecified]
}

console.log(getValue("a")) // 1
console.log(getValue("b")) // 2

console.log(getValue(someFormField.value))


text:
Q: Running Kubernetes Sample Controller I am trying to run the Kubernetes sample controller example by following the link https://github.com/kubernetes/sample-controller. I have the repo set up on an Ubuntu 18.04 system and was able to build the sample-controller package.
However, when I try to run the go package, I am getting some errors and am unable to debug the issue. Can someone please help me with this?
Here are the steps that I followed :
user@ubuntu-user:~$ go get k8s.io/sample-controller
user@ubuntu-user:~$ cd $GOPATH/src/k8s.io/sample-controller

Here's the error that I get on running the controller:
user@ubuntu-user:~/go/src/k8s.io/sample-controller$ ./sample-controller -kubeconfig=$HOME/.kube/config
E0426 15:05:57.721696   31517 reflector.go:125] k8s.io/sample-controller/pkg/generated/informers/externalversions/factory.go:117: Failed to list *v1alpha1.Foo: the server could not find the requested resource (get foos.samplecontroller.k8s.io)

Kubectl Version :
user@ubuntu-user:~$ kubectl version
Client Version: version.Info{Major:"1", Minor:"14", GitVersion:"v1.14.1", GitCommit:"b7394102d6ef778017f2ca4046abbaa23b88c290", GitTreeState:"clean", BuildDate:"2019-04-08T17:11:31Z", GoVersion:"go1.12.1", Compiler:"gc", Platform:"linux/amd64"} Server Version: version.Info{Major:"1", Minor:"14", GitVersion:"v1.14.1", GitCommit:"b7394102d6ef778017f2ca4046abbaa23b88c290", GitTreeState:"clean", BuildDate:"2019-04-08T17:02:58Z", GoVersion:"go1.12.1", Compiler:"gc", Platform:"linux/amd64"```

A: I have reproduced your issue. The order of commands in this tutorial is wrong.
In this case you received this error due to lack of resource (samplecontroller)
$ ./sample-controller -kubeconfig=$HOME/.kube/config
E0430 12:55:05.089624  147744 reflector.go:125] k8s.io/sample-controller/pkg/generated/informers/externalversions/factory.go:117: Failed to list *v1alpha1.Foo: the server could not find the requested resource (get foos.samplecontroller.k8s.io)
^CF0430 12:55:05.643778  147744 main.go:74] Error running controller: failed to wait for caches to sync
goroutine 1 [running]:
k8s.io/klog.stacks(0xc0002feb00, 0xc000282200, 0x66, 0x1f5)
    /usr/local/google/home/user/go/src/k8s.io/klog/klog.go:840 +0xb1
k8s.io/klog.(*loggingT).output(0x2134040, 0xc000000003, 0xc0002e12d0, 0x20afafb, 0x7, 0x4a, 0x0)
    /usr/local/google/home/user/go/src/k8s.io/klog/klog.go:791 +0x303
k8s.io/klog.(*loggingT).printf(0x2134040, 0x3, 0x14720f2, 0x1c, 0xc0003c1f48, 0x1, 0x1)
    /usr/local/google/home/user/go/src/k8s.io/klog/klog.go:690 +0x14e
k8s.io/klog.Fatalf(...)
    /usr/local/google/home/user/go/src/k8s.io/klog/klog.go:1241
main.main()
    /usr/local/google/home/user/go/src/k8s.io/sample-controller/main.go:74 +0x3f5

You can verify that this api was not created
$ kubectl api-versions | grep sample
$ <emptyResult>

In the tutorial you have command to create Custom Resource Definition
$ kubectl create -f artifacts/examples/crd.yaml
customresourcedefinition.apiextensions.k8s.io/foos.samplecontroller.k8s.io created

Now you can search this CRD, it will be on the list now.
$ kubectl api-versions | grep sample
samplecontroller.k8s.io/v1alpha1

Next step is to create Foo resource
$ kubectl create -f artifacts/examples/example-foo.yaml
foo.samplecontroller.k8s.io/example-foo created

Those commands will not create any objects yet.
user@user:~/go/src/k8s.io/sample-controller$ kubectl get all
NAME                 TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)   AGE
service/kubernetes   ClusterIP   XX.XXX.XXX.XX   <none>        443/TCP   14d

All resources will be created after you will run ./sample-controller -kubeconfig=$HOME/.kube/config
user@user:~/go/src/k8s.io/sample-controller$ ./sample-controller -kubeconfig=$HOME/.kube/config
user@user:~/go/src/k8s.io/sample-controller$ kubectl get all
NAME                               READY   STATUS    RESTARTS   AGE
pod/example-foo-6cbc69bf5d-8k59h   1/1     Running   0          43s

NAME                 TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)   AGE
service/kubernetes   ClusterIP   10.39.240.1   <none>        443/TCP   14d

NAME                          DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/example-foo   1         1         1            1           43s

NAME                                     DESIRED   CURRENT   READY   AGE
replicaset.apps/example-foo-6cbc69bf5d   1         1         1       43s

Correct order:
$ go get k8s.io/sample-controller
$ cd $GOPATH/src/k8s.io/sample-controller
$ go build -o sample-controller .
$ kubectl create -f artifacts/examples/crd.yaml
$ kubectl create -f artifacts/examples/example-foo.yaml
$ ./sample-controller -kubeconfig=$HOME/.kube/config
$ kubectl get deployments

A: Did you run those two commands from readme?
# create a CustomResourceDefinition
kubectl create -f artifacts/examples/crd.yaml

# create a custom resource of type Foo
kubectl create -f artifacts/examples/example-foo.yaml


text:
Q: 'flutter test' running on docker image causing testfile.dill.track.dill change and then causing test failure on CI environment I'm having unit test erros running flutter test in a gitlab-ci environment. Below is a complete list of things I've already done trying to solve the issue, but haven't found a solution so far. I've opened an issue in github/flutter wondering if it might actually be a bug in flutter, but would be very glad to hear from you if any other suggestions are made. All logs are in GitHub issue, if needed in this question.
Steps to Reproduce
Due to proprietary reasons, I can't paste all my flutter code. I'll try to be as detailed as possible to help in the solution, and feel free to ask for more details.
The main objective is to have flutter test running on gitlab-ci, on a docker image. Therefore, I created a local docker image on my MacBook (Dockerfile is included below and was also pushed to Docker Hub) to reproduce and debug the failure.

*

*Run docker pull isorensen/flutter-ubuntu:1.12.13-stable

*Run docker run -v [flutter_project_root_directory]:/app -it --rm isorensen/flutter-ubuntu:1.12.13-stable

*Run flutter test on the Docker image. Run at least twice, since, as you'll see below, the first command might succeed and actually cause further tests to fail.

Expected results:
00:09 +14: All tests passed!
Actual results:
00:12 +0 -1: faq:  check if has values [E]
  type 'MappedListIterable<MapEntry<int, dynamic>, dynamic>' is not a subtype of type 'List<dynamic>' in type cast
  package:credifit/API/client.dart 307:80  ApiClient.getFaqs

00:12 +0 -2: faq:  check first default question [E]
  type 'MappedListIterable<MapEntry<int, dynamic>, dynamic>' is not a subtype of type 'List<dynamic>' in type cast
  package:credifit/API/client.dart 307:80  ApiClient.getFaqs

00:18 +10 -3: getUserLoanInfos [E]
  Instance of 'Fatal'
  package:sdkgen_runtime/http_client.dart 30:5   SdkgenHttpClient._throwError
  package:sdkgen_runtime/http_client.dart 82:15  SdkgenHttpClient.makeRequest

00:19 +10 -4: simulateInstallments [E]
  type 'MappedListIterable<MapEntry<int, dynamic>, dynamic>' is not a subtype of type 'List<dynamic>' in type cast
  package:credifit/API/client.dart 313:236  ApiClient.simulateInstallments

00:19 +10 -4: Some tests failed.

What seems to be the problem
Since this problem does not occur on my local environment (running macOS Catalina, as detailed in logs below), what I noticed, running fswatch in my project folder and running flutter test in both environments (sharing the same project directory), only two files were "touched" (not necessarily changed):
- .packages
- .testfile.dill.track.dill
And after running diff on both files, before and after flutter test, noticed only testfile.dill.track.dill was changed.
Finally, when I did the sequence below, it made flutter test run successfully, concluding the error is being caused after a change in testfile.dill.track.dill cased by flutter test inside the docker image.

*

*Run flutter test on macOS (sharing the same project directory with docker image)

*Run cp build/testfile.dill.track.dill ~ to save a copy of the file

*Run flutter test on docker vm (the first time, the test runs successfully, but it alters test file.dill.track.dill)

*Run diff build/testfile.dill.track.dill ~/testfile.dill.track.dill
The result: Binary files build/testfile.dill.track.dill and /Users/eduardosorensen/testfile.dill.track.dill differ

*Run flutter test on docker vm
The test above fails

*Run cp ~/testfile.dill.track.dill build/testfile.dill.track.dill (to revert changed file)

*Run flutter test on docker vm
The test above is successfully, although it changes again testfile.dill.track.dill and starts failing again on further tests

A: It was a problem of flutter package versions.
When you create a docker image and run flutter pub get it builds the packages from scratch, and therefore upgrading some packages with minor updates.
This may cause a different of versions between local and docker image.
So make sure you run tests with the same environment, locally and dockerized.


text:
Q: If Banach space $C(K)$ is decomposable (non trivial) then $C(K)$ is isomorphic to some of the sumands subspaces In  Beauzamy  (Banach spaces) book  appears  this  statement  without proof: "if $X\oplus Y$ is isomorphic to Banach space $C(K)$ then either $X$ or $Y$ is isomorphic to $C(K)$''  where $X$, $Y$ are Banach  spaces and $C(K)$ is  the  Banach space  of  continuous  real-valued functions defined on the compact Hausdorff topological space $K$, endowed  with sup norm.
I would appreciate some help about how to prove it.

A: It seems to be a non-trivial result.
A Banach space $X$ is primary if whenever $X$ is
isomorphic to $Y \oplus Z$ (for some Banach spaces $Y$ and $Z$), then $X$ is isomorphic to $Y$ or
to $Z$.
In the paper:  J. Lindenstrauss and A. Pełczynski, Contributions to the theory of the classical Banach spaces, J. Funct.
Anal. 8 (1971), 225–249, it is shown that $C[0,1]$ is primary. Any $C(K)$ space with $K$ uncountable metric and compact is isomorphic to $C[0,1]$ (this is known as Miljutin's Theorem; a proof can be found in Albiac and Kalton's Topics in Banach Space theory). So, $C(K)$ is primary whenever $K$ is uncountable metric and compact.
In the papers: D.E. Alspach and Y. Benyamini, Primariness of spaces of continuous functions on ordinals, Israel J. Math.
27 (1977), 64–92 and   P. Billard, Sur la primarité des espaces C(α), Studia Math. 62 (2) (1978), 143–162 (French), it is shown that $C(K)$ is primary whenever $K$ is countable and compact.
The above (with a different proof that $C[0,1]$ is primary) is contained in Rosenthal's article in The Handbook of the Geometry of Banach Spaces, Vol II.
I don't know of any references for the case where   $K$ is uncountable, compact, Hausdorff, but not metrizable. (In this case, $C(K)$ is not separable.)


text:
Q: .dot template and angular or what should I use here? This is a generic question don't need the "ready to use" code , but an idea where should invest my time in. I set mustache tag because may be similar.
This is an express (4) application using .doT template where i want to expand with some angular (1.4.3) features.

*

*Doesn't seem possible to me to work with .doT template and angularjs , I'm i right here? .I'm trying get it to work a .html template file and his angular application without success( return a 404 cause don't find a template, but when i use with ejs, it does work ( because it read .html files)

2 . STILL , would like to know in case i'm wrong above. considering this anwer that state is possible to use multiple view engine with consolidate. is possible and how would it be done with angular? (just a hint, doens't need to be the whole implementation)

*I know by this answer would be possible to use this below, but also says is better to use a helper, is possible to use helpers in.doT template ? , how?
appModule.config(function($interpolateProvider) {
  $interpolateProvider.startSymbol('{[{');
  $interpolateProvider.endSymbol('}]}');
});

*considering the above. Which one of 2 and 3 whould you say would be faster?

*it would considerably be faster if I change my app to ejs view engine ?

A: Point by point :

*

*This is incorrect , .doT template works well with Angular, I have use it both, as long as you render a route with dot.
 router.get("/blog/new", function(req, res) {
     res.render("owner/blog/create");
 });

and set a state in your angular provider like
  $stateProvider
   ...
    .state("owner-new-blog", {
        url: "/blog/new",
        templateUrl: "/owner/blog/new",
        controller: "CreateUpdateCtrl"
    })

*There is no point to use consolidate middleware, .doT template works with angular template out of the box, unless you change .doT default parameters.

*Yes ... that would be like this , like state in this post
var dT = require('doT');
var tpl = {
     tmpl:dT.template('{{=this.helper()}}'),
     helper: function(){
         /* do what you want to do */
     }
}
tpl.tmpl(); // render template

*as you can see in this benchmark , .doT is pretty fast if you set double engine in you app , is a bit slowe since you are expanded is functionallity, if you set a helper in doT is less painfull than having two engines .. so , is faster adding a Helper to dot.

*there is no point in changing  to ejs , dot is pretty fast and an advance template engines which suport layouts and partials. and still , in my opinion, is faster.


text:
Q: tera wallet not showing at checkout/order-pay/ wordpress when we try to make payment using checkout url "checkout/order-pay/?{order-id}=true&key={key}" which is obtain by custom api, tera wallet option not displaying
when we try same with web it shows tera wallet option but not with checkout url obtain by custom api


text:
Q: Is there electric potential outside a grounded sphere with charge inside? Say I have a point charge put inside a grounded sphere. The rest of space is charge-free. Is there still any electric potential outside the sphere?

A: Yes, by Gauss' law there is an E-field outside the sphere and therefore there is a spatially varying potential.
Note, by your description the sphere must be an uncharged sphere of a non-conductive material

A: If it is a grounded sphere, the potential on the surface of the sphere will be zero. Then, by the uniqueness theorem, the potential and field outside the sphere will be zero.


text:
Q: material ui datagrid onSortModelChange infinite loop material ui datagrid onSortModelChange infinite loop when use this.setState
I'm using material-ui in React class Component
when in onSortModelChange property of DataGrid use 'this.setState', An infinite loop is created.
How do I solve the problem?
Thank you


text:
Q: Is Blaze-Persistence Querydsl integration support projections? How to use Projections with Blaze-Persistence Querydsl?
And in bellow example when criteria.getEmail() give me NullPointerException.
So How I can overcome NullPointerException for more wheres?
cbf.create(em, WalletReportDto.class)
                .fromSubquery(WalletCTE.class, "offerCTO").from(TenantBalanceOffers.class, "tbo")
                .bind("walletId").select("tbo.wallet.id")
                .bind("amount").select("SUM(tbo.amount)")
                .groupBy("tbo.wallet.id").end()

                .joinOn(TenantWallet.class, "tw", JoinType.INNER)
                .onExpression("offerCTO.walletId = tw.id")
                .end() //

                .select("MIN(tw.createdDate)", "fromtDate").select("MAX(tw.createdDate)", "toDate")

                .select("tw.customer.email", "email")
                .select("sum(offerCTO.amount)").where("tw.customer.email").eq(criteria.getEmail())

                .groupBy("tw.id")

                .getResultList();

A: You need to use the Blaze-Persistence Querydsl integration to use Querydsl projections with Blaze-Persistence's query features.
List<WalletReportDto> result = new BlazeJPAQuery<>(em, cbf)
    .from(new BlazeJPAQuery<>()
          .from(QTenantBlanceOffers.tenantBlanceOffers)
          .bind(QWalletCTE.walletCTE.walletId, QTenantBlanceOffers.tenantBlanceOffers.wallet.id)
          .bind(QWalletCTE.walletCTE.amount, QTenantBlanceOffers.tenantBlanceOffers.amount.sum())
    , QWalletCTE.walletCTE)
    .innerJoin(QTenantWallet.tenantWallet)
    .on(QTenantWallet.tenantWallet.id.eq(QWalletCTE.walletCTE.walletId))
    .transform(Projections.bean(
        WalletReportDto.class,
        QTenantWallet.tenantWallet.createdDate.min(),
        QTenantWallet.tenantWallet.createdDate.max(),
        QTenantWallet.tenantWallet.customer.email,
        QWalletCTE.walletCTE.id
    )


text:
Q: javax Mail gets the same message multpile times my application opens an IMAPFolder and the first time gets the messages with folder.getMessages, then i store the UID that will be assigned to the next message in a member variable: nextUID=folder.getUIDNext();
When i open the folder again, i use folder.getMessagesByUID(nextUID, folder.LASTUID); but even though there has been no new mail since the first time, it still returns an 1-element array containg the mail that was already there the first time. How can in only get the new mails?

A: From the JavaDoc : LASTUID
          This is a special value that can be used as the end parameter in getMessagesByUID(start, end), to denote the UID of the last message in the folder.
Therefore although your start parameter refers to a non-existent UID, the use of LASTUID causes the latest message to be retreived again, as it is in range.


text:
Q: How do I display the child elements of Firebase Realtime Database in a RecyclerView? I am developing an ecommerce application and I want to display the list of products in an order done by the customer. I am able to display the details of the order but unable to display the list of products in that order.
Please see the image below. I want to display those 2 products with their details in a RecyclerView.

Here is my code
databaseReference.child("Orders").child(shopId).child(orderId).orderByChild(orderId).equalTo(orderId)
        .addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        ArrayList<PlaceOrder> placeOrderArrayList = new ArrayList<>();
        for (DataSnapshot ds : dataSnapshot.getChildren()){
            placeOrderArrayList.add(ds.getValue(PlaceOrder.class));
        }
        UserOrderDetailsAdapter userOrderDetailsAdapter = new UserOrderDetailsAdapter(UserOrderDetailsActivity.this,placeOrderArrayList);
        productsRv.setAdapter(userOrderDetailsAdapter);
        userOrderDetailsAdapter.notifyDataSetChanged();
    }

    @Override
    public void onCancelled(@NonNull DatabaseError error) {

    }
});

A: You need to order on the child named "orderId", not on the value of the orderId variable:
databaseReference.child("Orders").child(shopId).child(orderId)
   .orderByChild("orderId").equalTo(orderId)

Your data structure is not following the best practices outlined in the Firebase documentation on structuring data. I specifically recommend reading about limiting nesting and flattening data structures, and considering creating two top-level nodes: Orders and OrderItems, each with the $orderId as keys under it. Separating the data types like that is least likely to require changing the data model down the line.


text:
Q: Calibration Asymmetric laplace distribution function I'm trying to fit my data to Asymmetric laplace distribution function as defined in this link https://en.wikipedia.org/wiki/Asymmetric_Laplace_distribution . Unfortunately, I can't find a way to do it with python. I tried to do inheritance but it seems like it doesn't work. Does anyone have a solution please
'''data=np.array([0.936,0.942,0.968,0.981,1.006,1.011,0.996,0.992,0.979,0.976,0.977,0.978,0.987,1.029,1.078,1.188,1.251,1.263,1.284,1.238,1.253,1.219,1.148,1.068,0.971,0.950,0.944,0.941,0.939,0.934,0.947,0,958,1.002,1.043,1.074,1.096,1.095,1.102,1.091,1.074,1.084,1.070,1.060,1.065,1.061,1.045,1.056,1.090,1,121,1.167,1.194,1.196,1.129,1.107,1.114,1.154,1.182,1.144,1.078,0.947,0.872,0.811,0.771,0.756,0.755,0.793,0.837,0.870,0.888,0.859,0.846,0.828,0.808,0.848,0.857,0.891,0.947,0.949,0.963,0.942,0.947,0.922,0.932,0.936,0.922,0.946,0.951,0.978,1.019,1.042,1.054,1.088,1.072,1.080,1.061,1.028,1.028,1.012,1.006,1.040,1.089,1.141,1.156,1.104,1.051,0.995,1.014,1.046,1.058,1.066,1.087,1.129,1.176,1.184,1.107,1.044,1.000,1.004,1.028,1.041,1.008,0.967,0.948,0.923,0.932,0.954,0.958,0.977,1.008,1.024,1.035,1.038,1.008,0.958,0.889,0.815,0.763,0.738,0.804,0.900,0.980,1.052,1.041,.999,0.942,0.928,0.919,0.917,0.950,0.935,0.926,0.923,0.918,0.938,0.946,0.976,1.016,1.041,1.097,1.075,1.050,1.026,0.984,1.000,1.014,1.023,1.022,1.001,0.978,0.969,0.942,0.939,0.933,0.930,0.926,0.919,0.911,0.897,0.904,0.906,0.910,])

class A_Laplace(scipy.stats.rv_continuous):
     def pdf(self, x, location, scale, asym):
            return coef * np.where(x < location,
  np.exp((scale / asym) * (x - location)),
  np.exp(-scale * asym * (x - location))
)

instance=A_Laplace()
instance.fit(data)

A: I believe you have to implement _pdf method as well as argument check.
Along the lines, some (untested!) code
import numpy as np
from scipy.stats import rv_continuous

class A_Laplace(rv_continuous):
    def _argcheck(self, *params):
        """Should truly check parameters"""
        return True

    def _pdf(self, x, m, λ, κ):
        return np.where(x < m, np.exp((λ/κ) * (x - m)), np.exp(-(λ*κ) * (x - m)))*λ/(κ+1.0/κ)

Adding some plotting code
ald = A_Laplace()

x = np.linspace(-3.0, 3.0, 101)

q = ald.pdf(x, 0.0, 1., 2.)

plt.plot(x, q, 'r-')
plt.show()

produced graph just like in Wiki


text:
Q: Loop issues with Less I am trying to create the following Less via a loop.
@brand-gold: #bd9e5e;

&.brand-gold {
 background:@brand-gold;
}
&.brand-gold-20 {
 background: tint(@brand-gold, 80%)
}
&.brand-gold-40 {
 background: tint(@brand-gold, 60%)
}
&.brand-gold-60 {
 background: tint(@brand-gold, 40%)
}
&.brand-gold-80 {
 background: tint(@brand-gold, 20%)
}

I have a number of brand colours and would like to call a mixin/loop with the colour and have it print out the 5 classes.
Could someone help in this please?
Here is my code so far. I am having troubles creating the tint %.
@iterations: 5;
@brand-gold: #bd9e5e;
@brand-black: #231f20;
.brand-scale-loop (@i,@colour,@name) when (@i > 0) {
  &.brand-@{name}-20 { background: tint(@colour, 80%); }
}
.brand-scale-loop(@iterations,@brand-gold,gold);
.brand-scale-loop(@iterations,@brand-black,black);

A: Based on your comment, the below seems to be what you are looking for. You just have to create two variables - one which produces the number that has to be appended in the selector (@sel in snippet) and the other which is an exact inverse (100% - @sel) of the first variable to set as the tint percent.
Additionally since you don't want the number to appended to the selector when it is 0 (or the color to be tinted in such cases), we need to add  guard conditions within the mixin to perform like if statement.
@iterations: 5;
@brand-gold: #bd9e5e;
@brand-black: #231f20;

.brand-scale-loop (@i,@colour,@name) when (@i > 0) {
  @sel: (100 * (@i - 1) / @iterations); /* calculate the number to append in selector */
  @tint: 100% - @sel; /* inverse of the no. from previous step is tint percentage */

  & when (@sel = 0) { /* dont apply tint or add 0 in selector when value is 0 */
    &.brand-@{name} { background: @colour; }
  }
  & when not(@sel = 0) { /* for all other cases append number to selector and tint */
    &.brand-@{name}-@{sel} { background: tint(@colour, @tint);}
  }

  .brand-scale-loop(@i - 1,@brand-gold,@name); /* call for next iteration */

}

/* call as many times as you need with as many values */
/* used the ~"" syntax for color names to be backward compatible. Older Less versions used to convert such names into hex codes in output */

.brand-scale-loop(@iterations,@brand-gold,~"gold");
.brand-scale-loop(@iterations,@brand-black,~"black");


text:
Q: CALayer position and anchorpoint I've already done a lot of work with animating CALayers, but I never really understood the positioning system completely. Most of the time I just try, how it turns out.
I know the anchorPoint of an implicit CALayer is the center of the parent UIView.
Meaning I have to subtract or add 160 to each value I want to animate on the x-axix, or 284 (this does vary due to NavigationBars) on the y-axis.
But I got into a situation which was kinda weird in my eyes. I'll explain it here:
I created a bar on the bottom of the screen, which is 44px heigh. I created it with this frame: CGRectMake(0.0, 568.0, 320.0, 44.0). 524 would be the normal position, 568 is the hidden position.
The animation did not work with these values, neither adding or subtracting 284 solved the issue. I had to experiment a bit, to get it working, this is the working version of my code.
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position.y"];
[animation setFromValue:[NSNumber numberWithFloat:546.0]];
[animation setToValue:[NSNumber numberWithFloat:590.0]];
[animation setDuration:0.3];
[[self layer] addAnimation:animation forKey:@"inAnimation"];
[[self layer] setPosition:CGPointMake(160.0, 590.0)];

This animates the UIView out of the visible area. Why do I have to use 546 instead of 524 for my fromValue and 590 for my toValue. This is a difference of 22px. Why?
Still a miracle.


text:
Q: Number of roots of $p_n-\lambda p_{n-1}$ where $p_n$ are orthogonal polynomials
Let $(p_n)_{n\in\Bbb N}$ be the orthonormal sequence of polynomials associated to a tempered weight $w$ on an interval $I$ (so that for example, $\deg(p_n)=n$). Show that $p_n-\lambda p_{n-1}$ has $n$ distinct roots in $I$ for any real $\lambda$.

I'm stuck at how to prove this.
My attempt at a proof:
Let $l_n:=p_n-\lambda p_{n-1}$
and $r_1,..r_k$ be the roots of odd multiplicity in I.
Let $q=(t-r_1)...(t-r_k)$ . Then $deg(q)=k≤n$. Note that $l_nq$ is either nonpositive or non negative. Hence $<l_n,q>\neq 0$. Since $l_n\in \{p_0,p_1,..,p_{n-2}\}^{perp}$. This implies that $deg(q)≥n-1$. This is where im stuck. Any helps or hints?
After this I have to show that the roots of $p_n$ and $p_{n-1}$ are interlaced. Any hints for that?


text:
Q: Spring LDA: Problem with contextSource Bean I am writing a Spring application that uses LDAP. Here is my beans file.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id="contextSource" class="org.springframework.ldap.core.support.LdapContextSource">
      <property name="url" value="xxxxx:xxx" />
      <property name="base" value="ou=xxxxx,dc=xxxxxxx,dc=xxxxxx" />
      <property name="userDn" value="uid=xxxxxxx" />
      <property name="password" value="xxxxxxxx" />
   </bean>

   <bean id="ldapTemplate" class="org.springframework.ldap.core.LdapTemplate">
      <constructor-arg ref="contextSource" />
   </bean>

   <bean id="helloLdap" class="a.b.c.HelloLdap">
      <property name="ldapTemplate" ref="ldapTemplate" />
   </bean>

</beans>

Here is my beans creation code:
ApplicationContext fac = new ClassPathXmlApplicationContext(
                "a/b/c/ldap.xml");
HelloLdap hello = (HelloLdap) fac.getBean("helloLdap");

Here is my error message:

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'contextSource' defined in class path resource [xxxxxxxxxxxx]: Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'base' threw exception; nested exception is java.lang.NoClassDefFoundError: org/apache/commons/lang/StringUtils

So it says (most importantly):
"Property 'base' threw exception"

I am wondering whether this is because the authentication requires StartTLS. I don't indicate StartTLS authentication anywhere in my beans file, so perhaps that is causing the error. Still, I would expect the authentication to happen after the beans are created, not during their creation.
Does anyone know if that is the cause (StartTLS authentication)? If not, any idea of what I am doing wrong in my XML?

A: The answer is in the error message:

java.lang.NoClassDefFoundError: org/apache/commons/lang/StringUtils

Something in the application requires Apache Commons Lang. Download that, add it to your classpath.

A: I was going through same problem and eventually found this
The recommended way of configuring Spring LDAP is to use the custom XML configuration namespace. To make this available, You need to include the Spring LDAP namespace declaration in your bean file
Note these two lines below: xmlns:ldap="http://www.springframework.org/schema/ldap" and http://www.springframework.org/schema/ldap https://www.springframework.org/schema/ldap/spring-ldap.xsd"
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:ldap="http://www.springframework.org/schema/ldap"
       xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/ldap https://www.springframework.org/schema/ldap/spring-ldap.xsd">

Then you can declare contextSource:
<bean id="contextSource" class="org.springframework.ldap.core.support.LdapContextSource">
    <property name="url" value="xxxxx:xxx" />
    <property name="base" value="ou=xxxxx,dc=xxxxxxx,dc=xxxxxx" />
    <property name="userDn" value="uid=xxxxxxx" />
    <property name="password" value="xxxxxxxx" />
</bean>


text:
Q: can't destroy view of related model I've got a model which is being destroyed in a form view, and I need it to also remove the related element from the list view.
in my form view I have

delete: function(){
        this.model.destroy();
        this.el.remove();
    }

and in my list view I have

initialize: function(){
    this.model.on('remove',this.delete);
},

delete: function(){
   alert('delete');
   this.el.remove();
   this.el.unbind();
}

when I delete the item, the delete in the listView is triggered, but I get an error cannot call method remove of undefined.
I've also tried $(this.el).remove(), but no luck.
The listView is added from the collection in another view with

 itemCollection.each(this.add);

 add: function(){
    var create = new Myapp.Views.Items({model:item});
    $(this.el).append(create.el);
}

A: *

*replace this.el with this.$el

*don't use delete as method name

*change from this.model.on('remove',this.delete); to this.model.on('remove',_.bind(this.delete, this));

*jsbin


text:
Q: Flink 1.12 Could not find any factory for identifier 'kafka' that implements 'org.apache.flink.table.factories.DynamicTableFactory' in the classpath I have a Flink job that runs well locally but fails when I try to flink run the job on cluster. It basically reads from Kafka, do some transformation, and writes to a sink. The error happens when trying to load data from Kafka via 'connector' = 'kafka'.
Here is my pom.xml, note flink-connector-kafka is included.
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>exmple</groupId>
    <artifactId>featurepipelines</artifactId>
    <version>0.1</version>
    <packaging>jar</packaging>

    <name>Feature Pipelines</name>

    <repositories>
        <repository>
            <id>apache.snapshots</id>
            <name>Apache Development Snapshot Repository</name>
            <url>https://repository.apache.org/content/repositories/snapshots/</url>
            <releases>
                <enabled>false</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <flink.version>1.12.0</flink.version>
        <scala.binary.version>2.11</scala.binary.version>
        <scala.version>2.11.12</scala.version>
        <log4j.version>2.12.1</log4j.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-streaming-scala_${scala.binary.version}</artifactId>
            <version>${flink.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-clients_${scala.binary.version}</artifactId>
            <version>${flink.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-table-api-scala-bridge_${scala.binary.version}</artifactId>
            <version>${flink.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-table-planner-blink_${scala.binary.version}</artifactId>
            <version>${flink.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-connector-kafka_${scala.binary.version}</artifactId>
            <version>${flink.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-avro-confluent-registry</artifactId>
            <version>${flink.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-json</artifactId>
            <version>${flink.version}</version>
        </dependency>
        <dependency>
            <groupId>com.typesafe</groupId>
            <artifactId>config</artifactId>
            <version>1.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.bahir</groupId>
            <artifactId>flink-connector-redis_${scala.binary.version}</artifactId>
            <version>1.1-SNAPSHOT</version>
        </dependency>
    </dependencies>

    <profiles>
        <profile>
            <id>testing</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <kafka.source.servers>10.111.135.233:9092,10.111.130.11:9092,10.111.130.12:9092</kafka.source.servers>
                <redis.host>10.106.74.22</redis.host>
                <redis.port>19000</redis.port>
            </properties>
        </profile>
    </profiles>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.2.4</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <!-- 重命名包, 如果不开启, shade生成的jar包为默认包名, 默认生成的jar会被改名 -->
                            <shadedArtifactAttached>false</shadedArtifactAttached>
                            <shadedClassifierName>Shade</shadedClassifierName>
                            <!-- 过滤掉重复依赖 -->
                            <filters>
                                <filter>
                                    <artifact>*:*</artifact>
                                    <excludes>
                                        <exclude>META-INF/*.SF</exclude>
                                        <exclude>META-INF/*.DSA</exclude>
                                        <exclude>META-INF/*.RSA</exclude>
                                    </excludes>
                                </filter>
                            </filters>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>featurepipelines.generation_ingestion.GenerationIngestionJobRunner</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>net.alchim31.maven</groupId>
                <artifactId>scala-maven-plugin</artifactId>
                <version>4.4.1</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>testCompile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

This is the full error log, note the sentence Caused by: org.apache.flink.table.api.ValidationException: Could not find any factory for identifier 'kafka' that implements 'org.apache.flink.table.factories.DynamicTableFactory' in the classpath.
flink run -d -c featurepipelines.generation_ingestion.GenerationIngestionJobRunner -p 1 -yjm 768M -ytm 768M -ys 1 -ynm feat_gen_ingest_user_last_n_clicks -yqu tech_platform -yD metrics.reporter.promgateway.jobName=feat_gen_ingest_user_last_n_clicks-metric- -m yarn-cluster /data/code/feat_gen_ingest_user_last_n_clicks/target/featurepipelines-0.1.jar
submit cmd stdout log:
2021-03-10 20:35:15,015 INFO  org.apache.flink.yarn.cli.FlinkYarnSessionCli                [] - Dynamic Property set: metrics.reporter.promgateway.jobName=feat_gen_ingest_user_last_n_clicks-metric-
2021-03-10 20:35:15,015 INFO  org.apache.flink.yarn.cli.FlinkYarnSessionCli                [] - Dynamic Property set: metrics.reporter.promgateway.jobName=feat_gen_ingest_user_last_n_clicks-metric-
submit cmd stderr log:
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/data/apache/flink/flink-1.12.0/lib/log4j-slf4j-impl-2.12.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/data/apache/hadoop/hadoop-2.7.3/share/hadoop/common/lib/slf4j-log4j12-1.7.10.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.apache.logging.slf4j.Log4jLoggerFactory]

------------------------------------------------------------
 The program finished with the following exception:

org.apache.flink.client.program.ProgramInvocationException: The main method caused an error: Unable to create a source for reading table 'default_catalog.default_database.kafka_source'.

Table options are:

'connector'='kafka'
'format'='json'
'json.fail-on-missing-field'='false'
'properties.bootstrap.servers'='10.111.135.233:9092,10.111.130.11:9092,10.111.130.12:9092'
'properties.group.id'='flink-test2'
'topic'='data-report-stat-old-logtype7'
    at org.apache.flink.client.program.PackagedProgram.callMainMethod(PackagedProgram.java:330)
    at org.apache.flink.client.program.PackagedProgram.invokeInteractiveModeForExecution(PackagedProgram.java:198)
    at org.apache.flink.client.ClientUtils.executeProgram(ClientUtils.java:114)
    at org.apache.flink.client.cli.CliFrontend.executeProgram(CliFrontend.java:743)
    at org.apache.flink.client.cli.CliFrontend.run(CliFrontend.java:242)
    at org.apache.flink.client.cli.CliFrontend.parseAndRun(CliFrontend.java:971)
    at org.apache.flink.client.cli.CliFrontend.lambda$main$10(CliFrontend.java:1047)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1698)
    at org.apache.flink.runtime.security.contexts.HadoopSecurityContext.runSecured(HadoopSecurityContext.java:41)
    at org.apache.flink.client.cli.CliFrontend.main(CliFrontend.java:1047)
Caused by: org.apache.flink.table.api.ValidationException: Unable to create a source for reading table 'default_catalog.default_database.kafka_source'.

Table options are:

'connector'='kafka'
'format'='json'
'json.fail-on-missing-field'='false'
'properties.bootstrap.servers'='10.111.135.233:9092,10.111.130.11:9092,10.111.130.12:9092'
'properties.group.id'='flink-test2'
'topic'='data-report-stat-old-logtype7'
    at org.apache.flink.table.factories.FactoryUtil.createTableSource(FactoryUtil.java:125)
    at org.apache.flink.table.planner.plan.schema.CatalogSourceTable.createDynamicTableSource(CatalogSourceTable.java:265)
    at org.apache.flink.table.planner.plan.schema.CatalogSourceTable.toRel(CatalogSourceTable.java:100)
    at org.apache.calcite.sql2rel.SqlToRelConverter.toRel(SqlToRelConverter.java:3585)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertIdentifier(SqlToRelConverter.java:2507)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2144)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2093)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2050)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertSelectImpl(SqlToRelConverter.java:663)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertSelect(SqlToRelConverter.java:644)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertQueryRecursive(SqlToRelConverter.java:3438)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2169)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2050)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2105)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2050)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertIdentifier(SqlToRelConverter.java:2483)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2144)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2093)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2050)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertSelectImpl(SqlToRelConverter.java:663)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertSelect(SqlToRelConverter.java:644)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertQueryRecursive(SqlToRelConverter.java:3438)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2169)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2050)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2105)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2050)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertIdentifier(SqlToRelConverter.java:2483)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2144)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2093)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2050)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertSelectImpl(SqlToRelConverter.java:663)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertSelect(SqlToRelConverter.java:644)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertQueryRecursive(SqlToRelConverter.java:3438)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2169)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2093)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2050)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertSelectImpl(SqlToRelConverter.java:663)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertSelect(SqlToRelConverter.java:644)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertQueryRecursive(SqlToRelConverter.java:3438)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2169)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2050)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2105)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2050)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertIdentifier(SqlToRelConverter.java:2483)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2144)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2093)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertFrom(SqlToRelConverter.java:2050)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertSelectImpl(SqlToRelConverter.java:663)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertSelect(SqlToRelConverter.java:644)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertQueryRecursive(SqlToRelConverter.java:3438)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertQuery(SqlToRelConverter.java:570)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertWith(SqlToRelConverter.java:4277)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertQueryRecursive(SqlToRelConverter.java:3452)
    at org.apache.calcite.sql2rel.SqlToRelConverter.convertQuery(SqlToRelConverter.java:570)
    at org.apache.flink.table.planner.calcite.FlinkPlannerImpl.org$apache$flink$table$planner$calcite$FlinkPlannerImpl$$rel(FlinkPlannerImpl.scala:165)
    at org.apache.flink.table.planner.calcite.FlinkPlannerImpl.rel(FlinkPlannerImpl.scala:157)
    at org.apache.flink.table.planner.operations.SqlToOperationConverter.toQueryOperation(SqlToOperationConverter.java:823)
    at org.apache.flink.table.planner.operations.SqlToOperationConverter.convertSqlQuery(SqlToOperationConverter.java:795)
    at org.apache.flink.table.planner.operations.SqlToOperationConverter.convert(SqlToOperationConverter.java:250)
    at org.apache.flink.table.planner.delegation.ParserImpl.parse(ParserImpl.java:78)
    at org.apache.flink.table.api.internal.TableEnvironmentImpl.sqlQuery(TableEnvironmentImpl.java:639)
    at featurepipelines.generation_ingestion.GenerationIngestionJobRunner$.run(GenerationIngestionJobRunner.scala:42)
    at featurepipelines.generation_ingestion.GenerationIngestionJobRunner$.main(GenerationIngestionJobRunner.scala:63)
    at featurepipelines.generation_ingestion.GenerationIngestionJobRunner.main(GenerationIngestionJobRunner.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.flink.client.program.PackagedProgram.callMainMethod(PackagedProgram.java:316)
    ... 11 more
Caused by: org.apache.flink.table.api.ValidationException: Cannot discover a connector using option: 'connector'='kafka'
    at org.apache.flink.table.factories.FactoryUtil.enrichNoMatchingConnectorError(FactoryUtil.java:385)
    at org.apache.flink.table.factories.FactoryUtil.getDynamicTableFactory(FactoryUtil.java:372)
    at org.apache.flink.table.factories.FactoryUtil.createTableSource(FactoryUtil.java:118)
    ... 79 more
Caused by: org.apache.flink.table.api.ValidationException: Could not find any factory for identifier 'kafka' that implements 'org.apache.flink.table.factories.DynamicTableFactory' in the classpath.

Available factory identifiers are:

blackhole
datagen
filesystem
print
    at org.apache.flink.table.factories.FactoryUtil.discoverFactory(FactoryUtil.java:245)
    at org.apache.flink.table.factories.FactoryUtil.enrichNoMatchingConnectorError(FactoryUtil.java:382)
    ... 81 more

I confirm that org.apache.flink.table.factories.DynamicTableFactory is in my classpath locally:
> jar vtf target/featurepipelines-0.1.jar | grep DynamicTableFactory
   579 Wed Dec 02 09:48:44 CST 2020 org/apache/flink/table/factories/DynamicTableFactory$Context.class
   396 Wed Dec 02 09:48:44 CST 2020 org/apache/flink/table/factories/DynamicTableFactory.class
  3794 Wed Dec 02 09:16:50 CST 2020 org/apache/flink/streaming/connectors/kafka/table/UpsertKafkaDynamicTableFactory$DecodingFormatWrapper.class
 19234 Wed Dec 02 09:16:50 CST 2020 org/apache/flink/streaming/connectors/kafka/table/KafkaDynamicTableFactory.class
 11773 Wed Dec 02 09:16:50 CST 2020 org/apache/flink/streaming/connectors/kafka/table/UpsertKafkaDynamicTableFactory.class
  3785 Wed Dec 02 09:16:50 CST 2020 org/apache/flink/streaming/connectors/kafka/table/UpsertKafkaDynamicTableFactory$EncodingFormatWrapper.class

Here is a similar question http://apache-flink-user-mailing-list-archive.2336050.n4.nabble.com/Flink-1-11-2-could-not-create-kafka-table-source-on-EMR-td39512.html but I don't think its answer works for me.
Any help? Thanks.

A: It turns out my pom.xml is configured incorrectly.
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-streaming-scala_${scala.binary.version}</artifactId>
            <version>${flink.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-clients_${scala.binary.version}</artifactId>
            <version>${flink.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-table-api-scala-bridge_${scala.binary.version}</artifactId>
            <version>${flink.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-table-planner-blink_${scala.binary.version}</artifactId>
            <version>${flink.version}</version>
        </dependency>

Add <scope>provided</scope> to each of the dependency fixes the issue.
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-streaming-scala_${scala.binary.version}</artifactId>
            <version>${flink.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-clients_${scala.binary.version}</artifactId>
            <version>${flink.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-table-api-scala-bridge_${scala.binary.version}</artifactId>
            <version>${flink.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-table-planner-blink_${scala.binary.version}</artifactId>
            <version>${flink.version}</version>
            <scope>provided</scope>
        </dependency>

Why <scope> should be provided? Here I quote from Flink docs:

It is highly recommended keeping the dependencies in scope provided. If they are not set to provided, the best case is that the resulting JAR becomes excessively large, because it also contains all Flink core dependencies. The worst case is that the Flink core dependencies that are added to the application's jar file clash with some of your own dependency versions (which is normally avoided through inverted classloading).


text:
Q: How to use @inherited annotation in Java? I am not getting the @Inherited annotation in Java. If it automatically inherits the methods for you then if I need to implement the method in my own way then what about that ?
How does will it come to know my way of implementation ?
Plus it is said if I do not want to use this and do it rather in an old fashioned Java way I have to implement the the equals(), toString(), and the hashCode() methods of the Object class and also the annotation type method of the java.lang.annotation.Annotation class.
Why is that?
I have never implemented those even when I did not know about the @Inherited annotation and the programs used to work fine also .
Please somebody explain me from the scratch about this.

A: Just that there is no misunderstanding: You do ask about java.lang.annotation.Inherited. This is a annotation for annotations.It means that subclasses of annotated classes are considered having the same annotation as their superclass.
Example
Consider the following 2 Annotations:
@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface InheritedAnnotationType {

}

and
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface UninheritedAnnotationType {

}

If three classes are annotated like this:
@UninheritedAnnotationType
class A {

}

@InheritedAnnotationType
class B extends A {

}

class C extends B {

}

running this code
System.out.println(new A().getClass().getAnnotation(InheritedAnnotationType.class));
System.out.println(new B().getClass().getAnnotation(InheritedAnnotationType.class));
System.out.println(new C().getClass().getAnnotation(InheritedAnnotationType.class));
System.out.println("_________________________________");
System.out.println(new A().getClass().getAnnotation(UninheritedAnnotationType.class));
System.out.println(new B().getClass().getAnnotation(UninheritedAnnotationType.class));
System.out.println(new C().getClass().getAnnotation(UninheritedAnnotationType.class));

will print a result similar to this (depending on the packages of the annotation):
null
@InheritedAnnotationType()
@InheritedAnnotationType()
_________________________________
@UninheritedAnnotationType()
null
null

As you can see UninheritedAnnotationType is not inherited but C inherits annotation InheritedAnnotationType from B.
I don't know what methods have to do with that.