text:
Q: Abrir un Archivo de Excel en asp.net Tengo el siguiente problema:
Quiero abrir un archivo de Excel al pulsar un botón; el archivo está en una carpeta compartida de un servidor.
Cuando estoy programando en mi localhost , si funciona con este código:
protected void BtnChk_Click(object sender, EventArgs e)
{
    Process.Start(@"\\server\vol1\Files\Book1.xls");
}

De esa manera doy clic y busca la ruta, y el archivo de excel inicia automáticamente.
Sin embargo, cuando la aplicación web la subo al servidor asignado host y todo, no me trae nada.
¿Cómo puedo hacer que funcione, o que otra manera podría hacerlo?
Este código es para verificar si existe el archivo, y si me funciona!! no entiendo porque visualizarlo no
            if (File.Exists(@"\\server\Files\Book1.xls"))
       {
            ButCrear.Visible = false;
            BtnChk.Visible = true;`

        }

A: Para darle permiso a la carpeta en donde tienes el archivo Excel a consultar, sigue estos pasos:

*

*Selecciona la carpeta destino: Ejemplo: C:/miCarpeta.

*Presiona click derecho > Propiedades.

*Ve a la pestaña Seguridad y presiona el Botón Editar.

*Aparecerá una nueva ventana. Selecciona el usuario IIS_USRS y debajo aparecerá un cuadro con los "Permisos de IIS_USRS".

*Selecciona el check en la columna "Allow/Permitir" al permiso de lectura "Read".

*Presiona el botón "Aplicar" y luego el botón "Aceptar" para guardar los cambios.

Intenta de nuevo acceder a tu archivo.

NOTA: Puedes darle permisos especiales o "Full Control", pero no creo que sea lo mas recomendable.

A: Te recomendaría que leyeras un poco de Cliente Servidor ya que si deseas subir tu código a un server obviamente el proceso que va a correr es el excel de donde este alojada tu aplicación Web.
Ahora si lo que quieres es que se habrá el Excel del cliente, entonces debes usar ActiveX, y lamento decirte que solo funciona en IE (no lo sé si en otros), y el Script de Java Script Seria el siguiente.
function test() {
    var Excel = new ActiveXObject("Excel.Application");
    Excel.Visible = true;
    Excel.Workbooks.Open("teste.xlsx");
  }

Donde teste.xlsx es la dirección del archivo (del lado del servidor). Ejemplo.
Tu carpeta donde esta tu pagina web:
http://site.com/views/pagina.html
Tu archivo xlsx esta en la siguiente dirección:
http://site.com/views/upload/teste.xlsx
entonces el path seria asi:
function test() {
    var Excel = new ActiveXObject("Excel.Application");
    Excel.Visible = true;
    Excel.Workbooks.Open("/upload/teste.xlsx");
  }

Saludos.

A: es debido a que utilizas la dirección del localhost para obtener la ruta del servidor desde donde se ejecuta la pagina utiliza System.Environment.GetEnvironmentVariable y te mostrara la carpeta en la que se encuentra espero te sirva


text:
Q: apply distance formula on three columns of text file in perl this is my data
nodes             x             y         z

1112,         23,       56,       88
2223,         56,       78,       54
3345,         32,       12,       11
4321,         11,       10,       06
5234,         10,       10,       12
6123,         12,       06,       04

now i want those nodes which are nearest to each other..example:
if distance between node(1112) and node(4321) is smaller (let d=10) than the distance between node(1112) and node(3345) (let d=34) and vice versa than output should be=
     node:1112 and node:4321 are closest
     node:6123 and node:3345 are closest.....

i am using distance formula like this:
my $dist = sqrt( ($x-$x2)*2 + ($y-$y2)*2 + ($z-$z2)**2 );
 i.e:
 d=sqrt( (56-23)**2 + (78-56)**2 + (54-88)**2 )
 d=sqrt( (32-23)**2 + (12-56)**2 + (11-88)**2 )
 d=sqrt( (11-23)**2 + (10-56)**2 + (06-88)**2 )
 d=sqrt( (10-23)**2 + (10-56)**2 + (12-88)**2 )....and so on

similarly for other nodes and their coordinates
 d=sqrt( (23-56)**2 + (56-78)**2 + (88-54)**2 )
 d=sqrt( (32-56)**2 + (12-78)**2 + (11-54)**2 )
 d=sqrt( (11-56)**2 + (10-78)**2 + (06-54)**2 )
 d=sqrt( (10-56)**2 + (10-78)**2 + (12-54)**2 )....

i have done this but got nothing......
use strict;
use warnings;
use Data::Dumper;

open(IN , "<" , "1.txt");
#open(OUT , ">" , "out.txt");

my $node_flag=0;
my %node_hash_1;
my %node_hash_2;

my @node_1;
my @node_2;

my @distance_array;
my $i=0;

foreach my $line(<IN>)
{
    if($line=~/^\*node$/i)
    {
        $node_flag=1;
        next;
    }
    if($node_flag==1)
    {
        if($line!~/^\*\*/i)
        {
            my @array=split(",",$line); # or  my @array=(split(",",$line))[1,2,3]
            my $node_id=shift @array;
            $node_hash_1{$node_id}=\@array;

            push(@node_1,[@array]);
            push(@node_2,[@array]);

            foreach my $var1(@node_1)
            {
                my($x,$y,$z)=@{$var1};
                foreach my $var2(@node_2)
                {
                    my($x2,$y2,$z2)=@{$var2};
                    my $dist = sqrt( ($x-$x2)**2 + ($y-$y2)**2 + ($z-$z2)**2 );
#                   print $dist;
                    print"\n";
                    foreach my $value(@{$node_hash_1{$node_id}})
                    {
                        my $vars=join",",@{$node_hash_1{$node_id}};
                        my @arr=split ",",$vars;
#                       print $arr[0];
                        print $vars;
                        if ($x==$value && $y==$value && $z==$value)
                        {
                            push @{$node_hash_1{$node_id}},$dist;
#                           $node_hash_2{x} = $x;
#                           $node_hash_2{y} = $y;
#                           $node_hash_2{z} = $z;
                        }
                    }
                }
            }
        }
        else
        {
            $node_flag=0;
        }
    }
}
#print Dumper(\%node_hash);
#print Dumper(\@distance_array);
#print Dumper(\@node_1);
#print Dumper(\%node_hash_2);

A: The input line never matches '*node' so $node_flag never gets set and so the second if gets totally skipped, skipping everything.

*

*Since 'nodes' comes with an 's' and comes at the beginning of the first line, I do not think you have it correctly.

*Also, since I see no literal '*' in your input, I don't think you understand that /\*/ is a way of matching a literal star.

I amended the regex to read m/^nodes\b/, which at least sets $node_flag and gets me into the main body. Here's the thing, though if you know a set number of lines will appear at the top of the file, and you don't need that information, this will do:
<IN> foreach 1..2;
# or just once if that blank line is just a formatting mistake.

If you wanted to check for the header line:
die 'No Header Line!' unless <IN> =~ m/^nodes\b/;

That way, you don't enter the loop (it should be a while loop, anyway).

*

*That you are shoving the same coordinates into two arrays, shows that you're overusing the foreach loops.

*In addition, doing a Cartesian compare while gathering data can be done in a better way, if you hold the current input value out of the list, comparing it the members already stored in the list. It looks like you end up comparing node #1 to node #1 for as many lines as you have.
Although I might decompose this into a set of classes if I really cared about the data, I offer the changes below as a straight perl line processor:
my ( @node_list, %distance_between, %closest_to );

die 'No Header' unless <IN> =~ m/^nodes\b/;

while ( my $line = <IN> ) {
    my ( $name, $x, $y, $z ) = split /\s*,\s*/, $line;
    foreach my $comp_node ( @node_list ) {
        my ( $name2, $x2, $y2, $z2 ) = @$comp_node;

        # distance_between is a needless structure, if
        # you don't want to keep the distance.
        $distance_between{ $name2 }{ $name }
            = $distance_between{ $name }{ $name2 }
            = my $dist
            = sqrt( ($x-$x2)**2 + ($y-$y2)**2 + ($z-$z2)**2 )
            ;

        my $closest = $closest_to{ $name2 } ||= [ $name, $dist ];
        if ( $closest->[1] > $dist ) {
            $closest_to{ $name2 } = [ $name, $dist ];
        }
        $closest = $closest_to{ $name } ||= [ $name2, $dist ];
        if ( $closest->[1] > $dist ) {
            $closest_to{ $name } = [ $name2, $dist ];
        }
    }
    push @node_list, [ $name, $x, $y, $z ];
}
foreach my $p ( map { [ $_, $closest_to{ $_ }[0] ] } sort keys %closest_to ) {
    say "$p->[0]'s closest neighbor is $p->[1]" ;
}

A: #!/usr/bin/perl

use strict;
use warnings;

my (@data, @temp, @result);

sub calc {
    my ($a, $b) = @_;
    my $dat = 0;
    $dat += ($a->[$_] - $b->[$_]) ** 2 for (1..3);
    return sqrt $dat;
}

while (<DATA>) {
    push @data, [split /,?\s+/];
}

for my $x (@data) {
    for my $y (@data) {
        push @temp, [calc($x, $y), $x, $y] if ($x->[0] > $y->[0]);
    }
}

@result = sort { $a->[0] <=> $b->[0]; } @temp;

for (@result) {
    print "[", join(', ', @{$_->[1]}), "], [", join(', ', @{$_->[2]}),
        "] => $_->[0]\n";
}

__DATA__
1112,         23,       56,       88
2223,         56,       78,       54
3345,         32,       12,       11
4321,         11,       10,       06
5234,         10,       10,       12
6123,         12,       06,       04

output:
[6123, 12, 06, 04], [4321, 11, 10, 06] => 4.58257569495584
[5234, 10, 10, 12], [4321, 11, 10, 06] => 6.08276253029822
[6123, 12, 06, 04], [5234, 10, 10, 12] => 9.16515138991168
[4321, 11, 10, 06], [3345, 32, 12, 11] => 21.6794833886788
[6123, 12, 06, 04], [3345, 32, 12, 11] => 22.0227155455452
[5234, 10, 10, 12], [3345, 32, 12, 11] => 22.113344387496
[2223, 56, 78, 54], [1112, 23, 56, 88] => 52.2398315464359
[3345, 32, 12, 11], [2223, 56, 78, 54] => 82.3468275041607
[3345, 32, 12, 11], [1112, 23, 56, 88] => 89.1403387922662
[5234, 10, 10, 12], [1112, 23, 56, 88] => 89.7830719011106
[5234, 10, 10, 12], [2223, 56, 78, 54] => 92.217135067188
[4321, 11, 10, 06], [2223, 56, 78, 54] => 94.62029380635
[4321, 11, 10, 06], [1112, 23, 56, 88] => 94.7839648885823
[6123, 12, 06, 04], [2223, 56, 78, 54] => 98.0815986819138
[6123, 12, 06, 04], [1112, 23, 56, 88] => 98.3717439105356

redpajama_set_name: RedPajamaStackExchange


text:
Q: what is the largest possible value of N? I was told that the following problem can be solved using this method, but I don't understand why N equals the sum of the $4$ terms. Can anyone explain it to me? I guess that my problem is that I may not understand the meaning of "$2^{N}$ is a factor of $20!$".
$\newcommand{\flr}[1]{\left\lfloor\,{#1}\,\right\rfloor}$
$$
N =
\flr{20 \over 2}+ \flr{20 \over 2^{2}} +\flr{20 \over 2^{3}} +
\flr{20 \over 2^{4}} = 10 + 5 + 2 + 1 = 18
$$

If $2^{N}$ is a factor of $20!$, what is the largest possible value of $N$ ?.

A: $2^N$ is a pure power of $2$, $20!$ is not. So, while dividing $20!$ by $2^N$, think of it as diving it $N$ times by $2$. Now, in order for $2^N$ to be a divisor of $20!$, there must be at least $N$ many $2$'s in its factorization. So, we count how many $2$'s are there. That'll be the maximum possible value of $N$.
As for the calculation, note that $20!=1 \cdot 2 \cdots 20$. How many multiples of $2$ are there? Exactly $\lfloor {20 \over 2} \rfloor$. Here comes the tricky (well, a bit) part. The multiples of $4$ contribute two $2$'s. So, we count them once again. Continuing, we count the number of multiples of $2^n$ under $20$, that is $\lfloor {20 \over 2^n} \rfloor$ . In this case, after $2^4$, we get zero number of multiples. Hence the solution is $10+5+2+1=18$.

A: $$20!=1\cdot2\cdot3\cdot4\cdot5\cdot6\cdot7\cdot8\cdot9\cdot10\cdot11\cdot12\cdot13\cdot14\cdot15\cdot16\cdot17\cdot18\cdot19\cdot20.$$
Now strike out every odd factor
$$2\cdot4\cdot6\cdot8\cdot10\cdot12\cdot14\cdot16\cdot18\cdot20$$
and divide all these $10$ factors by $2$. You obtain
$$1\cdot2\cdot3\cdot4\cdot5\cdot6\cdot7\cdot8\cdot9\cdot10.$$
This shows that the multiplicity of $2$ in $20!$ is $20/2$ plus the multiplicity in $10!$. For the same reason, the multiplicity in $10$ is $10/2$ plus the multiplicity in $5!$. And do on.


text:
Q: rdesktop aborts due to untrusted certificate I have rdesktop v1.9.0. I'm trying to connect to remote Win10 host.
rdesktop aborts with following error:
rdesktop -v -x -z -E -d domain -u user user.domain.com
Autoselecting keyboard map 'en-us' from locale
is_wm_active(): WM name: awes
Connecting to server using NLA...
Core(warning): Certificate received from server is NOT trusted by this system, an exception has been added by the user to trust this specific certificate.
TLS  Session info: (TLS1.2)-(ECDHE-X25519)-(RSA-SHA256)-(AES-256-GCM)

Failed to initialize NLA, do you have correct Kerberos TGT initialized ?
Failed to connect using NLA, trying with SSL
Failed to connect, CredSSP required by server (check if server has disabled old TLS versions, if yes use -V option).

The connection goes inside encrypted VPN tunnel. Remote host is definitely available and I'm absolutely sure the remote certificate is trusted (but may be expired).
I'm able to connect to the very same machine using window remote desktop application (it display me the same warning, but gives an option to ignore certificate issue and continue connection).
I read man rdesktop a few times and tried various options related to encryption and certs (e.g. -E), nothing seems to help. Neither helps internet search.
How do I force rdesktop to trust remote certificate and continue connection to remote host?

A: No, rdesktop aborts for reasons which have nothing to do with the certificate. (It does remember and "trust" individual certificates as other clients do, and your output says that an exception has already been added.)
The problem here is that rdesktop has incomplete NLA (CredSSP) support – it does not support the NTLM authentication mechanism required for password-based logins,  so it cannot prompt you for credentials before connection the way Windows MSTSC does. (And its Kerberos support is a bit buggy as well.)
In other words, rdesktop only works with the older XP/2003 login process, where you'd establish a connection first and see the server's login screen afterwards. FreeRDP is a more suitable client for connecting to modern hosts (Windows 7/8/10):
xfreerdp /bpp:32 /gfx +aero +fonts /d:domain /u:user /v:user.domain.com [/cert-...]

With FreeRDP you can add the option /cert-tofu to implement the "trust on first connection" certificate checking (as in MSTSC), or you can use /cert-ignore to completely disable certificate checking.
If you must use rdesktop, then you will have to disable NLA ("Network Level Authentication") requirement on the Windows 10 host – although that's generally not recommended due to much higher attack surface.


text:
Q: Evaluation of part of Clojure cond Trying to do exercise 1.16 (iterative version of fast-exp) in "Structure and Interpretation of Computer Programs" with Clojure I came up with this:
(defn fast-it-exp [base exp res]
  (cond (= exp 0) res
  (odd? exp) fast-it-exp base (- exp 1) (* base res)
  :else fast-it-exp base (/ exp 2) (* base base res)))

Trying it out:
user=> (fast-it-exp 0 0 10)
10   ;yep
user=> (fast-it-exp 2 2 2)
1     ;no...
user=> (fast-it-exp 1 1 1)
#<user$fast_it_exp__59 user$fast_it_exp__59@138c63>    ;huh?!

Seems the "odd" part of the cond expression returns a function instead of evaluating. Why?
I've tried putting parenthesis around the expressions after the predicates but that seems to be incorrect syntax, this is the best I've been able to come up with.
I'm using rev 1146 of Clojure.

A: Basically, what you wrote could be reformatted as:
(defn fast-it-exp [base exp res]
  (cond
    (= exp 0) res
    (odd? exp) fast-it-exp
    base (- exp 1)
    (* base res) :else
    fast-it-exp base
    (/ exp 2) (* base base res)))

So:
user=> (fast-it-exp 0 0 10) ; (= exp 0) => res
10   ;yep
user=> (fast-it-exp 2 2 2)  ; base => (- exp 1)
1     ;no...
user=> (fast-it-exp 1 1 1)  ; (odd? exp) => fast-it-exp
#<user$fast_it_exp__59 user$fast_it_exp__59@138c63>    ;huh?!

A: Try this:
 (defn fast-it-exp [base exp res]
  (cond (= exp 0) res
        (odd? exp) (fast-it-exp base (- exp 1) (* base res))
        :else (fast-it-exp base (/ exp 2) (* base base res))))

I have no REPL handy but is looks like what you want.


text:
Q: How to remove the blank text container on empty UITextView I've already set the properties textContainerInset and lineFragmentPadding to zero as seen on this code thanks to this removing the padding and margin via this SO answer.
// this is inside a UITextView Subclass
required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.textContainerInset = .zero
    self.textContainer.lineFragmentPadding = 0
}

Here's how the UITextView renders when it has text

Here it is with multiple lines

Here's how it renders without text

Is it possible to make the height 0 if the UITextView's text is empty?
Edit:

*

*There is no constraint being used on the UITextView and I'm not planning to set a height constraint as I want this UITextView to automatically resize depending on the text being set into it

*This is a isScrollEnabled = false UITextView inside a UITableViewCell, which automatically resizes depending on the data fetched from the api server.
About:
Language: Swift 3.2
IDE: Xcode 9.2

A: Thanks to uhuru's answer I've formulated an answer to the code of mine that wouldn't need too much of an overhaul.
First I've setup a height constraint for the UITextView programatically.
// outside the scope
var contentTextViewConstraint: NSLayoutConstraint?

// inside awakeFromNib
self.contentTextViewConstraint = NSLayoutConstraint(
    item: self.lblContent,
    attribute: NSLayoutAttribute.height,
    relatedBy: NSLayoutRelation.equal,
    toItem: nil,
    attribute: NSLayoutAttribute.notAnAttribute,
    multiplier: 1,
    constant: 0)
self.contentTextViewConstraint?.isActive = false

Then activate/deactivate the constraint depending on the String
// inside the setup
let contentText: String = model.contentText
self.tvContent.text = contentText
self.contentTextViewConstraint?.isActive = contentText.isEmpty

A: You can set two height constraints for the TVw. One with your desired height and the other one with 0 height and less priority.
Then on the TextView's delegate do something like:
func textViewDidChange(_ textView: UITextView) {
    constraint.isActive = textView.text.count != 0
}

A: Try this code:
CGSize sizeThatFitsTextView = [TextView sizeThatFits:CGSizeMake(TextView.frame.size.width, MAXFLOAT)];
TextViewHeightConstraint.constant = sizeThatFitsTextView.height;

A: This may be UITextView's bug. Try to follow code:
- (CGSize)intrinsicContentSize {
    CGSize size = [super intrinsicContentSize];
    if ((size.width < FLT_EPSILON || size.height < FLT_EPSILON) && self.textStorage.string.length == 0) {
        return CGSizeZero;
    } else {
        return size;
    }
}

A: Another possible solution is to add a constraint in InterfaceBuilder for height == 0, set it as isActive == false and give it a custom identifier.
Activate/deactivate it when needed in the code using :
textView.constraints.first { $0.identifier == "theConstrainIdentifier" }?.isActive = false // or true


text:
Q: C++ Linked List Iterator Class I created a singly linked list for a project and now need to create a custom Iterator class. I have a nested class within my Linked List that defines my iterator. I have written most of the class, but am confused as to how to implement some functions. My issues are as follows:
-Please look at my end() function. I set it to the default constructor for the Iterator class, so the
currentNode variable in iterator got defaulted to NULL I guess. Is this correctly implemented?
-How should I overload the -> operator in the Iterator class?
class SSLL_Iter : public std::iterator<std::forward_iterator_tag, T>
    {
    public:
        typedef T value_type;
        typedef std::ptrdiff_t difference_type;
        typedef T& reference;
        typedef T* pointer;
        typedef std::forward_iterator_tag iterator_category;
        typedef SSLL_Iter self_type;
        typedef SSLL_Iter& self_reference;

    private:
        Node* currentNode;

    public:
        explicit SSLL_Iter( Node* start = NULL) : currentNode( start ) {}   //****************complete

        SSLL_Iter( const SSLL_Iter& src ) : currentNode( src.currentNode ) {}      //****************complete

        reference operator*() const {   //****************complete
            T& temp = (currentNode->data);
            return temp;
        }

        pointer operator->() const {}  //*******??????????????????

        self_reference operator=( const SSLL_Iter& src ) {     //****************complete

            this->here = src.here;
            return *this;
        }

        self_reference operator++() { // preincrement         //****************complete
            currentNode = currentNode->next;
            return *this;
        }
        self_type operator++(int) {  // postincrement         //****************complete
            self_type temp = (*this);
            ++(*this);
            return temp;
        }

        bool operator==(const SSLL_Iter& rhs) const {        //****************complete
            return (this->currentNode == rhs.currentNode);
        }

        bool operator!=(const SSLL_Iter& rhs) const {        //****************complete
            return (this->currentNode != rhs.currentNode);
        }
    }; // end SSLL_Iter

    typedef std::size_t size_t;
    typedef T value_type;
    typedef SSLL_Iter iterator;
    //typedef Const_SSL_Iter const_iterator;

    SSLL() {}

    SSLL(const SSLL& src ) {

        for(int i = 0; i < src.size(); ++i) {    // populate this SSLL with copies of the other SSLL's    contents
            this->push_back(src.item_at(i));
        }
    }

    ~SSLL() {

        if(!is_empty()) {
            clear();
        }

    }

    iterator begin() { return SSLL_Iter( head ); }

    iterator end() { return SSLL_Iter(); }

A: return &*(*this); is a decent operator->.
Your SSLL class probably does not have an efficient at, so don't use it in the copy constructor.  Instead, create a SSLL template<class Iterator> void append(Iterator s, Iterator f), and implement SSLL(const SSLL& src) in terms of it.
If you have C++11 support, consider replacing the next node of Node with a std::unique_ptr<Node>.  Do the same with the pointer-to-first Node in the SSLL root.  Now memory management is handled pretty much automatically.  You may need a .get() in your iterator after that change.  This also eliminates the body of your destructor, makes your move-constructor =default correct (unless you are counting nodes), etc.


text:
Q: Pretty-printing WKT strings? Is there a tool that will pretty-print well-known-text strings? One that would accept for instance
MULTIPOLYGON (((40 40, 20 45, 45 30, 40 40)), ((20 35, 45 20, 30 5, 20 35)))

and output something like
MULTIPOLYGON (
  (
    (
      40 40,
      20 45,
      45 30,
      40 40
    ),
  ),
  (
    (
      20 35,
      45 20,
      30  5,
      20 35
    )
  )

Ideally this would be an online tool that runs in a browser (along the lines of the many JSON formatters that exist), but an offline tool would still be useful.
There are a number of online tools for viewing and editing WKT-format data, but none that seem to offer any support for reformatting. The OpenLayers vector-formats example app has a checkbox tantalizingly labelled "Pretty print", but selecting it seems not to do anything when WKT is set as the output format.

A: OpenJUMP http://openjump.org can do that on desktop.
Compressed format that is good for copy-paste

Beautified format that helps visual interpretation


text:
Q: Trying to prove that $TM$ is a manifold: Is this function an homeomorphism? I am trying to prove that if $M$ is a $k$-manifold in $\mathbb R^n$, then $TM=\{(p, v): p \in M, v \in T_pM\}$ is a manifold. Here, $T_pM$ is defined as a subset of $\mathbb R^n$.
I know that questions about this problem have already been asked in this website, but my question is very specific:
Let $(p, v) \in TM$ be given. I attempted to create a coordinate patch as follows:
Suppose $\alpha: U\rightarrow M$ is a coordinate patch for $p$. Let $f: U \times \mathbb R^k\rightarrow TM$ be given by:
$$f(x, u)=(\alpha (x), d\alpha(x)\cdot u)$$
I proved $f$ is $C^\infty$, injective, that $f[U \times \mathbb R^k]$ is a open set of $TM$. It remains to show that $f^{-1}$ is continuous.
Notice that $\alpha^{-1}(p, v)=(\alpha^{-1}(p), [d\alpha(\alpha^{-1}(p))]^{-1}\cdot v)$, where $[d\alpha(\alpha^{-1}(p))]^{-1}$ denotes the inverse of the linear map $d\alpha(\alpha^{-1}(p))$ as a function (we know that this function is injective, we set it's range, $T_pM$, as the inverse's domain).

I want to see that the function $(p, v)\rightarrow [d\alpha(\alpha^{-1}(p))]^{-1}\cdot v$ defined on $TM$ is continuous. I don't know how to proceed without some handwaving. Can someone clarify this?

A: Let $ \ F = G \circ d \alpha \circ \alpha^{-1} \ $, where $ \ G(T)=T^{-1}$. Then $F$ is continuous. If $ \ (p_0,v_0) \in TM \ $ and $ \ \varepsilon > 0 \ $ there exists $ \ \delta > 0 \ $ such that, $\forall p \in U$, $$\Vert p-p_0 \Vert < \delta \ \Rightarrow \Vert F(p) - F(p_0) \Vert < \sqrt{\varepsilon} \ . $$
Let $ \ \eta = min \{ \delta , \sqrt{\varepsilon} \}$. If $ \ \ max \{ \Vert p-p_0 \Vert , \Vert v-v_0 \Vert \} = \Vert (p,v) - (p_0,v_0) \Vert < \eta$, we have $$\Vert [F(p)](v) - [F(p_0)](v_0) \Vert = \Vert [F(p)-F(p_0)](v-v_0) \Vert \leqslant \Vert F(p-p_0)\Vert \cdot \Vert v-v_0 \Vert <$$ $$< \sqrt{\varepsilon} \cdot \Vert v-v_0 \Vert < \sqrt{\varepsilon} \cdot \sqrt{\varepsilon} = \varepsilon \ . $$

A: I assume you are talking about the tangent bundle as a subset of $M \times \mathbb{R}^n$, right?
Let me offer two alternative ways to solve this.

Firstly, since you are on a coordinate patch, you have a continuous (actually, smooth) way of choosing $n-k$ normal vector fields to your manifold which are pointwise linearly independent. Use them to extend your linear maps $d\alpha$ to invertible linear maps
with domain on $\mathbb{R}^n$ instead of $\mathbb{R}^k$. It is now easier to verify continuity (and smoothness) of the inverse map of this enlarged function $U \times \mathbb{R}^n \to M \times \mathbb{R}^n$, since we are dealing with bona fide invertible linear maps, not only injective ones. The function you want to be continuous is just the restriction of this to $TM$.

Secondly, assuming nothing besides topology, you can use this lemma:

Lemma: Let $X,Y$ be topological spaces, where $Y$ is Hausdorff, such that $X$ has an exhaustion by compact sets $K_n$, and let $F:X\rightarrow Y$ be a continuous bijective map such that $F(K_n)$'s exhaust $Y$. Then $F$ is a homeomorphism.
Proof: $F$ is by hypothesis continuous, and being injective on compact sets (the codomain is Hausdorff), each $F|_{K_n}$ is a homeomorphism with its image. We will prove that $G:=F^{-1}$ is continuous.
Take $y \in Y$, together with a open neighbourhood $W$ of $G(y)$. Since $K'_n:=F(K_n)$ exhaust $Y$, there exists a $K'_N$ such that $y \in K'_N$. By hypothesis, $y \in \text{int}K'_{N+1}$. Due to our previous observation, $G|_{K'_{N+1}}$ is a homeomorphism. Therefore, $G|_{\text{int}K'_{N+1}}$ is continuous (in fact, a homeomorphism). Hence, there exists an open neighbourhood $V$ of $y$ such that $G(V) \subset W$. But a neighbourhood in the induced topology of an open set must be an open set in the topology itself. Hence, we found an open neighbourhood of $y$ which is taken inside $W$. This proves continuity of $G$.

Considering that $U$ is open in $\mathbb{R}^k$, it has an exhaustion by compact sets $K_n$. The exhaustion $K_n \times [-n,n]^k$ of $U \times \mathbb{R}^k$ should satisfy the hypothesis of the lemma.
OBS: By exhaustion, I mean a sequence of compact sets such that $K_n \subset \text{int} K_{n+1}$.


text:
Q: clear specific fields when user changes value of a select Ok, I'm really starting to have a bad day and the ol' brain isn't working. I can't think of what I should be searching for, or even find previous examples of this kind of thing.
I have a HTML form with three fields;

*

*select: disposition_status

*text: disposition_datetime_hasrecord

*text: disposition_description

The select field disposition_status has the following values:

*

*1 - in

*2 - out

When a user selects the item in disposition_status with the value of 1 (in), I want to clear any text in the fields disposition_datetime_hasrecord and disposition_description.
If anyone has an example or can point me in the right direction for achieving this it would be appreciated.

A: demo
$('#disposition_status').change(function() {
    if (this.value == 1) {
        $('#disposition_datetime_hasrecord').val('');
        $('#disposition_description').val('');
    }
});

edit: based on comment
Okay, I see now the problem, it should be wrap inside
$(document).ready(function() {
    //code here
});

sorry jsfiddle do it internally (I did set it actually).. so just put the codes inside like
$(document).ready(function() {
   $('#disposition_status').change(function() {
      if (this.value == 1) {
        $('#disposition_datetime_hasrecord').val('');
        $('#disposition_description').val('');
      }
   });
});

explanation here

A: Try this:
$('select[name=disposition_status]').change(function() {
    if ($(this).val() == 1) {
        $('*[name=disposition_datetime_hasrecord]').val('');
        $('*[name=disposition_description]').val('');
    }
});

A: It's ok, Sunday nights are a tough night to code anyways ;-)
To do this, you would use the jQuery change method to catch any changes within the menu. From there, you could setup a simple case statement to decide what to do, e.g.:
 $("#disposition_status").change(function() {
     if ($(this).val() == 1) {
         $("#disposition_datetime_hasrecord").val("");
         $("#disposition_description").val("");
     }
 });

This is assuming you have those set as ID's, if not you can use the selector "*[name=disposition_status]" etc. to select them.
Edit: Oh drats! Just beaten by someone else ;-) Same thought process at least :)


text:
Q: How to find the vtable order, Specifically for directx I have been trying for awhile to get a correct vtable order for direct2d and I thought I got the correct one but it has not been working other then the first 3 (IUnknown inherited), and i was wondering how to get a proper vtable order.
My vtable so far
;ID2D1RenderTargetVtbl
ID2D1RenderTarget_QueryInterface                textequ     <qword ptr [rbx+0]>
ID2D1RenderTarget_AddRef                        textequ     <qword ptr [rbx+8]>
ID2D1RenderTarget_Release                       textequ     <qword ptr [rbx+16]>
ID2D1RenderTarget_GetFactory                    textequ     <qword ptr [rbx+24]>
ID2D1RenderTarget_BeginDraw                     textequ     <qword ptr [rbx+32]>
ID2D1RenderTarget_Clear                         textequ     <qword ptr [rbx+40]>
ID2D1RenderTarget_CreateBitmap                  textequ     <qword ptr [rbx+48]>
ID2D1RenderTarget_CreateBitmapBrush             textequ     <qword ptr [rbx+56]>
ID2D1RenderTarget_CreateBitmapFromWicBitmap     textequ     <qword ptr [rbx+64]>
ID2D1RenderTarget_CreateCompatibleRenderTarget  textequ     <qword ptr [rbx+72]>
ID2D1RenderTarget_CreateGradientStopCollection  textequ     <qword ptr [rbx+80]>
ID2D1RenderTarget_CreateLayer                   textequ     <qword ptr [rbx+88]>
ID2D1RenderTarget_CreateLinearGradientBrush     textequ     <qword ptr [rbx+96]>
ID2D1RenderTarget_CreateMesh                    textequ     <qword ptr [rbx+104]>
ID2D1RenderTarget_CreateRadialGradientBrush     textequ     <qword ptr [rbx+112]>
ID2D1RenderTarget_CreateSharedBitmap            textequ     <qword ptr [rbx+120]>
ID2D1RenderTarget_CreateSolidColorBrush         textequ     <qword ptr [rbx+128]>
ID2D1RenderTarget_DrawBitmap                    textequ     <qword ptr [rbx+136]>
ID2D1RenderTarget_DrawEllipse                   textequ     <qword ptr [rbx+144]>
ID2D1RenderTarget_DrawGeometry                  textequ     <qword ptr [rbx+152]>
ID2D1RenderTarget_DrawGlyphRun                  textequ     <qword ptr [rbx+160]>
ID2D1RenderTarget_DrawLine                      textequ     <qword ptr [rbx+168]>
ID2D1RenderTarget_DrawRectangle                 textequ     <qword ptr [rbx+176]>
ID2D1RenderTarget_DrawRoundedRectangle          textequ     <qword ptr [rbx+184]>
ID2D1RenderTarget_DrawText                      textequ     <qword ptr [rbx+192]>
ID2D1RenderTarget_DrawTextLayout                textequ     <qword ptr [rbx+200]>
ID2D1RenderTarget_EndDraw                       textequ     <qword ptr [rbx+208]>
ID2D1RenderTarget_FillEllipse                   textequ     <qword ptr [rbx+216]>
ID2D1RenderTarget_FillGeometry                  textequ     <qword ptr [rbx+224]>
ID2D1RenderTarget_FillMesh                      textequ     <qword ptr [rbx+232]>
ID2D1RenderTarget_FillOpacityMask               textequ     <qword ptr [rbx+240]>
ID2D1RenderTarget_FillRectangle                 textequ     <qword ptr [rbx+248]>
ID2D1RenderTarget_FillRoundedRectangle          textequ     <qword ptr [rbx+256]>
ID2D1RenderTarget_Flush                         textequ     <qword ptr [rbx+264]>
ID2D1RenderTarget_GetAntialiasMode              textequ     <qword ptr [rbx+272]>
ID2D1RenderTarget_GetDpi                        textequ     <qword ptr [rbx+280]>
ID2D1RenderTarget_GetMaximumBitmapSize          textequ     <qword ptr [rbx+288]>
ID2D1RenderTarget_GetPixelFormat                textequ     <qword ptr [rbx+296]>
ID2D1RenderTarget_GetPixelSize                  textequ     <qword ptr [rbx+304]>
ID2D1RenderTarget_GetSize                       textequ     <qword ptr [rbx+312]>
ID2D1RenderTarget_GetTags                       textequ     <qword ptr [rbx+320]>
ID2D1RenderTarget_GetTextAntialiasMode          textequ     <qword ptr [rbx+328]>
ID2D1RenderTarget_GetTextRenderingParams        textequ     <qword ptr [rbx+336]>
ID2D1RenderTarget_GetTransform                  textequ     <qword ptr [rbx+344]>
ID2D1RenderTarget_IsSupported                   textequ     <qword ptr [rbx+352]>
ID2D1RenderTarget_PopAxisAlignedClip            textequ     <qword ptr [rbx+360]>
ID2D1RenderTarget_PopLayer                      textequ     <qword ptr [rbx+368]>
ID2D1RenderTarget_PushAxisAlignedClip           textequ     <qword ptr [rbx+376]>
ID2D1RenderTarget_PushLayer                     textequ     <qword ptr [rbx+384]>
ID2D1RenderTarget_RestoreDrawingState           textequ     <qword ptr [rbx+392]>
ID2D1RenderTarget_SaveDrawingState              textequ     <qword ptr [rbx+400]>
ID2D1RenderTarget_SetAntialiasMode              textequ     <qword ptr [rbx+408]>
ID2D1RenderTarget_SetDpi                        textequ     <qword ptr [rbx+416]>
ID2D1RenderTarget_SetTags                       textequ     <qword ptr [rbx+424]>
ID2D1RenderTarget_SetTextAntialiasMode          textequ     <qword ptr [rbx+432]>
ID2D1RenderTarget_SetTextRenderingParams        textequ     <qword ptr [rbx+440]>
ID2D1RenderTarget_SetTransform                  textequ     <qword ptr [rbx+448]>
;ID2D1Factory
    ID2D1Factory_QueryInterface                 textequ     <qword ptr [rbx+0]>
    ID2D1Factory_AddRef                         textequ     <qword ptr [rbx+8]>
    ID2D1Factory_Release                        textequ     <qword ptr [rbx+16]>
    ID2D1Factory_CreateDCRenderTarget           textequ     <qword ptr [rbx+24]>
    ID2D1Factory_CreateDrawingStateBlock        textequ     <qword ptr [rbx+32]>
    ID2D1Factory_CreateDxgiSurfaceRenderTarget  textequ     <qword ptr [rbx+40]>
    ID2D1Factory_CreateEllipseGeometry          textequ     <qword ptr [rbx+48]>
    ID2D1Factory_CreateGeometryGroup            textequ     <qword ptr [rbx+56]>
    ID2D1Factory_CreateHwndRenderTarget         textequ     <qword ptr [rbx+64]>
    ID2D1Factory_CreatePathGeometry             textequ     <qword ptr [rbx+72]>
    ID2D1Factory_CreateRectangleGeometry        textequ     <qword ptr [rbx+80]>
    ID2D1Factory_CreateRoundedRectangleGeometry textequ     <qword ptr [rbx+88]>
    ID2D1Factory_CreateStrokeStyle              textequ     <qword ptr [rbx+96]>
    ID2D1Factory_CreateTransformedGeometry      textequ     <qword ptr [rbx+104]>
    ID2D1Factory_CreateWicBitmapRenderTarget    textequ     <qword ptr [rbx+112]>
    ID2D1Factory_GetDesktopDpi                  textequ     <qword ptr [rbx+120]>
    ID2D1Factory_ReloadSystemMetrics            textequ     <qword ptr [rbx+128]>
;dcrendertarget
    ID2D1DCRenderTarget_BeginDraw                       textequ     <qword ptr [rbx+24]>
    ID2D1DCRenderTarget_Clear                           textequ     <qword ptr [rbx+32]>
    ID2D1DCRenderTarget_CreateBitmap                    textequ     <qword ptr [rbx+40]>
    ID2D1DCRenderTarget_CreateBitmapBrush               textequ     <qword ptr [rbx+48]>
    ID2D1DCRenderTarget_CreateBitmapFromWicBitmap       textequ     <qword ptr [rbx+56]>
    ID2D1DCRenderTarget_CreateCompatibleRenderTarget    textequ     <qword ptr [rbx+64]>
    ID2D1DCRenderTarget_CreateGradientStopCollection    textequ     <qword ptr [rbx+72]>
    ID2D1DCRenderTarget_CreateLayer                     textequ     <qword ptr [rbx+80]>
    ID2D1DCRenderTarget_CreateLinearGradientBrush       textequ     <qword ptr [rbx+88]>
    ID2D1DCRenderTarget_CreateMesh                      textequ     <qword ptr [rbx+96]>
    ID2D1DCRenderTarget_CreateRadialGradientBrush       textequ     <qword ptr [rbx+104]>
    ID2D1DCRenderTarget_CreateSharedBitmap              textequ     <qword ptr [rbx+112]>
    ID2D1DCRenderTarget_CreateSolidColorBrush           textequ     <qword ptr [rbx+120]>
    ID2D1DCRenderTarget_DrawBitmap                      textequ     <qword ptr [rbx+128]>
    ID2D1DCRenderTarget_DrawEllipse                     textequ     <qword ptr [rbx+136]>
    ID2D1DCRenderTarget_DrawGeometry                    textequ     <qword ptr [rbx+144]>
    ID2D1DCRenderTarget_DrawGlyphRun                    textequ     <qword ptr [rbx+152]>
    ID2D1DCRenderTarget_DrawLine                        textequ     <qword ptr [rbx+160]>
    ID2D1DCRenderTarget_DrawRectangle                   textequ     <qword ptr [rbx+168]>
    ID2D1DCRenderTarget_DrawRoundedRectangle            textequ     <qword ptr [rbx+176]>
    ID2D1DCRenderTarget_DrawText                        textequ     <qword ptr [rbx+184]>
    ID2D1DCRenderTarget_DrawTextLayout                  textequ     <qword ptr [rbx+192]>
    ID2D1DCRenderTarget_EndDraw                         textequ     <qword ptr [rbx+200]>
    ID2D1DCRenderTarget_FillEllipse                     textequ     <qword ptr [rbx+208]>
    ID2D1DCRenderTarget_FillGeometry                    textequ     <qword ptr [rbx+216]>
    ID2D1DCRenderTarget_FillMesh                        textequ     <qword ptr [rbx+224]>
    ID2D1DCRenderTarget_FillOpacityMask                 textequ     <qword ptr [rbx+232]>
    ID2D1DCRenderTarget_FillRectangle                   textequ     <qword ptr [rbx+240]>
    ID2D1DCRenderTarget_FillRoundedRectangle            textequ     <qword ptr [rbx+248]>
    ID2D1DCRenderTarget_Flush                           textequ     <qword ptr [rbx+256]>
    ID2D1DCRenderTarget_GetAntialiasMode                textequ     <qword ptr [rbx+264]>
    ID2D1DCRenderTarget_GetDpi                          textequ     <qword ptr [rbx+272]>
    ID2D1DCRenderTarget_GetMaximumBitmapSize            textequ     <qword ptr [rbx+280]>
    ID2D1DCRenderTarget_GetPixelFormat                  textequ     <qword ptr [rbx+288]>
    ID2D1DCRenderTarget_GetPixelSize                    textequ     <qword ptr [rbx+296]>
    ID2D1DCRenderTarget_GetSize                         textequ     <qword ptr [rbx+304]>
    ID2D1DCRenderTarget_GetTags                         textequ     <qword ptr [rbx+312]>
    ID2D1DCRenderTarget_GetTextAntialiasMode            textequ     <qword ptr [rbx+320]>
    ID2D1DCRenderTarget_GetTextRenderingParams          textequ     <qword ptr [rbx+328]>
    ID2D1DCRenderTarget_GetTransform                    textequ     <qword ptr [rbx+336]>
    ID2D1DCRenderTarget_IsSupported                     textequ     <qword ptr [rbx+344]>
    ID2D1DCRenderTarget_PopAxisAlignedClip              textequ     <qword ptr [rbx+352]>
    ID2D1DCRenderTarget_PopLayer                        textequ     <qword ptr [rbx+360]>
    ID2D1DCRenderTarget_PushAxisAlignedClip             textequ     <qword ptr [rbx+368]>
    ID2D1DCRenderTarget_PushLayer                       textequ     <qword ptr [rbx+376]>
    ID2D1DCRenderTarget_RestoreDrawingState             textequ     <qword ptr [rbx+384]>
    ID2D1DCRenderTarget_SaveDrawingState                textequ     <qword ptr [rbx+392]>
    ID2D1DCRenderTarget_SetAntialiasMode                textequ     <qword ptr [rbx+400]>
    ID2D1DCRenderTarget_SetDpi                          textequ     <qword ptr [rbx+408]>
    ID2D1DCRenderTarget_SetTags                         textequ     <qword ptr [rbx+416]>
    ID2D1DCRenderTarget_SetTextAntialiasMode            textequ     <qword ptr [rbx+424]>
    ID2D1DCRenderTarget_SetTextRenderingParams          textequ     <qword ptr [rbx+432]>
    ID2D1DCRenderTarget_SetTransform                    textequ     <qword ptr [rbx+440]>
    ID2D1DCRenderTarget_BindDC                          textequ     <qword ptr [rbx+448]>

I know addref works but i have not gotten CreateDCRenderTarget to work at all
A source for how i got these can be found here VTable, but now i'm doubting that it actually works
So if anybody knows how to get the correct VTable order That would be amazing.

A: The order of the vtable is wrong. Taken from DirectXVtable it defines the Vtable then defines it again but in the wrong order.
#define INTERFACE ID2D1Factory
DECLARE_INTERFACE_(ID2D1Factory, IUnknown)
{
  BEGIN_INTERFACE

  /* IUnknown methods */
  STDMETHOD(QueryInterface)(THIS_ REFIID riid, void **ppvObject) PURE;
  STDMETHOD_(ULONG, AddRef)(THIS) PURE;
  STDMETHOD_(ULONG, Release)(THIS) PURE;

  /* ID2D1Factory methods */
  STDMETHOD(ReloadSystemMetrics)(THIS) PURE;
  STDMETHOD_(void, GetDesktopDpi)(THIS_ FLOAT *dpiX, FLOAT *dpiY) PURE;
  STDMETHOD(CreateRectangleGeometry)(THIS_ D2D1_RECT_F *rectangle, ID2D1RectangleGeometry **rectangleGeometry) PURE;
  STDMETHOD(CreateRoundedRectangleGeometry)(THIS_ D2D1_ROUNDED_RECT *roundedRectangle, ID2D1RoundedRectangleGeometry **roundedRectangleGeometry) PURE;
  STDMETHOD(CreateEllipseGeometry)(THIS_ D2D1_ELLIPSE *ellipse, ID2D1EllipseGeometry **ellipseGeometry) PURE;
  STDMETHOD(CreateGeometryGroup)(THIS_ D2D1_FILL_MODE fillMode, ID2D1Geometry **geometries, UINT geometriesCount, ID2D1GeometryGroup **geometryGroup) PURE;
  STDMETHOD(CreateTransformedGeometry)(THIS_ ID2D1Geometry *sourceGeometry, D2D1_MATRIX_3X2_F *transform, ID2D1TransformedGeometry **transformedGeometry) PURE;
  STDMETHOD(CreatePathGeometry)(THIS_ ID2D1PathGeometry **pathGeometry) PURE;
  STDMETHOD(CreateStrokeStyle)(THIS_ D2D1_STROKE_STYLE_PROPERTIES *strokeStyleProperties, FLOAT *dashes, UINT dashesCount, ID2D1StrokeStyle **strokeStyle) PURE;
  STDMETHOD(CreateDrawingStateBlock)(THIS_ D2D1_DRAWING_STATE_DESCRIPTION *drawingStateDescription, IDWriteRenderingParams *textRenderingParams, ID2D1DrawingStateBlock **drawingStateBlock) PURE;
  STDMETHOD(CreateWicBitmapRenderTarget)(THIS_ IWICBitmap *target, D2D1_RENDER_TARGET_PROPERTIES *renderTargetProperties, ID2D1RenderTarget **renderTarget) PURE;
  STDMETHOD(CreateHwndRenderTarget)(THIS_ D2D1_RENDER_TARGET_PROPERTIES *renderTargetProperties, D2D1_HWND_RENDER_TARGET_PROPERTIES *hwndRenderTargetProperties, ID2D1HwndRenderTarget **hwndRenderTarget) PURE;
  STDMETHOD(CreateDxgiSurfaceRenderTarget)(THIS_ IDXGISurface *dxgiSurface, D2D1_RENDER_TARGET_PROPERTIES *renderTargetProperties, ID2D1RenderTarget **renderTarget) PURE;
  STDMETHOD(CreateDCRenderTarget)(THIS_ D2D1_RENDER_TARGET_PROPERTIES *renderTargetProperties, ID2D1DCRenderTarget **dcRenderTarget) PURE;

  END_INTERFACE
};
#undef INTERFACE

#define ID2D1Factory_QueryInterface(this,A,B) (this)->lpVtbl->QueryInterface(this,A,B)
#define ID2D1Factory_AddRef(this) (this)->lpVtbl->AddRef(this)
#define ID2D1Factory_Release(this) (this)->lpVtbl->Release(this)
#define ID2D1Factory_CreateDCRenderTarget(this,A,B) (this)->lpVtbl->CreateDCRenderTarget(this,A,B)
#define ID2D1Factory_CreateDrawingStateBlock(this,A,B,C) (this)->lpVtbl->CreateDrawingStateBlock(this,A,B,C)
#define ID2D1Factory_CreateDxgiSurfaceRenderTarget(this,A,B,C) (this)->lpVtbl->CreateDxgiSurfaceRenderTarget(this,A,B,C)
#define ID2D1Factory_CreateEllipseGeometry(this,A,B) (this)->lpVtbl->CreateEllipseGeometry(this,A,B)
#define ID2D1Factory_CreateGeometryGroup(this,A,B,C,D) (this)->lpVtbl->CreateGeometryGroup(this,A,B,C,D)
#define ID2D1Factory_CreateHwndRenderTarget(this,A,B,C) (this)->lpVtbl->CreateHwndRenderTarget(this,A,B,C)
#define ID2D1Factory_CreatePathGeometry(this,A) (this)->lpVtbl->CreatePathGeometry(this,A)
#define ID2D1Factory_CreateRectangleGeometry(this,A,B) (this)->lpVtbl->CreateRectangleGeometry(this,A,B)
#define ID2D1Factory_CreateRoundedRectangleGeometry(this,A,B) (this)->lpVtbl->CreateRoundedRectangleGeometry(this,A,B)
#define ID2D1Factory_CreateStrokeStyle(this,A,B,C,D) (this)->lpVtbl->CreateStrokeStyle(this,A,B,C,D)
#define ID2D1Factory_CreateTransformedGeometry(this,A,B,C) (this)->lpVtbl->CreateTransformedGeometry(this,A,B,C)
#define ID2D1Factory_CreateWicBitmapRenderTarget(this,A,B,C) (this)->lpVtbl->CreateWicBitmapRenderTarget(this,A,B,C)
#define ID2D1Factory_GetDesktopDpi(this,A,B) (this)->lpVtbl->GetDesktopDpi(this,A,B)
#define ID2D1Factory_ReloadSystemMetrics(this) (this)->lpVtbl->ReloadSystemMetrics(this)

You look at the "STDMETHOD" section of the definitions not the "#define" section.


text:
Q: how can I transfer health data from iPhone 5s to my new iPhone 6 plus? I got iPhone 6 plus and now want to transfer the health data from my old iPhone 5s to iPhone 6 Plus, but I don't know how. I've backed up the old one with iTunes and restore my iPhone 6 with the iPhone 5s backup file, but I can't see the heath data on iPhone 6 plus. Help.

A: If you want to back up your Health data using iTunes, you need to encrypt your backup by selecting "Encrypt iPhone backup" in the Summary tab in iTunes. If you don't select this option, your Health data won't back up.


text:
Q: undefined method for nil:NilClass when render new post form and @posts together It's a very strange bug bugged me for couple of hours already.
There are 3 models: user, school, post. Basically on the school page(school#show), there are a list of posts, and user can make new post.
The school controller:
def show
  @school = School.find(params[:id])
  $current_school = @school
  @post = @school.posts.build if logged_in?
  @posts = @school.posts

The school/show.html.erb:

      <%= render 'shared/post_form' %>

  <% if @school.posts.any? %>
      <%= render @posts %>
  <% end %>

_post_form.html.erb:
<%= form_for(@post) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>

    <%= f.text_area :content, placeholder: "Compose new post..." %>

  <%= f.submit "Post", class: "btn btn-primary" %>
<% end %>

posts/_post.html.erb:

  <%= image_tag post.user.avatar.url(:thumb) %>
  <%= link_to post.user.name, post.user %>
  <%= post.content %>

Post controller:
def create
  @post = $current_school.posts.create(content:params[:post[:content],user_id:current_user.id)
  if @post.save
    flash[:success] = "Post created!"
    redirect_to $current_school
  else
    render 'static_pages/home'
  end
end

The problem is, when navigate to school#show, it says
undefined method `avatar' for nil:NilClass

If I delete the
      @post = @school.posts.build if logged_in?

line, and the _post_form.html.erb fragment, the list of posts shows fine.
If I delete the _post.html.erb fragment, the new post function works fine as well.
But when they exist together, error comes up.
I guess the problem is at this line:
@post = @school.posts.build if logged_in?

because when I comment it out, the list of post shows fine. When I add it back, @posts can return a list of valid post, but post is nil.
Couldn't figure out what's wrong, please help.
Thanks
Edit: when visit url/schools/1, it crashes with NilClass error, post command returns
#<Post id: nil, content: nil, user_id: nil, school_id: 1, created_at: nil, updated_at: nil>

However, it should return the first post from @posts
Is it possible that
    @post = @school.posts.build if logged_in?

assign @post a nil post, and when it renders @posts, it is looking for @post which become nil instead of first post in @posts?
If so, how can I correct this?
Edit2: I tried to change @post to @test:
@test = @school.posts.build if logged_in?

and the same nilClass error persists. So my previous guess is not valid. There should be something wrong with using build here. But what's wrong?

A: Your Post does not have a User associated with it on the new/show action, unless you're somehow plugging a user in on the model. Try:
@post = @school.posts.build(user: current_user) if logged_in?

A: This line: @post = @school.posts.build if logged_in?,
should be without build method.
Like this:
@post = @school.posts if logged_in?

A: Please try
@post=@school.posts if logged_in?
and see if it works.
Also another important debugging thing that I can tell you is the gem 'pry'.Install it and you can check the value of variables anywhere in your views/models/controllers.
Hope it helps.


text:
Q: Design of CNN whose input is a 2D game board I am writing an artificial intelligence of a game. The algorithm needs a neural network to represent some information of the game board. The board is an 8*8 grid and each position in the grid has 4 types of contents. Since the type of a position is a discrete value, I binarize the type to a vector of size 4 (according to Arun Iyer's suggestions). Thus, I can map the game board to a 8*8*4 tensor that feeds to the neural network.
Since the game board can be viewed (roughly) as an 8*8 image with 4 channels, I think a convolutional neural network may be helpful. Am I right?
If that's right, I am wondering if my design of the three convolution layers (all with stride 1) makes sense: a 3*3 kernel with 32 feature maps, followed by a 3*3 kernel with 64 feature maps and followed by a 2*2 kernel with 64 feature maps.
Through testing, I found this structure is helpful and I want to add more layers or more parameters. However, since the input is too small (8*8), adding more convolution layers will make the size of the last feature maps (before FC layers) very small (may be 1*1 or 2*2). Does small feature map worsen the model's performance? Or should I use some other network architectures?
Thanks in advance!
P.S. I am applying deep reinforcement learning on the game. The output of the network is the estimated rewards the agent could get under current game board configuration. The network is trained using q-learning.

A: As your feature maps get smaller, each of them is representing information about larger portion of the game board. Features 1x1 contain global information about the game board, whereas larger one contain more fine-resolution information (about individual parts of the board). It is not so clear what you are doing with the network output or how you train the network, so it is hard to say what is better in your case.
My guess is that small feature maps should be okay unless you need the network output to contain spatial information (which you lose by using a fully connected layer anyway).


text:
Q: Make Migrations on Django I have a Django model which looks like this
class RedUsers(BaseModel):
    user_email = models.EmailField(null=True, blank=True)
    user_name = models.CharField(max_length=30, null=True, blank=True)
    red_id = models.CharField(max_length=30, null=True, blank=True)
    active = models.BooleanField(default=False)

    def __str__(self):
        return self.user_email

    class Meta:
        verbose_name_plural = "Red Users"

I want to add a new field
activation_key = models.CharField(max_length=40, null=True, blank=True)

I already have lots of data in this model and I can't drop the table, so I need to make migration manually.
I have tried adding the model from my 0001_initial.py file without luck
class Migration(migrations.Migration):
    initial = True

    dependencies = []

    operations = [
        migrations.CreateModel(
            name='RedUsers',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created', models.DateTimeField(auto_now_add=True)),
                ('modified', models.DateTimeField(auto_now=True)),
                ('user_email', models.EmailField(blank=True, max_length=254, null=True)),
                ('user_name', models.CharField(blank=True, max_length=30, null=True)),
                ('red_id', models.CharField(blank=True, max_length=30, null=True)),
                ('active', models.BooleanField(default=False)),
            ],
            options={
                'verbose_name_plural': 'RED Users',
            },
        ),
         migrations.AddField(
            model_name='redusers',
            name='activation_key',
            field=models.CharField(blank=True, max_length=40, null=True, verbose_name='activation key'),
        ),
    ]

When I run
python manage.py migrate
It says Your models have changes that are not yet reflected in a migration, and so won't be applied.
I don't know what else to do

A:
I want to add a new field
activation_key = models.CharField(max_length=40, null=True, blank=True)

I already have lots of data in this model and I can't drop the table,
  so I need to make migration manually.

You don't need to. If you run makemigrations a second time, Django will detect that you added a field, and will make an extra migration file to add that field to the model.
You thus better here remove the AddField migration object from the migration file, and run python3 manage.py makemigrations.
It will make a new file, likely something that starts with 0002_….py, and it will take the first migration as dependency.
You can then run python3 manage.py migrate, and Django will add the field at the database level, and insert the name of the migration in the migration table.


text:
Q: How to compare year month and day in java? I'n my application i want to sort the "MyDate" class so, my teacher show me how to sort but how can i compare years first and then the rest?
    Comparator<MyDate > dateCompare = new Comparator<MyDate >() {

            @Override
            public int compare(MyDate o1, MyDate o2) {

                int dd1 = o1.getDateDay();
                int mm1 = o1.getDateMonth();
//////years to compare ???????????????????
                int years1 = o1.getYear();

                int dd2 = o2.getDateDay();
                int mm2 = o2.getDateMonth();
//////years to compare ?????????????????
                 int years2 = o2.getYear();

                if (mm1 > mm2) {
                    return 1;
                } else if (mm1 < mm2) {
                    return -1;
                } else { // ==

                    if (dd1 > dd2) {
                        return 1;
                    } else if (dd1 < dd2) {
                        return -1;
                    } else {
                        return 0;
                    }
                }
            }
        };

    Collections.sort(list,dateCompare);

A: Compare the most significant field first. With a Date that is year.
Also, there is no need for a trailing else since the if and else if conditions return. Something like
if (years1 > years2) {
  return 1;
} else if (years1 < years2) {
  return -1;
}
if (mm1 > mm2) {
  return 1;
} else if (mm1 < mm2) {
  return -1;
}
if (dd1 > dd2) {
  return 1;
} else if (dd1 < dd2) {
  return -1;
}
return 0;

A: You could use the before() method of Date objects to compare the dates, it'll make writing code for your task very simple.  Of course, that means that you have to convert your MyDate objects to Date but it should be very easy.

A: You can use the built-in functionality of the GregorianCalendar class to do this in a single line.
return new GregorianCalendar(years1, mm1 - 1, dd1).compareTo(new GregorianCalendar(years2, mm2 - 1, dd2));

Note that the - 1 in the month arguments are needed because the GregorianCalendar constructor uses a month value in the range of 0 to 11.


text:
Q: Can WebRTC P2P connection be established with a peer within normal lan and a peer with symmetric lan? I have a WebRTC test application working both in LAN and with a TURN server.
I wonder why WebRTC cannot establish a "real" P2P connection if there is a NAT punchable peer but not the other.
Considering:
Peer A = Symmetric LAN peer
Peer B = Normal LAN peer
I tested that UDP was not blocked for Peer A by creating a small echo UDP server in Peer B and opening a UDP port in the router. Peer A could send AND receive messages.
For candidate negotiation and WebRTC, I thought that Peer A could get the IP:Port from STUN server, send it to Peer B and Peer B could connect to Peer A (and thus Peer A could send data back to Peer B) but looks that this is not the case.
Why would Peer A need to be accessible as well for a P2P WebRTC connection?
Why doesn't WebRTC use the socket created when Peer A sends data to Peer B to also receive data?
Very crude example of what I refer with "use the socket created when Peer A sends data to Peer B" in Python:
    import socket

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    client_address = ("127.0.0.1", 31337)
    sent = sock.sendto(b"Hello World", client_address)
    payload, client_address = sock.recvfrom(40)
    print("From Server: ", str(client_address), payload)


text:
Q: How to capture the name using Regex in the following html What would be the most reliable way of capturing the name from the following html:
Live Regex101 working example
I managed to get the name using:
View itineraryYour Guest.+?(?=>).+?(\s+[^\s].+?(?=<))

However this does not work in the code, just in the Regex example. anyone have any good ways of capturing such string?
EDIT:
This is what i was looking for.
View itineraryYour Guest\s*<[^>]*>\s*([^\s<>]+(?:\s*[^\s<>])*)

A: You can use the following regex:
View itineraryYour Guest\s*<[^>]*>\s*([^\s<>]+(?:\s*[^\s<>])*)

The \s* matches any optional whitespace symbols, <[^>]*> matches <...>-like substrings, and [^\s<>] matches any character other than <, > or whitespace.
The result is in Group 1.
See demo


text:
Q: Grails/Gradle Plugin for Grails 2.0 I'm trying to use the grails-gradle plugin with grails version 2.0.  Here is my build script:
buildscript {
    repositories {
        mavenRepo url: "http://repo.grails.org/grails/core/"
    }

    dependencies {
        classpath "org.grails:grails-gradle-plugin:1.1.1-SNAPSHOT",
                  "org.grails:grails-bootstrap:2.0.0"
    }

    grailsVersion="2.0.0"
}

apply plugin: "grails"

repositories {
    mavenCentral()
    mavenRepo url: "http://repo.grails.org/grails/core/"
}

dependencies {
    compile "org.grails:grails:2.0.0",
            "org.grails:grails-core:2.0.0",
            "org.grails:grails-crud:2.0.0",
            "org.grails:grails-datastore-core:1.0.2.RELEASE",
            "org.grails:grails-datastore-gorm:1.0.2.RELEASE",
            "org.grails:grails-hibernate:2.0.0",
            "org.grails:grails-logging:2.0.0"
}

The dependencies at the bottom of the script are different than the original "1.3.4" located here.  When I use this script to create a grails project with gradle grails-init it works correctly, creating the project.  When I try to use gradle grails-run-app I receive the following errors:
~>gradle grails-run-app
:grails-run-app
| Configuring classpath
| Error log4j:WARN No appenders could be found for logger (org.springframework.core.io.support.PathMatchingResourcePatternResolver).
| Error log4j:WARN Please initialize the log4j system properly.
| Error log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
| Compiling 38 source files

| Compiling 8 source files.....
| Error Error: The following plugins failed to load due to missing dependencies: [hibernate]
- Plugin: hibernate
   - Dependencies:
       ! dataSource (Required: 2.0 > *, Found: Not Installed) [INVALID]
       - i18n (Required: 2.0 > *, Found: 2.0.0)
       - core (Required: 2.0 > *, Found: 2.0.0)
       - domainClass (Required: 2.0 > *, Found: 2.0.0)

I'm assuming that this means I'm missing a dependency, but I have no idea what dependency.  It looks like hibernate is the culprit, but I have included the grails hibernate jar above.  The list of jars between the two versions of grails are different, so I'm not sure which should be included (or maybe there isn't one and this will not work).  The list of dependencies can be see here.
Any help resolving these errors would be much appreciated.
Using:
gradle 1.0, milestone-7 & grails 2.0.0
NOTE: the dependency "org.grails:grails-gradle-plugin:1.1.1-SNAPSHOT" is a local copy of the tip revision from github.

