问:
Ajax not working with Node js - Express js
Im trying to send data from my server side to my client side with ajax but when i use res.send(data) in node, it show me a empty html with the data and i want to get data from my client side without reloading the page and edit something in my actual html

Here's my server-side code

```<code>    app.post('/',(req,res)=>{
    var userName = req.body.username;
    var password = req.body.password;

    connection.query('SELECT * from admin',(err, rows, fields)=> {
      if (!err){
        if((userName == rows[0].usuario) && (password == rows[0].contraseña)){
            res.sendStatus(200);

        }else{
            res.send('Incorrect username or password')
        }
      }else{
        res.send('Error while performing Query.');
      }

    });

});
</code>```

Here's my client-side code

```<code>$(document).ready(function(){
$('#login-form').submit(function (e) {
        setTimeout(function () {
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: '/',
            dataType: 'jsonp',
            data: ({username: $('input[name=username]'),password: $('input[name=password]')}),
            success: function(data,textStatus){
                if(textStatus.statusCode == 200) {
                    $('.error-user').html('Succes');
                }else{
                    $('.error-user').html('Not Success');
                }

            },
        });
        }, 1000);

});
});
</code>```

UPDATE: I removed the setTimeOut() but when I submit the form the page freeze like two seconds and then nothing happen, I get this 'error Maximum call stack size exceeded', dont get me data just stay in the same view if like post method was never called

UPDATE-FINAL: I got values from input outside of the ajax and it works nice,thanks :#

答: Remove the setTimeout which is preventing your preventDefault from running in the actual event handler and causing you to see the response in the browser load rather than ajax handler, and debug from there.</p>

Body:
Im trying to send data from my server side to my client side with ajax but when i use res.send(data) in node, it show me a empty html with the data and i want to get data from my client side without reloading the page and edit something in my actual html

Here's my server-side code

    app.post('/',(req,res)=>{
    var userName = req.body.username;
    var password = req.body.password;

    connection.query('SELECT * from admin',(err, rows, fields)=> {
      if (!err){
        if((userName == rows[0].usuario) && (password == rows[0].contraseña)){
            res.sendStatus(200);

        }else{
            res.send('Incorrect username or password')
        }
      }else{
        res.send('Error while performing Query.');
      }

    });

});

Here's my client-side code

$(document).ready(function(){
$('#login-form').submit(function (e) {
        setTimeout(function () {
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: '/',
            dataType: 'jsonp',
            data: ({username: $('input[name=username]'),password: $('input[name=password]')}),
            success: function(data,textStatus){
                if(textStatus.statusCode == 200) {
                    $('.error-user').html('Succes');
                }else{
                    $('.error-user').html('Not Success');
                }

            },
        });
        }, 1000);

});
});

UPDATE: I removed the setTimeOut() but when I submit the form the page freeze like two seconds and then nothing happen, I get this 'error Maximum call stack size exceeded', dont get me data just stay in the same view if like post method was never called

UPDATE-FINAL: I got values from input outside of the ajax and it works nice,thanks :#


来源: stackexchange

问:
how to syncronize cordova and android studio for debugging?
I have latest version of android studio and android sdk, but I always get gradle version error
commnad: "cordova run android"
so I can't run on device but I can run it on android studio with gradle updating.
what's the problem. </p>

答:
you should delete node-modules folder first and rebuild node-modules using packages.json file</p>

```<code>{
  "name": "Your app name",
  "version": "1.1.0",
  "description": "Renelco FSE for Android 6.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "platforms": [
    "ios",
    "android"
  ],
  "cordovaPlatforms": [
    "android@6.0.1"
  ],
  "cordovaPlugins": [
    "cordova-plugin-camera@1.1.0",
    "cordova-plugin-contacts@1.1.0",
    "cordova-plugin-device@1.0.1",
    "cordova-plugin-file@2.1.0",
    "cordova-plugin-media@1.0.1",
    "cordova-plugin-media-capture@1.0.1",
    "cordova-plugin-network-information@1.0.1",
    "cordova-plugin-splashscreen@2.1.0",
    "cordova-plugin-statusbar@1.0.1",
    "cordova-plugin-vibration@1.2.0",
    "com.ionic.keyboard@1.0.5"
  ],
  "devDependencies": {
    "load-grunt-tasks": "~0.4.0",
    "time-grunt": "~0.3.1",
    "grunt": "~0.4.4",
    "grunt-shell": "~0.6.4"
  },
  "dependencies": {}

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
you should delete node-modules folder first and rebuild node-modules using packages.json file

{
  "name": "Your app name",
  "version": "1.1.0",
  "description": "Renelco FSE for Android 6.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "platforms": [
    "ios",
    "android"
  ],
  "cordovaPlatforms": [
    "android@6.0.1"
  ],
  "cordovaPlugins": [
    "cordova-plugin-camera@1.1.0",
    "cordova-plugin-contacts@1.1.0",
    "cordova-plugin-device@1.0.1",
    "cordova-plugin-file@2.1.0",
    "cordova-plugin-media@1.0.1",
    "cordova-plugin-media-capture@1.0.1",
    "cordova-plugin-network-information@1.0.1",
    "cordova-plugin-splashscreen@2.1.0",
    "cordova-plugin-statusbar@1.0.1",
    "cordova-plugin-vibration@1.2.0",
    "com.ionic.keyboard@1.0.5"
  ],
  "devDependencies": {
    "load-grunt-tasks": "~0.4.0",
    "time-grunt": "~0.3.1",
    "grunt": "~0.4.4",
    "grunt-shell": "~0.6.4"
  },
  "dependencies": {}

}


问:
Input Onkeyup can be avoided by form autocomplete
I'm validating a field using OnKeyUp. Unfortunately it is not running when the user selects an autocomplete suggestion in his browser.

I would like to know if there is any way I can trigger my JavaScript when the user clicks in the browser input suggestions.

答:
One options you could take would be triggering events using the custom event model by YUI
http://developer.yahoo.com/yui/event/#customevent

By doing this you can explicitly fire/trigger the way you see fit

ContentLicense: CC BY-SA 2.5


问:
DHGEX failing with 2048-bit key under Java 8, but succeeding with 1024-bit key
I'm using JSCH 0.1.53 to connect to a remote SSH server, which uses a 1024-bit RSA key.  We are able to connect successfully to the remote server when we also use a 1024-bit RSA key, but when we generated stronger 2048-bit keys we stopped being able to connect.  We got an error message that reads "prime size must be multiple of 64, and can only range from 512 to 2048" and that originates from a call to DHGEX.java (Diffie-Hellman Group EXchange).

We're running Java 1.8, and the error message correctly specifies a max bit size of 2048, so the problem is not the JCE key limitation of 1024 bits in Java 1.6 and 1.7.  And we've confirmed that both our private and our public key are in fact 2048 bits, via openssl rsa -text -noout -in id_rsa and ssh-keygen -lf id_rsa.pub.

Since everything looked fine on our end, I started adding debugging lines to the JSCH code and recompiling the JAR, and I was eventually able to determine that the modulus being passed to us during the key exchange was in fact 2047 bits long.  Now, 2047 bits in length doesn't inherently mean that you didn't generate a 2048-bit key or that it's any less strong than a key that actually contains 2048 bits, it just means that you happened to get two primes that multiplied together to something whose first bit was a 0. So it's expected behavior (some of the time) and the JCE check should probably be (n % 64 == 0 || n % 64 == 63).  But JCE is a stickler on the point, so it rejects this key for not being of a length it considers valid.

Based on that, I thought I'd found the problem: the remote server had generated a 2048-bit key that only contained 2047 bits, so they just needed to generate a new one (and keep doing it till they got one that really was 2048 bits).  But when I asked their administrators about it, they were insistent that they were using a 1024-bit key, and indeed that's what you get in the known_hosts file when you SSH over.  So that doesn't appear to be the cause after all.

So I started logging the contents of the buffer that contained what they sent us and pulling out the p and g values (modulus and group), and I discovered that in just a few short periods of testing over a couple of days, there were 33 different modulus values, and all of them differed by only the last few characters when encoded in either base 64 or base 10.  Modulii values were reused, sometimes only once and sometimes a dozen times, but there were lots of distinct values, so the keys are neither generated for one-time use nor generated once and reused forever.

Is this (having the server send many different keys that are very close numerically, with some reuse but many unique values) expected behavior under any conditions, and especially is this expected behavior when the client uses a 2048-bit key but the server uses a 1024-bit key?  I know nothing about Diffie-Hellman group exchange besides what I've read since I started investigating last week, so maybe this is just how it works, but it seems strange to me.

Also, does the SSH standard specify anything about how keys should be generated in cases like these?  I haven't yet found out what SSH server the far side is using (I suspect OpenSSH, but don't know for sure and don't know what version), but I'm hopeful that there might be some standard that forces the use of keys that are of the same size as was requested (between 1^(n-1) and 1^n - 1), and that the remote server might have an option to force this or that I can submit a bug against them to get them to change the behavior.  I'll probably also submit a bug against the JDK to allow keys of n-1 bits, with 0-padding for the first bit.

Any guidance that anyone can give would be greatly appreciated.

I've also posted this question to the JSCH mailing list: https://sourceforge.net/p/jsch/mailman/message/35042955/

UPDATE:

After further reading, I believe that Diffie-Hellman's forward secrecy characteristic means that different primes (often from a pre-generated set stored somewhere like /etc/ssl/moduli) would be used for each session (source: https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange#Forward_secrecy) and that the prime used is not actually the RSA key (source: https://stackoverflow.com/a/23346185/1247705), so the fact that many different p values are seen no longer seems like a concern.  I'm still surprised that they're so close in value, but maybe that's expected as well.

The far side is using Solaris SSH 1.1.4 (which as I understand it is based on OpenSSH) as the SSH daemon.  Is it expected that that daemon would pass 2047-bit primes as part of the Diffie-Hellman key exchange, and is there anything that can be done to get it to send 2048-bit primes instead?

答:
I ended up working around this issue by disabling the key-exchange algorithms that used a variant of Diffie-Hellman Group key exchange.  @Brian Low appears to have worked around it by using BouncyCastle instead of the JDK's built-in security provider.

I consider both of those to be workarounds that don't solve the underlying problem (which appears to be a bug in either the JDK for what key sizes they accept or in OpenSSH for what key sizes they generate), but neither I nor my project cared enough to spend time and money trying to force one or the other to take ownership of the issue.


问:
Haskell key input memory leak
I came up with the following code for the raw-input problem, as discussed in SO Haskell read raw keyboard input.  Unfortunately, when I go to ghci, run getAllInput, and hit the right arrow key, it never returns.  Unless I kill it pretty quickly, it seems to eat all my memory so that other applications stop responding and I have to restart the OS.  In the Activity Monitor I can see the memory for the ghc process go quickly into the gigabytes.

(1) I think the problem is in the recursive call of go, which is evaluated lazily by calling hReady before getChar; this means hReady keeps returning true and the stack grows forever.  Is that plausible?

(2) I'm used to languages in which this would soon cause a stack overflow exception, so it wouldn't prevent me from working.  Is there any general way to protect against this massive memory leak?  Maybe starting ghci with a hard limit on memory use?

```<code>import System.IO