A: Thanks a lot. This is a very helpful thread, to answer your question, you need to add "org.grails:grails-plugin-datasource:2.0.1" on compile, it solved the problem on my machine.

A: Looks like you're missing a few dependencies... Check Gradle / Grails application for a complete example of how to do this.
Hope this helps!


text:
Q: Remove comma after last object in the Schema array with PHP WordPress Loop I have a "Product" Google Schema Markup with the pasted loop for the "Reviews".
Here's a part of the Markup's code:
     "review": [
            <?php
            $args = array(
            'post_type' => 'my_reviews',
            'category_name' => 'my-product',
            'paged' => $paged);

            $loop = new WP_Query($args);
            if ($loop->have_posts()) :
            while ($loop->have_posts()) : $loop->the_post(); ?>
{

            "@type": "Review",
            "reviewRating": {
              "@type": "Rating",
              "ratingValue": "5"
            },
            "author": {
              "@type": "Person",
              "name": "<?php the_title(); ?>"
            },
            "reviewBody": "<?php echo get_the_content(); ?>"},
    <?php
    endwhile;
    endif;
    wp_reset_postdata();
    ?>],

          "aggregateRating": {
            "@type": "AggregateRating",
            "ratingValue": "5",
            "bestRating": "5",
            "ratingCount": "<?php echo count_cat_post('My Product'); ?>"
},