-- For example, should get "\ESC[C" from the user hitting the right arrow key.
getAllInput :: IO [Char]
getAllInput =
  let
    go :: IO [Char] -> IO [Char]
    go chars = do
      more <- hReady stdin
      if more then go (added chars getChar) else chars
    added :: IO [Char] -> IO Char -> IO [Char]
    added chars char = do
      chars1 <- chars
      char1 <- char
      return (chars1 ++ [char1])
  in do
    hSetBuffering stdin NoBuffering
    firstChar <- getChar
    go (return [firstChar])
</code>```

I'm running ghci 7.10.3 in OS X 10.11.6.  I cleaned up the code in some obvious ways, basically following the similar SO answer: putting the getChar call in its own line fixes the problem.  But I'd like to understand this better in case it bites me again.

答:
You have an infinite loop in go.  If hReady returns true, then you call go again, which immediately calls hReady again, which will of course return true, and so on.   You probably assume that added will be run because of go (added chars getChar), but it will not; it is just building an IO action and passing it to go as an argument, but that argument is only used when hReady returns False.  The name chars is misleading -- chars is actually an I/O procedure which will return a list of characters when it is eventually run.

In general, when using monads, a "normal" function signature looks like:

```<code>:: Foo -> Bar -> Baz -> IO Quuz
</code>```

That is, the monad (IO) is only present on the return value, not the arguments.  A signature like

```<code>:: IO Foo -> IO Bar
</code>```

usually indicates that something higher-order is going on, for example that this function will perhaps execute its argument multiple times or in a new context.

I recommend the signatures

```<code>go :: [Char] -> IO [Char]
added :: [Char] -> Char -> IO [Char]
</code>```

and trying to get the program to compile from there.

You should also try changing added to be a pure function

```<code>added :: [Char] -> Char -> [Char]
</code>```

because it doesn't actually have any side effects.  The implementation and usage will need to be altered a little, though.

Title: Haskell key input memory leak

Body:
I came up with the following code for the raw-input problem, as discussed in SO Haskell read raw keyboard input.  Unfortunately, when I go to ghci, run getAllInput, and hit the right arrow key, it never returns.  Unless I kill it pretty quickly, it seems to eat all my memory so that other applications stop responding and I have to restart the OS.  In the Activity Monitor I can see the memory for the ghc process go quickly into the gigabytes.

(1) I think the problem is in the recursive call of go, which is evaluated lazily by calling hReady before getChar; this means hReady keeps returning true and the stack grows forever.  Is that plausible?

(2) I'm used to languages in which this would soon cause a stack overflow exception, so it wouldn't prevent me from working.  Is there any general way to protect against this massive memory leak?  Maybe starting ghci with a hard limit on memory use?

import System.IO

-- For example, should get "\ESC[C" from the user hitting the right arrow key.
getAllInput :: IO [Char]
getAllInput =
  let
    go :: IO [Char] -> IO [Char]
    go chars = do
      more <- hReady stdin
      if more then go (added chars getChar) else chars
    added :: IO [Char] -> IO Char -> IO [Char]
    added chars char = do
      chars1 <- chars
      char1 <- char
      return (chars1 ++ [char1])
  in do
    hSetBuffering stdin NoBuffering
    firstChar <- getChar
    go (return [firstChar])

I'm running ghci 7.10.3 in OS X 10.11.6.  I cleaned up the code in some obvious ways, basically following the similar SO answer: putting the getChar call in its own line fixes the problem.  But I'd like to understand this better in case it bites me again.

Body:
You have an infinite loop in go.  If hReady returns true, then you call go again, which immediately calls hReady again, which will of course return true, and so on.   You probably assume that added will be run because of go (added chars getChar), but it will not; it is just building an IO action and passing it to go as an argument, but that argument is only used when hReady returns False.  The name chars is misleading -- chars is actually an I/O procedure which will return a list of characters when it is eventually run.

In general, when using monads, a "normal" function signature looks like:

:: Foo -> Bar -> Baz -> IO Quuz

That is, the monad (IO) is only present on the return value, not the arguments.  A signature like

:: IO Foo -> IO Bar

usually indicates that something higher-order is going on, for example that this function will perhaps execute its argument multiple times or in a new context.

I recommend the signatures

go :: [Char] -> IO [Char]
added :: [Char] -> Char -> IO [Char]

and trying to get the program to compile from there.

You should also try changing added to be a pure function

added :: [Char] -> Char -> [Char]

because it doesn't actually have any side effects.  The implementation and usage will need to be altered a little, though.


问:
why and how a head file is generated from the Interface Definition Language(IDL)
The following code is nsIEventTarget.h, which from firefox source library, but I am curious why and how this head file is generated from nsIEventTarget.idl ?

The Interface Definition Language

A file that contains interface and type library definitions is called an IDL file, and has a .idl file name extension. The Interface Definition Language (IDL) is not a programming language, but a descriptive language to describe the interfaces being implemented by objects. IDL files are similar to C++ header files.

The following code is nsIEventTarget.h. Even if I edit the following head file, it will recover and roll back to the original version after re-build.

nsIEventTarget.h

```<code>/*
 * DO NOT EDIT.  THIS FILE IS GENERATED FROM ../../../dist/idl/nsIEventTarget.idl
 */

#ifndef __gen_nsIEventTarget_h__
#define __gen_nsIEventTarget_h__

#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif

#ifndef __gen_nsIRunnable_h__
#include "nsIRunnable.h"
#endif

/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
#include "nsCOMPtr.h"
#include "mozilla/AlreadyAddRefed.h"

/* starting interface:    nsIEventTarget */
#define NS_IEVENTTARGET_IID_STR "88145945-3278-424e-9f37-d874cbdd9f6f"

#define NS_IEVENTTARGET_IID \
  {0x88145945, 0x3278, 0x424e, \
    { 0x9f, 0x37, 0xd8, 0x74, 0xcb, 0xdd, 0x9f, 0x6f }}

class nsIEventTarget : public nsISupports {
 public:

  NS_DECLARE_STATIC_IID_ACCESSOR(NS_IEVENTTARGET_IID)

     nsresult Dispatch(nsIRunnable* aEvent, uint32_t aFlags) {
      return Dispatch(nsCOMPtr<nsIRunnable>(aEvent).forget(), aFlags);
    }
  enum {
    DISPATCH_NORMAL = 0U,
    DISPATCH_SYNC = 1U,
    DISPATCH_AT_END = 2U
  };

  /* boolean isOnCurrentThread (); */
  NS_IMETHOD IsOnCurrentThread(bool *_retval) = 0;

  /* [binaryname(Dispatch),noscript] void dispatchFromC (in alreadyAddRefed_nsIRunnable event, in unsigned long flags); */
  NS_IMETHOD Dispatch(already_AddRefed<nsIRunnable> event, uint32_t flags) = 0;

  /* [binaryname(DispatchFromScript)] void dispatch (in nsIRunnable event, in unsigned long flags); */
  NS_IMETHOD DispatchFromScript(nsIRunnable *event, uint32_t flags) = 0;

  /* [noscript] void delayedDispatch (in alreadyAddRefed_nsIRunnable event, in unsigned long delay); */
  NS_IMETHOD DelayedDispatch(already_AddRefed<nsIRunnable> event, uint32_t delay) = 0;

};

  NS_DEFINE_STATIC_IID_ACCESSOR(nsIEventTarget, NS_IEVENTTARGET_IID)

/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIEVENTTARGET \
  NS_IMETHOD IsOnCurrentThread(bool *_retval) override; \
  NS_IMETHOD Dispatch(already_AddRefed<nsIRunnable> event, uint32_t flags) override; \
  NS_IMETHOD DispatchFromScript(nsIRunnable *event, uint32_t flags) override; \
  NS_IMETHOD DelayedDispatch(already_AddRefed<nsIRunnable> event, uint32_t delay) override;

/* Use this macro when declaring the members of this interface when the
   class doesn't implement the interface. This is useful for forwarding. */
#define NS_DECL_NON_VIRTUAL_NSIEVENTTARGET \
  nsresult IsOnCurrentThread(bool *_retval); \
  nsresult Dispatch(already_AddRefed<nsIRunnable> event, uint32_t flags); \
  nsresult DispatchFromScript(nsIRunnable *event, uint32_t flags); \
  nsresult DelayedDispatch(already_AddRefed<nsIRunnable> event, uint32_t delay);

/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIEVENTTARGET(_to) \
  NS_IMETHOD IsOnCurrentThread(bool *_retval) override { return _to IsOnCurrentThread(_retval); } \
  NS_IMETHOD Dispatch(already_AddRefed<nsIRunnable> event, uint32_t flags) override { return _to Dispatch(event, flags); } \
  NS_IMETHOD DispatchFromScript(nsIRunnable *event, uint32_t flags) override { return _to DispatchFromScript(event, flags); } \
  NS_IMETHOD DelayedDispatch(already_AddRefed<nsIRunnable> event, uint32_t delay) override { return _to DelayedDispatch(event, delay); }

/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIEVENTTARGET(_to) \
  NS_IMETHOD IsOnCurrentThread(bool *_retval) override { return !_to ? NS_ERROR_NULL_POINTER : _to->IsOnCurrentThread(_retval); } \
  NS_IMETHOD Dispatch(already_AddRefed<nsIRunnable> event, uint32_t flags) override { return !_to ? NS_ERROR_NULL_POINTER : _to->Dispatch(event, flags); } \
  NS_IMETHOD DispatchFromScript(nsIRunnable *event, uint32_t flags) override { return !_to ? NS_ERROR_NULL_POINTER : _to->DispatchFromScript(event, flags); } \
  NS_IMETHOD DelayedDispatch(already_AddRefed<nsIRunnable> event, uint32_t delay) override { return !_to ? NS_ERROR_NULL_POINTER : _to->DelayedDispatch(event, delay); }

#if 0
/* Use the code below as a template for the implementation class for this interface. */

/* Header file */
class nsEventTarget : public nsIEventTarget
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIEVENTTARGET

  nsEventTarget();

private:
  ~nsEventTarget();

protected:
  /* additional members */
};

/* Implementation file */
NS_IMPL_ISUPPORTS(nsEventTarget, nsIEventTarget)

nsEventTarget::nsEventTarget()
{
  /* member initializers and constructor code */
}

nsEventTarget::~nsEventTarget()
{
  /* destructor code */
}

/* boolean isOnCurrentThread (); */
NS_IMETHODIMP nsEventTarget::IsOnCurrentThread(bool *_retval)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* [binaryname(Dispatch),noscript] void dispatchFromC (in alreadyAddRefed_nsIRunnable event, in unsigned long flags); */
NS_IMETHODIMP nsEventTarget::Dispatch(already_AddRefed<nsIRunnable> event, uint32_t flags)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* [binaryname(DispatchFromScript)] void dispatch (in nsIRunnable event, in unsigned long flags); */
NS_IMETHODIMP nsEventTarget::DispatchFromScript(nsIRunnable *event, uint32_t flags)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* [noscript] void delayedDispatch (in alreadyAddRefed_nsIRunnable event, in unsigned long delay); */
NS_IMETHODIMP nsEventTarget::DelayedDispatch(already_AddRefed<nsIRunnable> event, uint32_t delay)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* End of implementation class template. */
#endif

// convenient aliases:
#define NS_DISPATCH_NORMAL nsIEventTarget::DISPATCH_NORMAL
#define NS_DISPATCH_SYNC   nsIEventTarget::DISPATCH_SYNC
#define NS_DISPATCH_AT_END nsIEventTarget::DISPATCH_AT_END

#endif /* __gen_nsIEventTarget_h__ */
</code>```

nsIEventTarget.idl

```<code>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=2 sw=2 sts=2 et cindent: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "nsISupports.idl"
#include "nsIRunnable.idl"
%{C++
#include "nsCOMPtr.h"
#include "mozilla/AlreadyAddRefed.h"
%}

native alreadyAddRefed_nsIRunnable(already_AddRefed<nsIRunnable>);

[scriptable, uuid(88145945-3278-424e-9f37-d874cbdd9f6f)]
interface nsIEventTarget : nsISupports
{
  /* until we can get rid of all uses, keep the non-alreadyAddRefed<> version */
%{C++
    nsresult Dispatch(nsIRunnable* aEvent, uint32_t aFlags) {
      return Dispatch(nsCOMPtr<nsIRunnable>(aEvent).forget(), aFlags);
    }
%}

  /**
   * This flag specifies the default mode of event dispatch, whereby the event
   * is simply queued for later processing.  When this flag is specified,
   * dispatch returns immediately after the event is queued.
   */
  const unsigned long DISPATCH_NORMAL = 0;

  /**
   * This flag specifies the synchronous mode of event dispatch, in which the
   * dispatch method does not return until the event has been processed.
   *
   * NOTE: passing this flag to dispatch may have the side-effect of causing
   * other events on the current thread to be processed while waiting for the
   * given event to be processed.
   */
  const unsigned long DISPATCH_SYNC = 1;

  /**
   * This flag specifies that the dispatch is occurring from a running event
   * that was dispatched to the same event target, and that event is about to
   * finish.
   *
   * A thread pool can use this as an optimization hint to not spin up
   * another thread, since the current thread is about to become idle.
   *
   * These events are always async.
   */
  const unsigned long DISPATCH_AT_END = 2;

  /**
   * Check to see if this event target is associated with the current thread.
   *
   * @returns
   *   A boolean value that if "true" indicates that events dispatched to this
   *   event target will run on the current thread (i.e., the thread calling
   *   this method).
   */
  boolean isOnCurrentThread();

  /**
   * Dispatch an event to this event target.  This function may be called from
   * any thread, and it may be called re-entrantly.
   *
   * @param event
   *   The alreadyAddRefed<> event to dispatch.
   *   NOTE that the event will be leaked if it fails to dispatch.
   * @param flags
   *   The flags modifying event dispatch.  The flags are described in detail
   *   below.
   *
   * @throws NS_ERROR_INVALID_ARG
   *   Indicates that event is null.
   * @throws NS_ERROR_UNEXPECTED
   *   Indicates that the thread is shutting down and has finished processing
   * events, so this event would never run and has not been dispatched.
   */
  [noscript, binaryname(Dispatch)] void dispatchFromC(in alreadyAddRefed_nsIRunnable event, in unsigned long flags);
  /**
   * Version of Dispatch to expose to JS, which doesn't require an alreadyAddRefed<>
   * (it will be converted to that internally)
   *
   * @param event
   *   The (raw) event to dispatch.
   * @param flags
   *   The flags modifying event dispatch.  The flags are described in detail
   *   below.
   *
   * @throws NS_ERROR_INVALID_ARG
   *   Indicates that event is null.
   * @throws NS_ERROR_UNEXPECTED
   *   Indicates that the thread is shutting down and has finished processing
   * events, so this event would never run and has not been dispatched.
   */
  [binaryname(DispatchFromScript)] void dispatch(in nsIRunnable event, in unsigned long flags);
  /**
   * Dispatch an event to this event target, but do not run it before delay
   * milliseconds have passed.  This function may be called from any thread.
   *
   * @param event
   *   The alreadyAddrefed<> event to dispatch.
   * @param delay
   *   The delay (in ms) before running the event.  If event does not rise to
   *   the top of the event queue before the delay has passed, it will be set
   *   aside to execute once the delay has passed.  Otherwise, it will be
   *   executed immediately.
   *
   * @throws NS_ERROR_INVALID_ARG
   *   Indicates that event is null.
   * @throws NS_ERROR_UNEXPECTED
   *   Indicates that the thread is shutting down and has finished processing
   * events, so this event would never run and has not been dispatched, or
   * that delay is zero.
   */
  [noscript] void delayedDispatch(in alreadyAddRefed_nsIRunnable event, in unsigned long delay);
};