Everything works as it should, except that after } of the last object, a comma is still trapped.
And it turns out something like the following:
   "review": [{
        "@type": "Review",
        "reviewRating": {
          "@type": "Rating",
          "ratingValue": "5"
        },
        "author": {
          "@type": "Person",
          "name": "John Doe"
        },
        "reviewBody": "Review 1 Content"
      },
      {
        "@type": "Review",
        "reviewRating": {
          "@type": "Rating",
          "ratingValue": "1"
        },
        "author": {
          "@type": "Person",
          "name": "Jane Doe"
        },
        "reviewBody": "Review 2 Content."
      }, <-- this is the comma I need to remove
],
      "aggregateRating": {
        "@type": "AggregateRating",
        "ratingValue": "88",
        "bestRating": "100",
        "ratingCount": "2"
      },

How can I remove it?

A: in wordpress loop you have property current_post for index and post_count for total number of posts. You can use condition ($loop->current_post + 1 != $loop->post_count) to compare that it is not a last post then you can print comma.
so your code for get_the_content  should be like this:
"reviewBody": "<?php echo get_the_content(); ?>"} <?php if ($loop->current_post + 1 != $loop->post_count) { echo ','; } ?>
Update for all others : I know json_encode is correct way but he said in comment that he want it like this. But for future viewers, Correct approach should be like this :
// define reviews array
   $reviewArr = [
       'review' => [],
       'aggregateRating' => []
   ];

   // get and loop through posts
    $args = array(
    'post_type' => 'my_reviews',
    'category_name' => 'my-product',
    'paged' => $paged);

    $loop = new WP_Query($args);
    if ($loop->have_posts()) :
    while ($loop->have_posts()) : $loop->the_post();

        // new post review
        $post_review = [

            "@type" => "Review",
            "reviewRating" => [
              "@type" => "Rating",
              "ratingValue" => "5"
            ],
            "author" => [
              "@type" => "Person",
              "name" => "<?php the_title(); ?>"
            ],
            "reviewBody" => get_the_content()
        ];

        // insert the post review in reviews array
        $reviewArr['review'][] = $post_review;

    endwhile;
    endif;
    wp_reset_postdata();

    // aggregate rating
    $aggRating =  [
        "@type" => "AggregateRating",
        "ratingValue" => "5",
        "bestRating" => "5",
        "ratingCount" => count_cat_post('My Product')
    ];

    // insert in reviews array
    $reviewArr['aggregateRating'] = $aggRating;

    //  here you get your json
    $json = json_encode($reviewArr);

A: You hould not be creating JSON by concatenating with a loop, instead within the loop you should be adding your text to an array, and then use implode(',',$yourArray) to convert the array to a JSON, where that last comma would not exist.
Or even better approach is to create nested arrays, and use json_encode() function to create a valid JSON out of a nested array.


text:
Q: Handlebody cross an interval An $n$-dimensional handlebody with $g$ handles is the result of attaching $g$ $n$ dimensional 1-handles to a single $n$-dimensional $0$-handle in such a way that the result is orientable.  Is it in general true that if $H$ is an $n$-dimensional handlebody of genus $g$, then $H \times I$ is an $(n+1)$-dimensional handlebody of genus $g$?
I am not really sure how to identify manifold as being a handlebody in the first place.  In dimension $3$, I know that when identifying a handlebody, you try and cut along disks and get a bunch balls and the number of disks and balls that you have allow you to determine $g$.  Is a similar thing true in higher dimensions?

A: A "handlebody" in higher dimensions (be careful because in higher dimensions people usually use this word to mean any manifold with a handle decomposition) is a boundary connect sum of $S^1 \times B^{n-1}$. If you have an $n$-dimensional handlebody, then there is a set of codim 1 balls which you can cut along so every piece is just $S^1 \times B^{n-1}$. When you cross these balls with $I$ you get $n$-dimensional balls cutting your manifold into pieces which are just $S^1 \times B^{n-1}\times I = S^1 \times B^n$.