%{C++
// convenient aliases:
#define NS_DISPATCH_NORMAL nsIEventTarget::DISPATCH_NORMAL
#define NS_DISPATCH_SYNC   nsIEventTarget::DISPATCH_SYNC
#define NS_DISPATCH_AT_END nsIEventTarget::DISPATCH_AT_END
%}
</code>```

答:
After compiling an .idl file the respective header file is generated along with few c files.

So here in your case when ever you compile  nsIEventTarget.idl, the nsIEventTarget.h is always regenerated.

So your changes are disappearing.

A COM object when build creates an IDL file. Then MIDL compiler parses this IDL to generate the type library(.tlb), header file (in your case) and some proxy files. The ".tlb" is again serves the applications, that want to consume the COM object from which the ".tlb" is generated.

You do not need to know much about MIDL compiler. IDE (ex:visual studio) will take care of all these actions. But still if you want to know more about it you can refer below link:

https://msdn.microsoft.com/en-us/library/windows/desktop/aa367300(v=vs.85).aspx

Body:
The following code is nsIEventTarget.h, which from firefox source library, but I am curious why and how this head file is generated from nsIEventTarget.idl ?

The Interface Definition Language

A file that contains interface and type library definitions is called an IDL file, and has a .idl file name extension. The Interface Definition Language (IDL) is not a programming language, but a descriptive language to describe the interfaces being implemented by objects. IDL files are similar to C++ header files.

The following code is nsIEventTarget.h. Even if I edit the following head file, it will recover and roll back to the original version after re-build.

nsIEventTarget.h

/*
 * DO NOT EDIT.  THIS FILE IS GENERATED FROM ../../../dist/idl/nsIEventTarget.idl
 */

#ifndef __gen_nsIEventTarget_h__
#define __gen_nsIEventTarget_h__

#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif

#ifndef __gen_nsIRunnable_h__
#include "nsIRunnable.h"
#endif

/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
#include "nsCOMPtr.h"
#include "mozilla/AlreadyAddRefed.h"

/* starting interface:    nsIEventTarget */
#define NS_IEVENTTARGET_IID_STR "88145945-3278-424e-9f37-d874cbdd9f6f"

#define NS_IEVENTTARGET_IID \
  {0x88145945, 0x3278, 0x424e, \
    { 0x9f, 0x37, 0xd8, 0x74, 0xcb, 0xdd, 0x9f, 0x6f }}

class nsIEventTarget : public nsISupports {
 public:

  NS_DECLARE_STATIC_IID_ACCESSOR(NS_IEVENTTARGET_IID)

     nsresult Dispatch(nsIRunnable* aEvent, uint32_t aFlags) {
      return Dispatch(nsCOMPtr<nsIRunnable>(aEvent).forget(), aFlags);
    }
  enum {
    DISPATCH_NORMAL = 0U,
    DISPATCH_SYNC = 1U,
    DISPATCH_AT_END = 2U
  };

  /* boolean isOnCurrentThread (); */
  NS_IMETHOD IsOnCurrentThread(bool *_retval) = 0;

  /* [binaryname(Dispatch),noscript] void dispatchFromC (in alreadyAddRefed_nsIRunnable event, in unsigned long flags); */
  NS_IMETHOD Dispatch(already_AddRefed<nsIRunnable> event, uint32_t flags) = 0;

  /* [binaryname(DispatchFromScript)] void dispatch (in nsIRunnable event, in unsigned long flags); */
  NS_IMETHOD DispatchFromScript(nsIRunnable *event, uint32_t flags) = 0;

  /* [noscript] void delayedDispatch (in alreadyAddRefed_nsIRunnable event, in unsigned long delay); */
  NS_IMETHOD DelayedDispatch(already_AddRefed<nsIRunnable> event, uint32_t delay) = 0;

};

  NS_DEFINE_STATIC_IID_ACCESSOR(nsIEventTarget, NS_IEVENTTARGET_IID)

/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIEVENTTARGET \
  NS_IMETHOD IsOnCurrentThread(bool *_retval) override; \
  NS_IMETHOD Dispatch(already_AddRefed<nsIRunnable> event, uint32_t flags) override; \
  NS_IMETHOD DispatchFromScript(nsIRunnable *event, uint32_t flags) override; \
  NS_IMETHOD DelayedDispatch(already_AddRefed<nsIRunnable> event, uint32_t delay) override;

/* Use this macro when declaring the members of this interface when the
   class doesn't implement the interface. This is useful for forwarding. */
#define NS_DECL_NON_VIRTUAL_NSIEVENTTARGET \
  nsresult IsOnCurrentThread(bool *_retval); \
  nsresult Dispatch(already_AddRefed<nsIRunnable> event, uint32_t flags); \
  nsresult DispatchFromScript(nsIRunnable *event, uint32_t flags); \
  nsresult DelayedDispatch(already_AddRefed<nsIRunnable> event, uint32_t delay);

/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIEVENTTARGET(_to) \
  NS_IMETHOD IsOnCurrentThread(bool *_retval) override { return _to IsOnCurrentThread(_retval); } \
  NS_IMETHOD Dispatch(already_AddRefed<nsIRunnable> event, uint32_t flags) override { return _to Dispatch(event, flags); } \
  NS_IMETHOD DispatchFromScript(nsIRunnable *event, uint32_t flags) override { return _to DispatchFromScript(event, flags); } \
  NS_IMETHOD DelayedDispatch(already_AddRefed<nsIRunnable> event, uint32_t delay) override { return _to DelayedDispatch(event, delay); }

/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIEVENTTARGET(_to) \
  NS_IMETHOD IsOnCurrentThread(bool *_retval) override { return !_to ? NS_ERROR_NULL_POINTER : _to->IsOnCurrentThread(_retval); } \
  NS_IMETHOD Dispatch(already_AddRefed<nsIRunnable> event, uint32_t flags) override { return !_to ? NS_ERROR_NULL_POINTER : _to->Dispatch(event, flags); } \
  NS_IMETHOD DispatchFromScript(nsIRunnable *event, uint32_t flags) override { return !_to ? NS_ERROR_NULL_POINTER : _to->DispatchFromScript(event, flags); } \
  NS_IMETHOD DelayedDispatch(already_AddRefed<nsIRunnable> event, uint32_t delay) override { return !_to ? NS_ERROR_NULL_POINTER : _to->DelayedDispatch(event, delay); }

#if 0
/* Use the code below as a template for the implementation class for this interface. */

/* Header file */
class nsEventTarget : public nsIEventTarget
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIEVENTTARGET

  nsEventTarget();

private:
  ~nsEventTarget();

protected:
  /* additional members */
};

/* Implementation file */
NS_IMPL_ISUPPORTS(nsEventTarget, nsIEventTarget)

nsEventTarget::nsEventTarget()
{
  /* member initializers and constructor code */
}

nsEventTarget::~nsEventTarget()
{
  /* destructor code */
}

/* boolean isOnCurrentThread (); */
NS_IMETHODIMP nsEventTarget::IsOnCurrentThread(bool *_retval)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* [binaryname(Dispatch),noscript] void dispatchFromC (in alreadyAddRefed_nsIRunnable event, in unsigned long flags); */
NS_IMETHODIMP nsEventTarget::Dispatch(already_AddRefed<nsIRunnable> event, uint32_t flags)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* [binaryname(DispatchFromScript)] void dispatch (in nsIRunnable event, in unsigned long flags); */
NS_IMETHODIMP nsEventTarget::DispatchFromScript(nsIRunnable *event, uint32_t flags)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* [noscript] void delayedDispatch (in alreadyAddRefed_nsIRunnable event, in unsigned long delay); */
NS_IMETHODIMP nsEventTarget::DelayedDispatch(already_AddRefed<nsIRunnable> event, uint32_t delay)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* End of implementation class template. */
#endif

// convenient aliases:
#define NS_DISPATCH_NORMAL nsIEventTarget::DISPATCH_NORMAL
#define NS_DISPATCH_SYNC   nsIEventTarget::DISPATCH_SYNC
#define NS_DISPATCH_AT_END nsIEventTarget::DISPATCH_AT_END

#endif /* __gen_nsIEventTarget_h__ */

nsIEventTarget.idl

/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=2 sw=2 sts=2 et cindent: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "nsISupports.idl"
#include "nsIRunnable.idl"
%{C++
#include "nsCOMPtr.h"
#include "mozilla/AlreadyAddRefed.h"
%}

native alreadyAddRefed_nsIRunnable(already_AddRefed<nsIRunnable>);

[scriptable, uuid(88145945-3278-424e-9f37-d874cbdd9f6f)]
interface nsIEventTarget : nsISupports
{
  /* until we can get rid of all uses, keep the non-alreadyAddRefed<> version */
%{C++
    nsresult Dispatch(nsIRunnable* aEvent, uint32_t aFlags) {
      return Dispatch(nsCOMPtr<nsIRunnable>(aEvent).forget(), aFlags);
    }
%}

  /**
   * This flag specifies the default mode of event dispatch, whereby the event
   * is simply queued for later processing.  When this flag is specified,
   * dispatch returns immediately after the event is queued.
   */
  const unsigned long DISPATCH_NORMAL = 0;

  /**
   * This flag specifies the synchronous mode of event dispatch, in which the
   * dispatch method does not return until the event has been processed.
   *
   * NOTE: passing this flag to dispatch may have the side-effect of causing
   * other events on the current thread to be processed while waiting for the
   * given event to be processed.
   */
  const unsigned long DISPATCH_SYNC = 1;

  /**
   * This flag specifies that the dispatch is occurring from a running event
   * that was dispatched to the same event target, and that event is about to
   * finish.
   *
   * A thread pool can use this as an optimization hint to not spin up
   * another thread, since the current thread is about to become idle.
   *
   * These events are always async.
   */
  const unsigned long DISPATCH_AT_END = 2;

  /**
   * Check to see if this event target is associated with the current thread.
   *
   * @returns
   *   A boolean value that if "true" indicates that events dispatched to this
   *   event target will run on the current thread (i.e., the thread calling
   *   this method).
   */
  boolean isOnCurrentThread();

  /**
   * Dispatch an event to this event target.  This function may be called from
   * any thread, and it may be called re-entrantly.
   *
   * @param event
   *   The alreadyAddRefed<> event to dispatch.
   *   NOTE that the event will be leaked if it fails to dispatch.
   * @param flags
   *   The flags modifying event dispatch.  The flags are described in detail
   *   below.
   *
   * @throws NS_ERROR_INVALID_ARG
   *   Indicates that event is null.
   * @throws NS_ERROR_UNEXPECTED
   *   Indicates that the thread is shutting down and has finished processing
   * events, so this event would never run and has not been dispatched.
   */
  [noscript, binaryname(Dispatch)] void dispatchFromC(in alreadyAddRefed_nsIRunnable event, in unsigned long flags);
  /**
   * Version of Dispatch to expose to JS, which doesn't require an alreadyAddRefed<>
   * (it will be converted to that internally)
   *
   * @param event
   *   The (raw) event to dispatch.
   * @param flags
   *   The flags modifying event dispatch.  The flags are described in detail
   *   below.
   *
   * @throws NS_ERROR_INVALID_ARG
   *   Indicates that event is null.
   * @throws NS_ERROR_UNEXPECTED
   *   Indicates that the thread is shutting down and has finished processing
   * events, so this event would never run and has not been dispatched.
   */
  [binaryname(DispatchFromScript)] void dispatch(in nsIRunnable event, in unsigned long flags);
  /**
   * Dispatch an event to this event target, but do not run it before delay
   * milliseconds have passed.  This function may be called from any thread.
   *
   * @param event
   *   The alreadyAddrefed<> event to dispatch.
   * @param delay
   *   The delay (in ms) before running the event.  If event does not rise to
   *   the top of the event queue before the delay has passed, it will be set
   *   aside to execute once the delay has passed.  Otherwise, it will be
   *   executed immediately.
   *
   * @throws NS_ERROR_INVALID_ARG
   *   Indicates that event is null.
   * @throws NS_ERROR_UNEXPECTED
   *   Indicates that the thread is shutting down and has finished processing
   * events, so this event would never run and has not been dispatched, or
   * that delay is zero.
   */
  [noscript] void delayedDispatch(in alreadyAddRefed_nsIRunnable event, in unsigned long delay);
};

%{C++
// convenient aliases:
#define NS_DISPATCH_NORMAL nsIEventTarget::DISPATCH_NORMAL
#define NS_DISPATCH_SYNC   nsIEventTarget::DISPATCH_SYNC
#define NS_DISPATCH_AT_END nsIEventTarget::DISPATCH_AT_END
%}


问:
Bootstrap columns within another columns
I am trying to include a bootstrap grid inside another grid and make sure it is still responsive but on larger screens the child grid doesnt collapse.

```<code><div class="container">
<div class="row">
   <div class="col-md-6">First column content</div>
   <div class="col-md-6">
     <div class="row">
       <!-- child grid -->
        <div class="col-md-6"><img class="img-responsive" src="http://placehold.it/350x150"></div>
        <div class="col-md-6">column content</div>
     </div>
   </div>
</div>
</div>
</code>```

bootsplay link: http://www.bootply.com/PCMV1BF4YF

the child grid should collapse in larger screens because the width of the parent class is already small. Is it possible to get around this issue?

答:
Inner col-*-* should also be contained in a row. Read the Bootstrap docs on nesting

```<code><div class="container">
  <div class="row">
   <div class="col-md-6">First column content</div>
   <div class="col-md-6">
     <div class="row">
       <div class="col-lg-6"><img class="img-responsive" src="http://placehold.it/350x150"></div>
       <div class="col-lg-6">Second column content</div>
     </div>
   </div>
 </div>