text: Q: How to make a manipulatable map that can change color? I want to color the world map differently according to how much the number of each country. For example, USA using renewable energy for 20% should be colored lighter than Canada using renewable for 50%. However, I want it to be manipulatable too because the number changes every year. Can I do that?


text:
Q: Fixing "ImportError: No module named qgis.core"? First of all, I'm using Python 2.7.3, QGIS 1.8 (Lisboa) on Windows 7 pro 64 bits.  Now let's go to the actual question:
I have written some code (Python) that works well within the QGIS built in Python console, but now I need to run it from outside QGIS (it is too much to ask for the final user to open QGIS, then the python console and to copy and paste the code).
I have been trying to access the QGIS API, but it is missing from my PYTHONPATH. I've tried whatever is on the instructions, plus a bunch of paths like:
 C:\Program Files(x86)\QGIS\apps\qgis\python\qgis and  C:\Program Files(x86)\QGIS\apps\qgis\python. My result so far is always the same:
import qgis.core
ImportError: No module named qgis.core

Any ideas?

A: It is possible that you have a separate Python installation on your system in addition to Python being bundled with QGIS and PyQGIS is installed only for the bundled Python.
Check if you have two separate Python installations and if you do, try running the script by specifying the full path to the Python executable under the QGIS installation. If that works you'd need to make sure that the PYTHONPATH and/or PATH variables first find the Python under QGIS, because (as far as I know) PATH is only checked until it encounters the first instance of whatever is being looked for...

A: For new users reading this post, you can find a way of solving errors about importing qgis modules on Windows 7 at Problem with import qgis.core when writing a stand-alone PyQGIS script.

A: Add this to PATH variable (replace "C:\Program Files\QGIS Valmiera" with QGIS install location):

C:\Program Files\QGIS Valmiera\bin;C:\Program Files\QGIS
  Valmiera\apps\qgis\bin

and this to PYTHONPATH variable:

C:\Program Files\QGIS Valmiera\apps\qgis\python;
  C:\Program Files\QGIS Valmiera\apps\qgis\python\plugins;
  C:\Program Files\QGIS Valmiera\apps\Python27\lib\site-packages

A: This worked for me from A note on configuring your IDE on Windows and tere is available information for Eclipse and Pydev, I just like using Pyscripter
If you used the OSGeo4W Installer, you can find this under the bin folder of your OSGeo4W install. Look for something like C:\OSGeo4W\bin\qgis-unstable.bat.

*

*For using Pyscripter IDE, here's what you have to do:

*Make a copy of qgis-unstable.bat and rename it pyscripter.bat.

*Open it in an editor. And remove the last line, the one that starts
QGIS.

*Add a line that points to your Pyscripter executable and add the
commandline argument that sets the version of Python to be used (2.7
in the case of QGIS >= 2.0)