</div>
</code>```

Make the inner grid col-lg-* if you want it to stack/collapse before the outer grid does. The breakpoint (when the columns stack) depends on the viewport width, not the width of the parent container.

Also, instead of overriding the Bootstrap container, use a custom class.

http://www.bootply.com/aoUZozmcsc

Body:
I am trying to include a bootstrap grid inside another grid and make sure it is still responsive but on larger screens the child grid doesnt collapse.

First column content

column content

bootsplay link: http://www.bootply.com/PCMV1BF4YF

the child grid should collapse in larger screens because the width of the parent class is already small. Is it possible to get around this issue?

Body:
Inner col-*-* should also be contained in a row. Read the Bootstrap docs on nesting

<div class="container">
  <div class="row">
   <div class="col-md-6">First column content</div>
   <div class="col-md-6">
     <div class="row">
       <div class="col-lg-6"><img class="img-responsive" src="http://placehold.it/350x150"></div>
       <div class="col-lg-6">Second column content</div>
     </div>
   </div>
 </div>
</div>

Make the inner grid col-lg-* if you want it to stack/collapse before the outer grid does. The breakpoint (when the columns stack) depends on the viewport width, not the width of the parent container.

Also, instead of overriding the Bootstrap container, use a custom class.

http://www.bootply.com/aoUZozmcsc


问:
can't open web page on my virtual lamp server ubuntu 12.04
i can't open one php script on my virtual ubuntu 12.04 lamp server, i tried at an online host and it works fine but at home didn't work.

what i already did:
 i intall php 5.4 like the online host
 change permisions on folder
change user folder
install php 7 (but the scripts tell php 5.4-5.5)

and i get this error page when i try to open: The requested URL /loja/login was not found on this server.

and the log apache tell :
[client 192.168.0.10] File does not exist: /var/www/script/login
"GET /loja/ HTTP/1.1" 307 769 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"
192.168.0.10 - - [02/Apr/2017:00:12:23 -0300] "GET /loja/login HTTP/1.1" 404 502 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36""

what is wrong on my lamp server? onlines hosts works very well.
the script: https://mega.nz/#!dpskSCDS!vmlxWXVjByV67wv41DO8MqDMPgfjBpxxj_p7uoxmfjQ

答:
Hi please add your php files on your htdocs folder it's /opt/lampp/htdocs

also do this

This will change the ownership of the /opt/lampp/htdocs/ to you:

```<code>sudo chown username:groupname /opt/lampp/htdocs
</code>```

Example : (My username is test and my group name is also test)

```<code>sudo chown test:test /opt/lampp htdocs
</code>```

This will change the folder's permissions to be read, write and executed by you:

```<code>sudo chmod 777 /opt/lampp/htdocs
</code>```

Body:
Hi please add your php files on your htdocs folder it's /opt/lampp/htdocs

also do this

This will change the ownership of the /opt/lampp/htdocs/ to you:

sudo chown username:groupname /opt/lampp/htdocs

Example : (My username is test and my group name is also test)

sudo chown test:test /opt/lampp htdocs

This will change the folder's permissions to be read, write and executed by you:

sudo chmod 777 /opt/lampp/htdocs


问:
Add event listener to <router-link> component using "v-on:" directive - VueJS
I'm attempting to add a custom handler InlineButtonClickHandler to a <router-link> component's click event, so that I can emit a custom appSidebarInlineButtonClick event.

But, my code isn't working. What am I doing wrong?

```<code><template>
   <router-link :to="to" @click="InlineButtonClickHandler">
     {{ name }}
   </router-link>
</template>

<script type="text/babel">
export default {
  props: {
    to: { type: Object, required: true },
    name: { type: String, required: true }
  },
  methods: {
    InlineButtonClickHandler(event) {
      this.$emit('appSidebarInlineButtonClick');
    }
  }
}
</script>
</code>```

答:
```<code><router-link:to="to">
    <span @click="InlineButtonClickHandler">{{name}}</span>
</router-link>
</code>```

Maybe you can try this.

Body:
I'm attempting to add a custom handler InlineButtonClickHandler to a <router-link> component's click event, so that I can emit a custom appSidebarInlineButtonClick event.

But, my code isn't working. What am I doing wrong?

<template>
   <router-link :to="to" @click="InlineButtonClickHandler">
     {{ name }}
   </router-link>
</template>

Body:
<router-link:to="to">
    <span @click="InlineButtonClickHandler">{{name}}</span>
</router-link>

Maybe you can try this.


问:
Android FileProvider, is it possible to modify its paths programmatically in runtime

A FileProvider can only generate a content URI for files in
  directories that you specify beforehand.

Our app allows users to change our default save directory to an arbitrary folder on their device's SD Card.

We have no way of foreseeing such paths and specifying them in the provide_paths.xml file.

Has anybody had this problem before and have you managed to modify these paths in runtime?

答: If you are using the Storage Access Framework, there's no reason to use FileProvider at all. You can pass the document URIs you have to other apps (making sure you also include FLAG_GRANT_READ_URI_PERMISSION) just the same as you could pass them a Uri generated by FileProvider.


问:
Searching an ArrayList for a string and returning another associated string
```<code>private ArrayList<SocialMediaAccount> socialMediaAccounts;

public void addSocialMediaAccount(String userID, String websiteName, String websiteURL, int activityLevel)
{
    SocialMediaAccount object = new SocialMediaAccount(userID, websiteName, websiteURL, activityLevel);
    socialMediaAccounts.add(object);
}
</code>```

I have this ArrayList and I need to search for a particular websiteName and return the userID associated with the object.
Getting confused a lot and would like some help on getting started with this problem.
Thanks!

答:
```<code>I think what you will want

for (SocialMediaAccount socialMediaAccount: socialMediaAccounts) {
            if (socialMediaAccount.getwebsiteName() == your_website_search_name) {
                return socialMediaAccount.getId();
            }
        }
        return null;
</code>```

Body:
private ArrayList<SocialMediaAccount> socialMediaAccounts;

public void addSocialMediaAccount(String userID, String websiteName, String websiteURL, int activityLevel)
{
    SocialMediaAccount object = new SocialMediaAccount(userID, websiteName, websiteURL, activityLevel);
    socialMediaAccounts.add(object);
}

I have this ArrayList and I need to search for a particular websiteName and return the userID associated with the object.
Getting confused a lot and would like some help on getting started with this problem.
Thanks!


问:
Font-face web fonts looks bolder
I'm stuck with a problem. I'm trying to embed fonts with @font-face but they always looks bolder. I have tried everything: other fonts, change font-weight to "ligher" or "100" etc...
The font looks always as it is bolded. I'm pretty sure it could look good because I've seen it used in many other websites with @font-face and it looks thin and fine.

See the attached image link text (I know it would never look as in PS, but so different?)

thanks

答: You are probably using the wrong weight file. Fonts will often be sold in different weights. You should verify that the file you're embedding with @font-face is the right weight.

Title: Font-face web fonts looks bolder


问:
Bulk insert using EntityFramework Extended
According to this, bulk insert in Entity can be made using the following code:

```<code> var customers = GetCustomers();
 db.Customers.AddRange(customers);
 db.SaveChanges();
</code>```

I used SQL Profiler to verify how many insert queries were executed and I saw there was an insert for each element of the list.

Why?

答:
That's how EF6 does "bulk" insert, it doesn't do in bulk, rather row by row. As a result performance sucks.

Use EF.BulkInsert or EFUtilities instead.

Body:
According to this, bulk insert in Entity can be made using the following code:

 var customers = GetCustomers();
 db.Customers.AddRange(customers);
 db.SaveChanges();

I used SQL Profiler to verify how many insert queries were executed and I saw there was an insert for each element of the list.

Why?

ContentLicense: CC BY-SA 4.0


问:
Can we change origin after creation of bucket
Is it possible to change the bucket origin to  Mumbai after creating the bucket origin to Ohio? as I am using edge cache for America.

答:
Amazon S3 buckets are created in specific AWS regions.

Once the bucket is created, all data stored in the bucket remains in that location.

If you wish to change the region of a bucket, you will need to:

Delete the bucket

Wait a while for the name to become available again

Create the bucket in the new region

Of course, you'll want to move the contents of the bucket somewhere so you don't lose it when  you delete the bucket.

An easier option is to simply create a new bucket with a different name, copy the data across, then delete the original bucket.


问:
How to set up a remote database?
I'm a beginner in swift iOS development and I'm enrolled in a couple of Udemy courses (Swift) although there is one question that I have that I can't seem to find the answer to. Bare in mind that I'm a beginner.

I want to make an app and a website that both use the same online database. Basically I want my users to be able to have their own account and store data on a remote database then be able to access it from either the app or the website.

How can I do that ? Most of the courses I followed suggest Firebase but I don't know how scalable it is, if it's fast enough and if it's not too expansive (I plan on having at least 10 000 users)

What would be the best option ? Should I use a MySQL and PHP alongside my swift app ? Should I stick to Firebase ? Or do you have any other suggestion ?

In my mind the best option would be to use Core Data and then synchronizing it with my database, but how do I do it ?

Thanks in advance

答: Well, I'll answer your question simply, I developed an app and a website which uses the same DB, and at first, I thought that fire base was the solution, but the problem is that firebase doesn't have much flexibility, so, I used PHP with MySQL, and I developed a JSON API for my app. I think you should do the same ;)</p>

Title: How to set up a remote database?


答:
You can go through the arraylist and check if the websiteName matches the websiteName that is stored in the list like this:</p>

```<code>for(int i = 0; i < socialMediaAccounts.size(); i++)
    if(socialMediaAccounts.get(i).getWebSiteName().equals(the_website_you_arelooking_for){
    return socialMediaAccounts.get(i).getUserId
    }
}
</code>```

Title: Searching an ArrayList for a string and returning another associated string

Body:
You can go through the arraylist and check if the websiteName matches the websiteName that is stored in the list like this:

for(int i = 0; i < socialMediaAccounts.size(); i++)
    if(socialMediaAccounts.get(i).getWebSiteName().equals(the_website_you_arelooking_for){
    return socialMediaAccounts.get(i).getUserId
    }
}


问:
how does work the creation of indexes when the index is part of a closure?
In the following code I'm confused about the line with the comment "here!":

```<code>var foo = [];
for(var i = 0; i < 10; i++){
    (function(){
     var y = i;
     foo[i] = function(){return y;} //here!
 })();
}
</code>```

Why the "i" value creates the indexes of "foo" correctly? At the end when we try to consult its value is 10. So, why don'tnwe have something like:

content of foo: foo[10] //10 (having only this position in this array)

I understand that we have a closure over "i", because we are making a reference related to another scope, but what I don't understand is why the indexes for "foo" were created correctly having a closure over the "i" variable.

答:
I think it's useful to look at a single iteration of the loop to understand what is happening.

Let's say i = 3:

You create an anonymous function and assign y = i which makes y point to the value 3, ie. the value of y doesn't depend on i afterwards. Then you set foo[3] = function() {return y; // return 3. The key point is that i changing won't change the values of y.

The only relevant closure here is the one which grants foo[i] access to y despite the outer anonymous function having been fully executed and finished.

Also note that each iteration declares a new var y which points to the value in i for that iteration only. So each function returns a separate y in a separate execution context.

Compare to the following code, which does not have an intermediate variable (like the y in your code) and so i refers to the actual value of i in the enclosing scope -- that is, 10, the value of i after the loop has finished

```<code>for(var i = 0; i < 10; i++){
    (function(){
     foo[i] = function(){return i;}
 })();
}