*Also add the argument that points to the folder where Pyscripter can
find the Python dll used by QGIS, you can find this under the bin
folder of your OSGeoW install
@echo off
SET OSGEO4W_ROOT=C:\OSGeo4W
call "%OSGEO4W_ROOT%"\bin\o4w_env.bat
call "%OSGEO4W_ROOT%"\bin\gdal16.bat
@echo off
path %PATH%;%GISBASE%\bin
Start C:\pyscripter\pyscripter.exe --python25 --pythondllpath=C:\OSGeo4W\bin
Start C:\pyscripter\pyscripter.exe --python25 --pythondllpath=C:\OSGeo4W\bin
Now when you double click this batch file it will start Pyscripter, with the correct path.

A: I tried to write a stand alone python script to use QGIS and encountered the same issue. I was using Ubuntu 20.04 and the QGIS version was version 3 family. The solution was:
import sys
sys.path.insert(0,"/usr/lib/python3/dist-packages")
import qgis

Note that you can use "Import qgis" after using the "sys.path.insert" command line.
Thanks to this link. I have found this solution from the link.


text:
Q: Sending DatagramPacket with no internet connection - Android I'm using the following code to send DatagramPacket to a given address:
InetAddress address = InetAddress.getByName(anIPAddress);

DatagramSocket socket = new DatagramSocket();
DatagramPacket packet = new DatagramPacket(packetBytes, packetBytes.length,
    address, port);

socket.send(packet);
socket.close();

It works fine, but how come this code does not throw any Exception when there's no internet connection available?
I turn off both Wi-Fi and mobile data, and this code still gets executed without any errors.
Is there a way to ensure that the packet is actually sent?
(i don't care if it's reached the destination or not, i'd just like to make sure it is sent)

A: You can use NetworkInterface.getNetworkInterfaces(); to check what interfaces are available.
Then you can check with ni.isUp().
Enumeration<NetworkInterface> nets=NetworkInterface.getNetworkInterfaces();
for(int i=0; nets.hasMoreElements(); ++i) {
    NetworkInterface ni=nets.nextElement();
    if (ni.isUp() && !ni.getName().equals("lo")) {
        //ni is not local
        break;
    }
}

A: Connect the datagram socket to the destination. Then after a few sends you may get an exception. If the datagram socket isn't connected there's an error routing issue which I cannot remember offhand: I'll edit it in when au get a chance to look it up.
And yes I know UDP is a connectionless protocol. But you can still connect a UDP socket.


text:
Q: Sinon Not Mocking db-mysql Node.js library I am trying to mock my database using Sinon with Mocha in Node.js for testing. I've tried the following:
var sinon = require('sinon');
var mysql = require('db-mysql');

beforeEach(function() {
  var db = sinon.mock(mysql);
  db.expects('execute');
});

but I keep getting the following error: TypeError: Attempted to wrap undefined property execute as function
I assumed that this is mocking the class and not the database instance. So I mocked the instance by doing var db = sinon.mock(new mysql.Database()); instead. When I did that, then all the valid methods for the db-mysql instance are passing, such as db.connect() and db.query(), no matter what the arguments are. I am unable to set behaviour. To set the behaviour, I am trying to call .expects on db but I get the following error:
TypeError: Object [object Object] has no method 'expects'
What's the right way to set the expected behaviour? Furthermore, how can I test several behaviours for the same function? Will I need to do this within each test according to what the test expects?

A: That's because execute is part of query object and not the database itself.
https://github.com/mariano/node-db-mysql#quick-start


text:
Q: Redmine Project Repository Location I have redmine set up using bitnami on windows I created a project and added a repository by location successfully. Now I'm trying to clone this via redmine,
ex
git clone http://localhost/git/myproject

 or

git clone http://localhost/redmine/git/myproject

The repository of the project is located in the htdocs\git\myproject folder, but when I try this it says repo not found. What is the link for redmine repos, or do I have to move the local repo elsewhere on the server to work?

A: I'm not sure about git, but for Mercurial you need to insert the local path of the repository. It looks like that also the case for git. So you'll need to set the repository to /htdocs/git/myproject


text:
Q: Central limit theorem does not converge to random variable Recently, we investigated whether the expression in the central limit theorem converges to a random variable pointwise almost sure? The answer was negative due to $P ( \text{limsup} \frac{X_1+...+X_n}{\sqrt{n}} = \infty)=1$. But I don't really understand this reasoning? I suspect that for almost sure convergence we would need to have that the sequence $\frac{X_1+...+X_n}{\sqrt{n}}$ is almost surely bounded, but I am not quite sure about this.

A: *

*A convergent sequence is bounded.

*If $(x_n)_{n\geqslant 1}$ is a sequence of real numbers such that $\limsup_{n\to \infty}x_n= +\infty$, then this sequence is unbounded.


text:
Q: Android unable to share file as an attachment I want to share a file as an attachment only with the email clients installed on the users device. For this, I am using the below code:
String tmp = "file://" + commonMethods.getFromPreferences(Constants.fileNameKey, "string");

Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.shareEmailSubject));
emailIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.shareEmailText));
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(tmp));

((Activity) getContext()).startActivityForResult(emailIntent, 1);

With the above code, if I share the file with GMail application, it works fine. But if I share them with Inbox or Outlook application the file does not get added as an attachment.
Is there anything that I am missing or needs to be done?

A: If you read the documentation, ACTION_SENDTO does not take any extras. There is no requirement for any app to honor any of those extras, let alone all of them.
Beyond that:

*

*FLAG_GRANT_READ_URI_PERMISSION works for content: Uri values, not file: Uri values.

*The other apps may not have read access to wherever this file is stored (e.g., external storage).

*ACTION_SENDTO with a mailto: Uri does not limit you to "the email clients installed on the users device". Any app can implement an activity that has a matching <intent-filter>.


text:
Q: Limit the JFileChooser's allowed selection without using .setFileSelectionMode Currently I'm attempting to replicate NetBeans' "Open Project" file choosing dialog because I would like a similar system of selecting a folder that meet certain conditions. However, I'm having trouble forcing the dialog to choose those that meet my condition and not any folder. How could I go about doing this?
EDIT: the condition needed to be met in order for a folder to be considered a NetBeans Project is that it needs to contain a nbproject folder.
So far, I've tried using .setFileSelectionMode, but that's not restrictive enough for my purposes.
My code (in main method):
JFileChooser chooser = new JFileChooser();
FileFilter filter = new FileFilter() {
    @Override
    public boolean accept(File f) {
        if (f.isDirectory()) {
            // check if this folder is a NetBeans Project
            File[] list = f.listFiles();
            for (File sub : list) {
                if (sub.isDirectory()) {
                    if (sub.getName().equals("nbproject")) {
                        return true;
                    }
                }
            }
                return false;
        } else {
            return false;
        }
    }

    @Override
    public String getDescription() {
        return "NetBeans Projects";
    }
};

// so I can select the folder...
// ...but I only want the user to be able to select stuff my filter accepts
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

chooser.addChoosableFileFilter(filter);
chooser.setFileFilter(new FileFilter() {
    @Override
    public boolean accept(File f) {
        return f.isDirectory();
    }

    @Override
    public String getDescription() {
        return "Folders";
    }
});
chooser.setAcceptAllFileFilterUsed(false);

chooser.showOpenDialog(null);

ADDENDUM: Here's a example file structure that I would have to navigate:
C:\USER\Documents\NetBeansProjects
|- Project
   |- nbproject
|- New Folder (empty)

I want to only be able to select the Project folder and not New Folder. Both still need to be visible. However, when I select New Folder, the program approves and closes the window.
This is not the behavior I want. Instead, I want the window to simply open the folder.
(sidenote: I don't really want to rewrite an entire class just for this purpose. But if it does come down to that, I could use a workaround that won't need this to happen.)

A: It seems that there is no direct way or approach to solve this problem. I'll use my workaround instead, then.
The impetus for selecting the folder was to make serialization easier (one object per file), but I'll just stuff everything in one file instead.


text:
Q: Weld-SE not logging with log4j2 Im using weld-se and log4j2 for logger. But I cannot get anything from Weld. Other logging works fine.
Libraries:
    <dependency>
        <groupId>org.jboss.weld.se</groupId>
        <artifactId>weld-se-core</artifactId>
        <version>2.2.4.Final</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.0.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.0.2</version>
    </dependency>

log4j2.xml
<Configuration status="INFO">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
    </Appenders>
    <Loggers>
        <logger name="org.jboss.weld.level" level="debug"/>
        <Root level="debug">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>
</Configuration>

Thank you for advice.

A: Try using the SLF4J implementation for Log4j 2:
<dependency>
    <groupId>org.jboss.weld.se</groupId>
    <artifactId>weld-se-core</artifactId>
    <version>2.2.4.Final</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.0.2</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-slf4j-impl</artifactId>
    <version>2.0.2</version>
</dependency>

JBoss Weld use the class org.jboss.logging.LoggerProviders for find a logging provider. If you see the code of this class, you will see that looks for a system property, org.jboss.logging.provider.
You can added to jvm arguments or you can emulate it. e.g.:
public class App {

    static {
        System.setProperty("org.jboss.logging.provider", "slf4j");
    }

    public static void main(String[] args) {
        Weld weld = new Weld();
        WeldContainer container = weld.initialize();
        // Do something
        weld.shutdown();
    }

}


text:
Q: Can I recharge a battery that I don't know anything about? I like electronics but I basically don't know anything about it (electricity is too complex), the thing is that I've opened a battery from an old laptop that reads "10.8 V 4300 mAh Li-ion"
The battery-pack contains other 6 batteries and a circuit inside, I suppose that the circuit is just for showing battery info in the computer, charge indicator and for preventing 'overcharge'. Batteries shows 2x 0.0 V, 2x 3.11 V and 2x 3.17 V (with a tester), but that's just their current charge, there's no info on them more than a serial number so...
There's a way to SAFELY recharge them? I'm not in a hurry so time is not a problem.
I thought about put them 0.5 V higher than they currently have over and over until they don't get any higher voltage, but I'm not sure if that will work nor if that will even recharge them.
PS: I thought that Li-Ion batteries didn't contain a pack of standard batteries inside...

A: If you know nothing about them then be aware that some batteries are not designed to be recharged and can explode if charging is attempted.
For rechargable batteries there is a different charging scheme for each technology. Do it wrong and the battery is likely to explode or catch fire.
I strongly urge that, since by your own assertion that you know nothing about these batteries, STOP experimenting around before you end up hurting yourself, others or destroying property.

A: You have a standard 2P (two parallel) and 3S (3 in series) laptop battery. And yes, all laptop batteries are made of standard cells, from variants of 18650 or 17650 cells. Or flat proprietary cells.
As Simon noted, you have one dead section. While the chances to recover full functionality are small, you can try.
You need to try to "pre-charge" the dead section, which can be done with a small, ~200 mA current applied to this section alone. You don't need to desolder anything, just find a way to connect external leads temporary. The best would be a benchtop power supply, set it to 4.2 V and 200mA current limit. Alternatively you can try a USB charger with a 22 - 33 Ohms resistor in series. After one-two minutes check if the cell builds any voltage. If the voltage goes above 2.5-3 V, you can stop the pre-charging and try to charge the whole battery inside your laptop, using the laptop's AC-DC adapter. I had some successful recoveries using this method.
ADDITION: for those who spread myths about explosiveness of over-discharged batteries. Here is a scholar research on the subject, "Effects of overdischarge on performance and thermal stability of a Li-ion cell" No explosive effects or thermal run-away instabilities were found, other than a loss of capacity (sometimes drastic).
NOTE OF CAUTION: The cells inside laptop batteries don't have built-in protection as many stand-alone cell have nowadays. Be careful not to short them with thick wires. Although no Li-Ion cell explode, they can rapidly "vent", which is sometimes accompanied by flames.

A: It is not safe to charge them anymore.
If Lithium batteries drop below a certain voltage, it is dangerous to recharge them. That small board that you have seen has many utilities. It cuts the current to ensure that you never discharge your battery more than this level plus a security margin. It also prevents you to charge it again in case it has discharged naturally below that level, and it also prevents you to charge it over its limit.
If one of your batteries shows 0V it means that it has gone below the non-return level, so don't play with it (unless you want to make it explode).


text:
Q: fedora linux environment, select fails in mysql In c this code fails:
result = mysql_query(conn, "select username from golfer");

However, previously executed MySQL_init and mysql_real_connect successfully works.
There is nothing wrong with the code, it works perfectly when connecting to a different server. I can successfully execute the failing query from a terminal, i.e.,
MySQL> select username from golfer;

All the queries work great as long as I execute them from a terminal. So it appears the data base is set up correctly. I checked the following:

*

*table User in db MySQL shows correct username and host.

*table User in db MySQL shows localhost, correct user, correct password, and Select_priv = Y.

In data base MySQL, tables db, host, tables-priv and column-priv are identical in both servers. But the code fails when connecting to one server but not the other.
I do not know the error code coming back because it would take a substantial effort to get it. Therefore, is there any other permissions, whatever, that I should be looking at?
This is 5 year old code that has been working perfectly. Trying to port to new server. I looked at grants for username@host, It said:
grant all privileges on 'correct database'.* to correct 'username'@'localhost'

So, that looks right to me.
EDIT:
I am trying to get error code from failing MYSQL query. Code follows:
#define CANNOT_CONNECT 2

MYSQL *conn;
char *server = "localhost";
char *user = "myname";
char *password = "";
char *database = "golfprob";
int result = 10;
int error_num = 0;
int no_char;
char insert[70];

freopen("home/Dave/stderr.log", "w", stderr);
conn = mysql_init(NULL);

if (!mysql_real_connect(conn,server,user,password,0,NULL,0))
    return(CANNOT_CONNECT);

noChar = sprintf(insert, "select username, password from golfer");
result = mysql_query(conn, insert);

if (result != 0)
{
    error_num = mysql_errno(conn);
    fprintf(stderr, "Query Failed: Error: %s\n", mysql_error(conn));
    fclose(stderr);
    mysqlL_close(conn);

    return(error_num);
}

The query fails.
Upon execution, error_num = 3 which is not a valid MySQL error code.
No output is printed on stderr. I'm not sure what display is stderr or if stderr makes any sense in this context.
As you have gathered, I am trying to write the error in text to a file.
No file is written anywhere. Please educate me as to why.
Important aspects of the environment:
Code is executing out of /var/www/cgi-bin in apache web server
Code is triggered by entry on web page, MS IE is browser.
computers are networked by intranet.
I welcome any insightful comments.
Thanks--

A: Problem solved: see the comments that are posted with the question. (It is obvious I do not know how to use this forum).


text:
Q: QSqlQuery Not Executing When Using Table Variable I am using Python 3 and PyQt 5 to execute a query that includes a table variable. My other queries work, but this specific one is causing me issues. The query is:
declare @Temp table
(
    SKU varchar(25),
    Lines int
)

insert into @Temp
SELECT convert(varchar, [Sku]) as [SKU]
    ,count([Order Number]) as [Lines]
from [Database].dbo.[Table Name]
GROUP BY [Sku]
ORDER BY [LINES]

Select RANK() OVER(Order by Lines Desc) / (Select Convert(float,Count(*)) from @Temp) as [CUM PERCENT SKU]
    ,sum(Lines) Over(Order by Lines Desc) / convert(float,sum(Lines) Over()) as [CUM PERCENT LINES]
from @Temp
Order By [Lines] DESC

I replaced the Database name and the Table name, but the rest of the text is the exact query.
Executing the above in SQL Server 2012 works perfectly. Is there a limitation to QSql that I don't know about?
Thank you in advance!

A: After a bit more research, it turns out that you need to use prepare() when you are trying to create a table (apparently even a temporary one).
I'm posting the answer in case anyone else has the same issue and doesn't feel like going through the C++ StackOverflow answers.
query = QSqlQuery()
query.prepare(*query text here*)
query.exec_()


text:
Q: What is a good reason why reinforcement learning relies on Q value instead of the reward r? I am new to reinforcement learning and I am reading off of some tutorial materials, but I have noticed a seldom discussed assumption that we should calculate our action based on Q-value instead of the reward.
Is there a simple reason why this is the case?
Consider the bandit problem. What happens if we did not use Q-value, but simply used the reward to select our strategy? It seems if we see our action yields the highest reward, we should simply repeat our action, instead of calculating some estimate on the reward and base off our decision on the estimate.
Further, wouldn't greedy action selection (or Boltzmann action selection, etc.) make much more sense because we are selecting our action based on highest reward instead of the highest estimate, which may not even be a good estimate?
Lastly, it seems that this would model real life scenario much more closely. I haven't noticed anybody calculating a Q-value in their head when making decisions in reinforcement learning scenarios, almost all of our decisions are based on the immediate (and most frequently, deterministic) reward, especially in game scenarios.
I apologize in advance if this seems to be a really novice observation.

A:
I have noticed a seldom discussed assumption that we should calculate our action based on Q-value instead of the reward.

I think you are getting confused about how estimates, Q-values and knowledge of rewards are arrived at. Ultimately, all reinforcement learning (and the related bandit problems) are concerned about is maximising long-term reward.
$Q$ usually represents either the expected value of $r$ (in bandit problems) or the total of a series of $r$ values expected in future actions. Either way, experiencing a single value of $r$ is rarely enough information for an agent to learn all that it needs to know. The $Q$ value holds accumulated knowledge gained by the agent when it experiences multiple different $r$ values over time.

Is there a simple reason why this is the case?

The key things about the optimisation problems presented in reinforcement learning is how much knowledge the agent starts with about the available rewards and dynamics of the system.
In many reinforcement learning systems, rewards are sparse. In a game for instance, the only rewards might be +1 for winning and -1 for losing. It is not possible to act directly on that knowledge at the start of the game. In order to choose between actions early on in a game, something has to assign a value to those actions. Typical approaches are:

*

*Search through possibilities and combinations until reliable values are found.

*Assign some values based on expert knowledge.

*Have machine calculate values based on experience of the game.
It is possible to combine all three approaches, and many game-playing routines will combine the first approach (search) with one or both of the other methods. Reinforcement learning is concerned with the last method in this list only, and is not the only way to tackle deterministic environments of games.

Consider the bandit problem. What happens if we did not use Q-value, but simply used the reward to select our strategy? It seems if we see our action yields the highest reward, we should simply repeat our action, instead of calculating some estimate on the reward and base off our decision on the estimate.

Used which reward? The last reward value received when taking the given action? Yes this would work provided the reward was always the same fixed value for each action. This is the same as having a learning rate of 1 - all you need to do is sample each action once, learn the single static reward value, and then the learning agent is done.
However, a deterministic bandit problem with fixed reward values is not an interesting problem. That is literally working through a list and taking the maximum. If that is your actual problem to solve, then you don't need any statistics or machine learning.
Instead, bandit problems are formulated to deal with rewards that are drawn from a random distribution, different for each action, that are not known by the agent (in tests of different bandit solvers, they might be known to the tester). That means when the agent observes a single reward for the first time, it cannot know whether it has a value that represents the expected reward, it could have been lucky or unlucky. The agent has no good option available to it other than to maintain an estimate of the expected reward and refine it as it gains more experience with the action. The different types of bandit solvers are usually assessed in how they can make the best use of this limited knowledge so that total reward is maximised whilst having to go through this experience and estimate-building process.

Further, wouldn't greedy action selection (or Boltzmann action selection, etc.) make much more sense because we are selecting our action based on highest reward instead of the highest estimate, which may not even be a good estimate?

No, this only makes sense if you already know what the highest reward is for each action at the point it is taken. In reinforcement learning, you generally make the assumption that you do not know this. However, if you do know that all state transitions and rewards are static, with no random effects, then you can take advantage of this with a high learning rate and a low exploration rate. That is close to your idea.
There is still one remaining problem even then in the full reinforcement problem, and with completely static non-random behaviour though - that is the number of states and actions, and how they connect. You might know that transitioning from state Y to state Z gives a reward of +100 and all other transitions give a reward of -1, but that does not tell you yet how to behave when in state A. In order to explore the state connectivity, which you do not know (or may be far too large to search exhaustively), you must explore, effectively randomly, and that means whenever you make that connection and find a route [e.g. A, C, N, Y, Z] and score +97, you do not for certain that the value of state A is +97, because there could be other routes. So that would be an estimate.

Lastly, it seems that this would model real life scenario much more closely. I haven't noticed anybody calculating a Q-value in their head

You probably have not noticed anyone calculating a full search tree, or performing minimax alpha beta pruning in a mathematically rigorous way either.
Even in deterministic games, if they are complex enough, then a lot of assessment is done by feel for good and bad positions gained through experience. That "feel" of the value of controlling a bit of the board, or having a good or bad hand in a game of cards is maybe a reasonable analogy to the Q value. This can be augmented by logical search, comparing exact moves into the future in your mind - and that is analogous to how reinforcement-learning based games bots work, they use Q-values as a heuristic to guide searches through logical deterministic play.
Here's maybe a good analogy to Q value in your head: When you play tic-tac-toe (aka noughts and crosses), then you probably know to play in the centre or a corner on your first move. It is highly unlikely that you calculate out the combinations of moves and arrive at that from scratch each time. That is similar to your brain telling you the max $Q$ value, learned from experience.
A lot of games based on fixed moves can have game bots based on tree search. They typically use heuristics to guide the search (e.g. having pieces in the corner is worth more in Othello, the queen is worth 9 points in chess). You can think of the Q-value as a machine learnt version of those heuristics where instead of an expert saying queen is worth 9 pawns, and coding it into the search routine, the machine has determined something similar through experiencing the games.


text:
Q: Why should I use HTML validators along with Angular Form Validators In the Angular documentation, its is recommended to use HTML validators (eg required) along with Angular validators eg. Validators.required. The reason is:

Use these HTML5 validation attributes in combination with the built-in validators provided by Angular's reactive forms. Using these in combination prevents errors when the expression is changed after the template has been checked.

But I didn't understand it well. Why should I use both? Isn't just Angular's form validators sufficient?