foo[3] = 10; // as you expected for your code
</code>```

Another example below which is similar to yours and has the same behaviour, the parameter to the outer anonymous function holds the value which the inner function is closed over.

```<code>for(var i = 0; i < 10; i++){
    (function(x){
     foo[i] = function(){return x;}
 })(i); // notice that we pass i in here
}

foo[3] = 3;
</code>```

Body:
In the following code I'm confused about the line with the comment "here!":

var foo = [];
for(var i = 0; i < 10; i++){
    (function(){
     var y = i;
     foo[i] = function(){return y;} //here!
 })();
}

Why the "i" value creates the indexes of "foo" correctly? At the end when we try to consult its value is 10. So, why don'tnwe have something like:

content of foo: foo[10] //10 (having only this position in this array)

I understand that we have a closure over "i", because we are making a reference related to another scope, but what I don't understand is why the indexes for "foo" were created correctly having a closure over the "i" variable.

Body:
I think it's useful to look at a single iteration of the loop to understand what is happening.

Let's say i = 3:

You create an anonymous function and assign y = i which makes y point to the value 3, ie. the value of y doesn't depend on i afterwards. Then you set foo[3] = function() {return y; // return 3. The key point is that i changing won't change the values of y.

The only relevant closure here is the one which grants foo[i] access to y despite the outer anonymous function having been fully executed and finished.

Also note that each iteration declares a new var y which points to the value in i for that iteration only. So each function returns a separate y in a separate execution context.

Compare to the following code, which does not have an intermediate variable (like the y in your code) and so i refers to the actual value of i in the enclosing scope -- that is, 10, the value of i after the loop has finished

for(var i = 0; i < 10; i++){
    (function(){
     foo[i] = function(){return i;}
 })();
}

foo[3] = 10; // as you expected for your code

Another example below which is similar to yours and has the same behaviour, the parameter to the outer anonymous function holds the value which the inner function is closed over.

for(var i = 0; i < 10; i++){
    (function(x){
     foo[i] = function(){return x;}
 })(i); // notice that we pass i in here
}

foo[3] = 3;


答:
I suppose this method will solve your question. Hope you have getters inside your socialMediaAccount class.</p>

```<code>public String getuserID(ArrayList<SocialMediaAccount> socialMediaAccounts,String websiteName){
 for(SocialMediaAccount s:socialMediaAccounts){
    if( s.getWebsiteName().equalsIgnoreCase( websiteName)){
        return s.getUserID;
    }
}
return "no user found";
}
</code>```

Body:
I suppose this method will solve your question. Hope you have getters inside your socialMediaAccount class.

public String getuserID(ArrayList<SocialMediaAccount> socialMediaAccounts,String websiteName){
 for(SocialMediaAccount s:socialMediaAccounts){
    if( s.getWebsiteName().equalsIgnoreCase( websiteName)){
        return s.getUserID;
    }
}
return "no user found";
}


问:
Generate unique image name and save to target folder
I have this form where you can upload an image that will serve as your profile picture. The image's name gets register to the database, so it would be wise to use a unique name that will serve as the image's name before registering it to the database to avoid future errors and stuffs.

Here's the code that I come up:

```<code>function random_str($type = 'alphanum', $length = 8)
{
  switch($type)
  {
      case 'basic'    : return mt_rand();
          break;
      case 'alpha'    :
      case 'alphanum' :
      case 'num'      :
      case 'nozero'   :
              $seedings             = array();
              $seedings['alpha']    = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
              $seedings['alphanum'] = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
              $seedings['num']      = '0123456789';
              $seedings['nozero']   = '123456789';

              $pool = $seedings[$type];

              $str = '';
              for ($i=0; $i < $length; $i++)
              {
                  $str .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
              }
              return $str;
          break;
      case 'unique'   :
      case 'md5'      :
                  return md5(uniqid(mt_rand()));
          break;
  }
}

$key = random_str('alphanum', 12);

if(isset($_POST['upload'])) {
    $target = "profiles/".$key.basename($_FILES['image']['name']);

    $image = $key.basename($_FILES['image']['name']);

    $sql = "UPDATE users SET img = '$image' WHERE idnumber = $idnumber";
    mysqli_query($con,$sql);

    if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
        header("Location:home.php");
    } else {
        header("Location:error_uploading.php");
    }
}
</code>```

The only problem is that, for example the image's original filename is image1.png, it generates the name sK1ls902nzAlimage1.png. I know this is kinda overkill but how can I get rid of that ...image1.png in the end? And is my code any good? Or is there a better way (shorter way) to do it? Thanks!

答:
Presumably you are wanting to remove image1 from sK1ls902nzAlimage1.png (it doesn't make sense to remove the ext):

```<code>if(isset($_POST['upload'])) {
    # Get extension
    $ext     = pathinfo($_FILES['image']['name'],PATHINFO_EXTENSION);
    # Create image file name
    $image   = "{$key}.{$ext}";
    # Create image path final destination
    $target  = "profiles/{$image}";
    # Check if the upload is successful
    $success = move_uploaded_file($_FILES['image']['tmp_name'], $target);
    # If successful, set home page, save to database
    if($success) {
        $path = "home";
        mysqli_query($con,"UPDATE users SET img = '{$image}' WHERE idnumber = {$idnumber}");
    }
    else
        $path = "error_uploading";

    header("Location: {$path}.php");
    exit;
}
</code>```

This will just save:

```<code>sK1ls902nzAl.png
</code>```

If you really only want to remove the extension as well, this line needs to just be:

```<code># Will be sK1ls902nzAl vs sK1ls902nzAl.png
$image   = $key;
</code>```

Body:
I have this form where you can upload an image that will serve as your profile picture. The image's name gets register to the database, so it would be wise to use a unique name that will serve as the image's name before registering it to the database to avoid future errors and stuffs.

Here's the code that I come up:

function random_str($type = 'alphanum', $length = 8)
{
  switch($type)
  {
      case 'basic'    : return mt_rand();
          break;
      case 'alpha'    :
      case 'alphanum' :
      case 'num'      :
      case 'nozero'   :
              $seedings             = array();
              $seedings['alpha']    = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
              $seedings['alphanum'] = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
              $seedings['num']      = '0123456789';
              $seedings['nozero']   = '123456789';

              $pool = $seedings[$type];

              $str = '';
              for ($i=0; $i < $length; $i++)
              {
                  $str .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
              }
              return $str;
          break;
      case 'unique'   :
      case 'md5'      :
                  return md5(uniqid(mt_rand()));
          break;
  }
}

$key = random_str('alphanum', 12);

if(isset($_POST['upload'])) {
    $target = "profiles/".$key.basename($_FILES['image']['name']);

    $image = $key.basename($_FILES['image']['name']);

    $sql = "UPDATE users SET img = '$image' WHERE idnumber = $idnumber";
    mysqli_query($con,$sql);

    if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
        header("Location:home.php");
    } else {
        header("Location:error_uploading.php");
    }
}

The only problem is that, for example the image's original filename is image1.png, it generates the name sK1ls902nzAlimage1.png. I know this is kinda overkill but how can I get rid of that ...image1.png in the end? And is my code any good? Or is there a better way (shorter way) to do it? Thanks!

Body:
Presumably you are wanting to remove image1 from sK1ls902nzAlimage1.png (it doesn't make sense to remove the ext):

if(isset($_POST['upload'])) {
    # Get extension
    $ext     = pathinfo($_FILES['image']['name'],PATHINFO_EXTENSION);
    # Create image file name
    $image   = "{$key}.{$ext}";
    # Create image path final destination
    $target  = "profiles/{$image}";
    # Check if the upload is successful
    $success = move_uploaded_file($_FILES['image']['tmp_name'], $target);
    # If successful, set home page, save to database
    if($success) {
        $path = "home";
        mysqli_query($con,"UPDATE users SET img = '{$image}' WHERE idnumber = {$idnumber}");
    }
    else
        $path = "error_uploading";

    header("Location: {$path}.php");
    exit;
}

This will just save:

sK1ls902nzAl.png

If you really only want to remove the extension as well, this line needs to just be:

# Will be sK1ls902nzAl vs sK1ls902nzAl.png
$image   = $key;


问:
Where to define C++ class member template function and functors that instantiate it?
I have a class Foo which is used in a small standalone project. It has a class definition in Foo.h with the implementation for the class' member functions in an implementation file Foo.cpp.

First question - one of the member functions of class Foo is a template method Foo::doSomething(), is it correct that the implementation of this method should appear with the declaration of the function in Foo.h ?

The template parameter which Foo::doSomething() will be instantiated with is one of two Functor types - class CalcA and CalcB.

Should I:

(A) put the defintion and implementation of the two Functor classes all together in Foo.cpp (where they are actually used by the implementation of other Foo member functions to call Foo::doSomething).

(B) put the definition and implementation of the two Functor classes in Foo.h.

(C) should I put split the definition and implementation of the two Functors across Foo.h and Foo.cpp as would be done with an ordinary class?

答:
First you must understand templates mechanism. Templates are not compiled, they are  instantiated when they are used and then their instantiation is compiled. So the compiler needs to have the full template definition in each module using the template function, in order to instantiate them first according to the parameters you've passed.

To solve your problem, there are three solutions but you'll see that they both lead to the same result.
Either you implement your whole templates in your header file inside the class definition (we use to suffix them with .hxx instead of .h in order to precise they're containing templates definitions):

```<code>// Foo.hxx

#ifndef __FOO_HXX__
#define __FOO_HXX__

class Foo {
  public:
   template <class T>
   void bar(const T& t) {
      t.doSomething();
   }
 };
#endif
</code>```

Or you can externalize the definition from the class, but still in the header file:

```<code>// Foo.hxx

#ifndef __FOO_HXX__
#define __FOO_HXX__

class Foo {
    public:
       template <class T>
       void bar(const T&);
};

template <class T>
void Foo::bar(const T& t) {
   t.doSomething();
}
#endif
</code>```

Finally, you can implement template methods bodies in an external file (prefixed with .cxx for the same reason). It will contain methods' bodies but won't include "Foo.hxx". Instead, it's "Foo.hxx" that will include "Foo.cxx" after the class definition. This way, when the compiler resolves the #include directive, it finds the whole template definition in the same module, allowing it to instantiate it:

```<code>// Foo.hxx

#ifndef __FOO_HXX__
#define __FOO_HXX__
class Foo {
    public:
       template <class T>
       void bar(const T&);
};

#include "Foo.cxx"

#endif

// Foo.cxx
template <class T>
void Foo::bar(const T& t) {
   t.doSomething();
}
</code>```

The choice between these 3 ways to implement templates is rather a matter of readability (and taste).

Second and third are equivalent in terms of generated code, but I'd rather not use the cxx file solution, because it often leads to stupid errors when you forget to invert the include.

Moreover, well-known C++ libraries like STL or Boost propose their code in header files only, which is a sign of good design. By using external definition inside headers, you clarify the definition of your class. You also prevent the compiler to automatically inline methods, which can sometimes lead to poor results according to Herb Sutter http://www.gotw.ca/gotw/033.htm

Body:
First you must understand templates mechanism. Templates are not compiled, they are  instantiated when they are used and then their instantiation is compiled. So the compiler needs to have the full template definition in each module using the template function, in order to instantiate them first according to the parameters you've passed.

To solve your problem, there are three solutions but you'll see that they both lead to the same result.
Either you implement your whole templates in your header file inside the class definition (we use to suffix them with .hxx instead of .h in order to precise they're containing templates definitions):

// Foo.hxx

#ifndef __FOO_HXX__
#define __FOO_HXX__

class Foo {
  public:
   template <class T>
   void bar(const T& t) {
      t.doSomething();
   }
 };
#endif

Or you can externalize the definition from the class, but still in the header file:

// Foo.hxx

#ifndef __FOO_HXX__
#define __FOO_HXX__

class Foo {
    public:
       template <class T>
       void bar(const T&);
};

template <class T>
void Foo::bar(const T& t) {
   t.doSomething();
}
#endif

Finally, you can implement template methods bodies in an external file (prefixed with .cxx for the same reason). It will contain methods' bodies but won't include "Foo.hxx". Instead, it's "Foo.hxx" that will include "Foo.cxx" after the class definition. This way, when the compiler resolves the #include directive, it finds the whole template definition in the same module, allowing it to instantiate it:

// Foo.hxx

#ifndef __FOO_HXX__
#define __FOO_HXX__
class Foo {
    public:
       template <class T>
       void bar(const T&);
};

#include "Foo.cxx"

#endif

// Foo.cxx
template <class T>
void Foo::bar(const T& t) {
   t.doSomething();
}

The choice between these 3 ways to implement templates is rather a matter of readability (and taste).

Second and third are equivalent in terms of generated code, but I'd rather not use the cxx file solution, because it often leads to stupid errors when you forget to invert the include.

Moreover, well-known C++ libraries like STL or Boost propose their code in header files only, which is a sign of good design. By using external definition inside headers, you clarify the definition of your class. You also prevent the compiler to automatically inline methods, which can sometimes lead to poor results according to Herb Sutter http://www.gotw.ca/gotw/033.htm


问:
Difference between the  tag and get request
I have a perhaps simple question. What would be the difference between an  tag and a normal GET request with any element. I know the  tag automatically sends you to the url specified in its href attribute. So I assume that a Get request does something similar in it's success callback (as demonstrated below)

But let's say that I also want to send some information along with a normal get request when a for example  element is clicked on so I write:

```<code>   $('span').click(() => {
    $.ajax({
        url: '/someurl',
        type: 'GET',
        data: {
            title: someTitle,
            email: someEmail
        },
        success: (data) => {
                window.location = '/someurl';

        }
    });
});
</code>```

Is there any way to achieve this with an  tag? Sending information to the server so it's available in req.query.title and req.query.email ?

Doing the ajax request above will run my app.get('/someurl',(req,res)=>{})twice because I am sending a GET request to send the data (title and email) and then I am making another GET request when I write window.location = '/someurl' How can I redo this so that it only sends the GET request ONCE but also allows for the sending and storing information to the req object AND ensures that the browser is now displaying /someurl.

Title: Difference between the <a> tag and get request

Body:
I have a perhaps simple question. What would be the difference between an  tag and a normal GET request with any element. I know the  tag automatically sends you to the url specified in its href attribute. So I assume that a Get request does something similar in it's success callback (as demonstrated below)

But let's say that I also want to send some information along with a normal get request when a for example  element is clicked on so I write:

   $('span').click(() => {
    $.ajax({
        url: '/someurl',
        type: 'GET',
        data: {
            title: someTitle,
            email: someEmail
        },
        success: (data) => {
                window.location = '/someurl';

        }
    });
});

Is there any way to achieve this with an  tag? Sending information to the server so it's available in req.query.title and req.query.email ?

Doing the ajax request above will run my app.get('/someurl',(req,res)=>{})twice because I am sending a GET request to send the data (title and email) and then I am making another GET request when I write window.location = '/someurl' How can I redo this so that it only sends the GET request ONCE but also allows for the sending and storing information to the req object AND ensures that the browser is now displaying /someurl.

Body: <a href="/someurl?title=Hello&email=tom%40home.com">Hello</a>


问:
Print form validation errors in Django
I am using registration-redux for Django and cannot get the error codes to display inline when the wrong username or password is entered. Oddly enough, if either is left blank, it shows the error message for that. I have left out the password bit to make the example brief.

```<code><form method="post" action="?next={{ next|default:" / " }}" class="form-horizontal">
    {% csrf_token %}
    <div>
        <div>
            <label for="id_username">Username:</label>
            # HERE IS THE BIT THAT IS FAILING {% if form.username.errors %} {{ form.username.errors }} {% endif %} {{ form.username }}
        </div>
    </div>
    ...
</code>```

Does anyone see  problem with what I am doing here? I also had the

{{ form. username.errors }} wrapped in a p tag but it didn't help.

答:
Try to add {{ form.non_field_errors }} to the form:

```<code><form method="post" action="?next={{ next|default:"/" }}" class="form-horizontal">
{% csrf_token %}
{{ form.non_field_errors }}
...
</code>```

Title: Print form validation errors in Django

Body:
I am using registration-redux for Django and cannot get the error codes to display inline when the wrong username or password is entered. Oddly enough, if either is left blank, it shows the error message for that. I have left out the password bit to make the example brief.

<form method="post" action="?next={{ next|default:" / " }}" class="form-horizontal">
    {% csrf_token %}

            Username:
            # HERE IS THE BIT THAT IS FAILING {% if form.username.errors %} {{ form.username.errors }} {% endif %} {{ form.username }}

    ...

Does anyone see  problem with what I am doing here? I also had the

{{ form. username.errors }} wrapped in a p tag but it didn't help.

Body:
Try to add {{ form.non_field_errors }} to the form:

<form method="post" action="?next={{ next|default:"/" }}" class="form-horizontal">
{% csrf_token %}
{{ form.non_field_errors }}
...


问:
Python base64.b64encode. How to obtain the 6 bit value for each encoded character?
For example, say I perform

```<code>base64.b64encode('Monday')
</code>```

to obtain 'TW9uZGF5'.  But when I want to access the 6 bits for each of the characters, I get something like this (the ASCII values for each of these characters):

```<code>[84 87 57 117 90 71 70 53]
</code>```

when I want to obtain the 6 bit (values between 0 and 63] equivalents:

```<code>[19 22 61  46 25  6  5 57]
</code>```

Is there a way to do so without looping through the list and manually changing them accordingly?

Thanks!

答:
Your question is tagged Python 3.x, but you can't pass a string to base64.b64encode in Python 3.x (need to pass bytes instead).  Anyway, this shows how to do this on either version, but it's not particularly optimized for either one:

```<code>import base64

codes = list(range(ord('A'), ord('Z')+1))
codes += list(range(ord('a'), ord('z')+1))
codes += list(range(ord('0'), ord('9')+1))
codes.extend((ord('+'), ord('/')))

remap = dict(zip(codes, range(64)))

print([remap[x] for x in bytearray(base64.b64encode(b'Monday'))])
</code>```

Body:
For example, say I perform

base64.b64encode('Monday')

to obtain 'TW9uZGF5'.  But when I want to access the 6 bits for each of the characters, I get something like this (the ASCII values for each of these characters):

[84 87 57 117 90 71 70 53]

when I want to obtain the 6 bit (values between 0 and 63] equivalents:

[19 22 61  46 25  6  5 57]

Is there a way to do so without looping through the list and manually changing them accordingly?

Thanks!

Body:
Your question is tagged Python 3.x, but you can't pass a string to base64.b64encode in Python 3.x (need to pass bytes instead).  Anyway, this shows how to do this on either version, but it's not particularly optimized for either one:

import base64

codes = list(range(ord('A'), ord('Z')+1))
codes += list(range(ord('a'), ord('z')+1))
codes += list(range(ord('0'), ord('9')+1))
codes.extend((ord('+'), ord('/')))

remap = dict(zip(codes, range(64)))

print([remap[x] for x in bytearray(base64.b64encode(b'Monday'))])


问:
Ajax not working with Node js - Express js
Im trying to send data from my server side to my client side with ajax but when i use res.send(data) in node, it show me a empty html with the data and i want to get data from my client side without reloading the page and edit something in my actual html

Here's my server-side code

```<code>    app.post('/',(req,res)=>{
    var userName = req.body.username;
    var password = req.body.password;

    connection.query('SELECT * from admin',(err, rows, fields)=> {
      if (!err){
        if((userName == rows[0].usuario) && (password == rows[0].contraseña)){
            res.sendStatus(200);

        }else{
            res.send('Incorrect username or password')
        }
      }else{
        res.send('Error while performing Query.');
      }

    });

});
</code>```

Here's my client-side code

```<code>$(document).ready(function(){
$('#login-form').submit(function (e) {
        setTimeout(function () {
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: '/',
            dataType: 'jsonp',
            data: ({username: $('input[name=username]'),password: $('input[name=password]')}),
            success: function(data,textStatus){
                if(textStatus.statusCode == 200) {
                    $('.error-user').html('Succes');
                }else{
                    $('.error-user').html('Not Success');
                }

            },
        });
        }, 1000);

});
});
</code>```

UPDATE: I removed the setTimeOut() but when I submit the form the page freeze like two seconds and then nothing happen, I get this 'error Maximum call stack size exceeded', dont get me data just stay in the same view if like post method was never called

UPDATE-FINAL: I got values from input outside of the ajax and it works nice,thanks :#

答: Preventdefault is creating issue. You can remove that to run Ajax call</p>

Body:
Im trying to send data from my server side to my client side with ajax but when i use res.send(data) in node, it show me a empty html with the data and i want to get data from my client side without reloading the page and edit something in my actual html

Here's my server-side code

    app.post('/',(req,res)=>{
    var userName = req.body.username;
    var password = req.body.password;

    connection.query('SELECT * from admin',(err, rows, fields)=> {
      if (!err){
        if((userName == rows[0].usuario) && (password == rows[0].contraseña)){
            res.sendStatus(200);

        }else{
            res.send('Incorrect username or password')
        }
      }else{
        res.send('Error while performing Query.');
      }

    });

});

Here's my client-side code

$(document).ready(function(){
$('#login-form').submit(function (e) {
        setTimeout(function () {
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: '/',
            dataType: 'jsonp',
            data: ({username: $('input[name=username]'),password: $('input[name=password]')}),
            success: function(data,textStatus){
                if(textStatus.statusCode == 200) {
                    $('.error-user').html('Succes');
                }else{
                    $('.error-user').html('Not Success');
                }

            },
        });
        }, 1000);

});
});

UPDATE: I removed the setTimeOut() but when I submit the form the page freeze like two seconds and then nothing happen, I get this 'error Maximum call stack size exceeded', dont get me data just stay in the same view if like post method was never called

UPDATE-FINAL: I got values from input outside of the ajax and it works nice,thanks :#


问:
Using XMLHttpRequest, reading XML data
i am trying to read the xml file but somehow i am getting this error: Invalid number of parameters.

```<code><script type="text/javascript">
//<![CDATA[
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET", "employee.XML", false);
    xmlhttp.send();
    xmlDoc = xmlhttp.responseXML;

    var empid= xmlDoc.getElementsByTagName("empid");
    var total = placeMarks.length;
    var names = xmlDoc.getElementsByTagName("Name");
    var designation= xmlDoc.getElementsByTagName("designation");
    var phone= xmlDoc.getElementsByTagName("phone");
    .....
</script>
</code>```

XML data:

```<code><employee>
<emp id="1007">
<name>John Chamber</name>
<designation>Web Expert1</designation>
<phone>555-55-555</phone>
<name>John D</name>
<designation>Web123123</designation>
<phone>555-55-555</phone>
<name>Chamber</name>
<designation>Web Expert</designation>
<phone>555-55-555</phone>
<name>Thomas</name>
<designation>TESTTEST</designation>
<phone>555-55-555</phone>

</emp>
</employee>
</code>```

Title: Using XMLHttpRequest, reading XML data

Body:
i am trying to read the xml file but somehow i am getting this error: Invalid number of parameters.

XML data:

<employee>
<emp id="1007">
<name>John Chamber</name>
<designation>Web Expert1</designation>
<phone>555-55-555</phone>
<name>John D</name>
<designation>Web123123</designation>
<phone>555-55-555</phone>
<name>Chamber</name>
<designation>Web Expert</designation>
<phone>555-55-555</phone>
<name>Thomas</name>
<designation>TESTTEST</designation>
<phone>555-55-555</phone>

</emp>
</employee>

Body: Use xmlhttp.send(null); http://www.w3.org/TR/XMLHttpRequest/#the-send-method


问:
Get popularity of has_many through relationship
I have the following models & relationships

```<code>Category
  has_many :candy
  # these are examples
  #"Hard Candy" "Gummies" "Rock Candy" "Gum" "Jawbreakers" "Lollipops" "Licorice" "Liquid Candy" "Powder Candy" "Taffy"

CandyCategory
  belongs_to :candy
  belongs_to :category

Candy
  has_many :candy_categories
  # Examples "Lemon Drop", "Tootsie Rolls", "Blow Pop", "Ring Pop", "Fun Dip"

Likes
  belongs_to :user
  belongs_to :candy
  has_many :categories, through: :candy
  # there is some meta data here, but the important bits are just the relationships
</code>```

I'm trying to derive the most popular category names  based on the likes of the candy itself.

I can group by the category name, and get a count, but that (obviously) won't leave me with the category object, just an array with the name and count.

e.g.

```<code>Like.includes(:categories).references(:categories).group("categories.name").count
</code>```

Can someone knock some sense into me today and show me the error of my ActiveRecordee ways!?! At the end of the day I need a list of Category objects, or at least the category name and id.

答:
EUREKA!!!!

So, apparently I was psyching myself out over this, it wasn't difficult, I was just thinking of it in reverse.

Here's the solution:

```<code>Category.joins(:candy).includes(:likes).group(:categories).count
</code>```

Body:
I have the following models & relationships

Category
  has_many :candy
  # these are examples
  #"Hard Candy" "Gummies" "Rock Candy" "Gum" "Jawbreakers" "Lollipops" "Licorice" "Liquid Candy" "Powder Candy" "Taffy"

CandyCategory
  belongs_to :candy
  belongs_to :category

Candy
  has_many :candy_categories
  # Examples "Lemon Drop", "Tootsie Rolls", "Blow Pop", "Ring Pop", "Fun Dip"

Likes
  belongs_to :user
  belongs_to :candy
  has_many :categories, through: :candy
  # there is some meta data here, but the important bits are just the relationships

I'm trying to derive the most popular category names  based on the likes of the candy itself.

I can group by the category name, and get a count, but that (obviously) won't leave me with the category object, just an array with the name and count.

e.g.

Like.includes(:categories).references(:categories).group("categories.name").count

Can someone knock some sense into me today and show me the error of my ActiveRecordee ways!?! At the end of the day I need a list of Category objects, or at least the category name and id.

Body:
EUREKA!!!!

So, apparently I was psyching myself out over this, it wasn't difficult, I was just thinking of it in reverse.

Here's the solution:

Category.joins(:candy).includes(:likes).group(:categories).count


问:
Why values in the ArrayList disappeared after using reflection invoke method?
I have two classes:

Child class : receptionist class with two methods ReadDoctorList(String readLine) and DisplayDoctorList().

Parent Class: base class with a readLine method where I pass a method as parameter, the method is from class receptionist.

My idea is to read from a txt file line by line and extract some lines and store them in an ArrayList. I could print out the values on the fly. However,the arraylist became empty If I called it from the TestClass.

Your answer will be greatly appreciated!

```<code>Output:
Tonny Bob
Mike tyson
The size is: 0

txt file:
    Tonny,Bob,abc,abc,D
    Mike,tyson,abc,abc,D
    Laura,jack,abc,abc,P
    Jimmy,viva,abc,abc,P
</code>```

```<code>public class TestClass {
    public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
        Receptionist obj = new Receptionist();
        obj.DisplayDoctorList();
        System.out.println("The size is: " + obj.doctorlist.size());
    }

}
</code>```

```<code>public class Base {
    String pathusers = "/Users/MacTonish/users.txt";
    ArrayList<String> doctorlist = new ArrayList<String>();

    public void readLines(Object instance, String path, Method method)
            throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        try {
            File txt = new File(path);
            BufferedReader reader = new BufferedReader(new FileReader(txt));
            String readLine = null;
            while ((readLine = reader.readLine()) != null) {
                method.invoke(instance, readLine); //something is fishy here.
            }
            reader.close();
        } catch (

        IOException e) {
            e.printStackTrace();
        }
    }
}

class Receptionist extends Base {

    public void DisplayDoctorList() throws NoSuchMethodException, SecurityException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException {
        Method method = Receptionist.class.getMethod("ReadDoctorList", String.class);
        readLines(new Receptionist(), pathusers, method);
    }

    public void ReadDoctorList(String readLine) {
        String[] token = readLine.split(",");
        if (token[4].equals("D")) {
            doctorlist.add(token[0] + " " + token[1]);
            System.out.println(token[0] + " " + token[1]); //Print out is ok.
        }

    }
}
</code>```

答:
If you make below changes to your code of Receptionist , it should work

```<code>    //readLines(new Receptionist(), pathusers, method);

    //Here you are creating a new object but while printing you are using last created Object of ReceptionList
</code>```

Change the above code of line to

```<code>readLines(this, pathusers, method);
</code>```

Body:
I have two classes:

Child class : receptionist class with two methods ReadDoctorList(String readLine) and DisplayDoctorList().

Parent Class: base class with a readLine method where I pass a method as parameter, the method is from class receptionist.

My idea is to read from a txt file line by line and extract some lines and store them in an ArrayList. I could print out the values on the fly. However,the arraylist became empty If I called it from the TestClass.

Your answer will be greatly appreciated!

Output:
Tonny Bob
Mike tyson
The size is: 0

txt file:
    Tonny,Bob,abc,abc,D
    Mike,tyson,abc,abc,D
    Laura,jack,abc,abc,P
    Jimmy,viva,abc,abc,P

public class TestClass {
    public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
        Receptionist obj = new Receptionist();
        obj.DisplayDoctorList();
        System.out.println("The size is: " + obj.doctorlist.size());
    }

}

public class Base {
    String pathusers = "/Users/MacTonish/users.txt";
    ArrayList<String> doctorlist = new ArrayList<String>();

    public void readLines(Object instance, String path, Method method)
            throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        try {
            File txt = new File(path);
            BufferedReader reader = new BufferedReader(new FileReader(txt));
            String readLine = null;
            while ((readLine = reader.readLine()) != null) {
                method.invoke(instance, readLine); //something is fishy here.
            }
            reader.close();
        } catch (

        IOException e) {
            e.printStackTrace();
        }
    }
}

class Receptionist extends Base {

    public void DisplayDoctorList() throws NoSuchMethodException, SecurityException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException {
        Method method = Receptionist.class.getMethod("ReadDoctorList", String.class);
        readLines(new Receptionist(), pathusers, method);
    }

    public void ReadDoctorList(String readLine) {
        String[] token = readLine.split(",");
        if (token[4].equals("D")) {
            doctorlist.add(token[0] + " " + token[1]);
            System.out.println(token[0] + " " + token[1]); //Print out is ok.
        }

    }
}

Body:
If you make below changes to your code of Receptionist , it should work

    //readLines(new Receptionist(), pathusers, method);

    //Here you are creating a new object but while printing you are using last created Object of ReceptionList

Change the above code of line to

readLines(this, pathusers, method);