Why does my code print a repeated garbage character after my string?

Question: Hi i'm new in Assembly and i've some problems with an exercise asking me to find a substring in an original string then, if found, replace it with another given string.
Example:
original string = "This string is a string";
string to find = "string"
String substitution = "dog"
Output =" This dog is a dog"
void main()
{
    //Input

    char stringa[1024] = "This string is a string";

    char str1[] = "string"; // string to find

    char str2[] = "dog";    // string to replace

    // Output
    char risultato[1024];

    __asm
    {

        LEA EDI, stringa
        MOV EAX, EDI             //EAX like 'i' in stringa
        LEA EDI, risultato
        MOV ECX, EDI         //ECX like 'j' in risultato

        //finding str1 in stringa
        MOV EDI, EAX
        LEA ESI, str1

 search:

        MOV BL, [ESI]       //current char of str1

        //if i'm at the end of str1

                //mean that str1 is in stringa
        CMP BL, 0
        JZ found

        CMP[EDI], 0  //check if end of stringa
        JZ fine
        //otherwise
        CMP[EDI], BL
        JNE notfound
        INC EDI
        INC ESI
        JMP search

found:

        MOV EAX, EDI

        DEC EAX

        LEA ESI, str2   //sostitution of str1 with str2

sostituisci:

        MOV BL, [ESI]   //current char of str2

        CMP BL, 0   //checj the end of str2

        JZ continua

        //otherwise

        MOV EDI, ECX

        MOV [EDI], BL   //str2 paste in risultato
        INC ECX
        INC ESI
        JMP sostituisci //next position in str2

notfound:

        MOV EDI, EAX
        MOV ESI, ECX
        MOV BL, [EDI]
        MOV [ESI], BL
        INC ECX

continua:

        LEA ESI, str1
        INC EAX
        MOV EDI, EAX
        CMP [EDI], 0
        JNE search

fine:

    }

    // output
    printf("New string: %s\n", risultato);
}

I can't understand why my code doesn't work exactly.
The output is:

New string: This dog is a dog╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠dog

instead of New string: This dog is a dog.
which is the reason of those symbols?
Comment: Presumably you forgot to put a `0` byte as a terminator at the right place in your `char[]` buffer to mark the end of the implicit-length C string.  In debug mode, MSVC poisons the stack with `0xCC` bytes; presumably `╠` is the character for that byte.  This makes it easier to debug your function because the error is more obvious than with random garbage which might have included some zero bytes.  Anyway, use a debugger.
Comment: you can see how you check for zero in source strings. You can find this zero, because in C and C++ when you do something like `char str2[] = "dog";`, the init-value compiled from `"dog"` is four bytes long, three bytes for letters and fourth byte is zero. So that's why your search for zero in input strings from C works. But in the new string you didn't write zero at the end = the string is not zero-terminated = it's not valid C string.
Comment: perfect, thank you. I've tried to put a 0 a the end but nothing has changed. For this reason, I thouth that there were other mistakes in my code. Probably I didn't put it in the right position.
Comment: @sof23 use memory view in debugger to see yourself content of memory in terms of individual byte values. Use this view while single-stepping over each instruction, then you can observe how your result string is built byte by byte, after each write into memory instruction. Then if you did try to add zero (probably after `fine:` label), you should see this zero byte in memory after the new string. Maybe you have other bug in logic causing you to not detect end of task correctly, or maybe you did write zero by accident into one of the source strings instead of result string,... Debugger helps :)
Comment: try to put a "\0" instead of a 0 : "This string is a string\0".
Answer: Not sure what your assembler encodes for this ambiguous CMP [EDI], 0. Make sure it is a byte-sized operation. Maybe you need to write something like cmp byte ptr [edi], 0.

Although your program has a messy flow it does what it needs to do with the exception of putting a zero-terminator at the end of the resulting text.
Just add this one instruction:
fine:
    mov byte ptr [ecx], 0

Please note that you can use any general purpose register for addressing memory, like I've used [ecx].
1.

    LEA EDI, stringa
    MOV EAX, EDI         //EAX like 'i' in stringa
    LEA EDI, risultato
    MOV ECX, EDI         //ECX like 'j' in risultato

becomes:
    LEA EAX, stringa     //EAX like 'i' in stringa
    LEA ECX, risultato   //ECX like 'j' in risultato

2.

    MOV EDI, ECX
    MOV [EDI], BL   //str2 paste in risultato
    INC ECX

becomes:
    MOV [ECX], BL   //str2 paste in risultato
    INC ECX

3.

notfound:
    MOV EDI, EAX
    MOV ESI, ECX
    MOV BL, [EDI]
    MOV [ESI], BL

becomes:
notfound:
    MOV BL, [EAX]
    MOV [ECX], BL

The LEA instruction can do some arithmetic for you:

    MOV EAX, EDI
    DEC EAX

becomes:
    LEA EAX, [EDI-1]

Comment: MSVC's inline assembly encodes the ambiguous `CMP [EDI], 0` as `CMP byte ptr [EDI], 0` . If the value you try to compare is greater than what can be represented in a byte it truncates the value and it won't warn you about it.


Override name of file field link in Drupal field.tpl template

Question: I have a file download field in a node. The field displays as a simple link with the name of the file that will be downloaded, eg:
picture.png
What I want to do is rename the name on the link, i.e. I want it to stay the same but say:
Download the picture,
instead.
I have created a field--resource.tpl template, I don't know how to get started to get the name that is displayed overridden.
Here is what is in my field--field-source--resources.tpl file:
<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:

  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?>

    <?php endforeach; ?>

Thanks!
Answer: There is an easier way to approach this without having to go through the template file:
On the 'edit' page for your content type, you can set it to 'enable description field'

which will add a new field to your content form that will let you override the label for the file, ex:

This should be easier than trying to parse the template approach and will work seamlessly with other modules that interact with the file field.


How to get record by object id in mongoose

Question: I want to get record based on student id and i follwed the following method,but i use to get empty even the data exists.
my data in db,
{
"_id" : ObjectId("58526f02b7258b0ec168ee77"),
"student" : ObjectId("58525c4c8cdabb7841b68163"),
"updated" : null,
"record_type" : "Invoice",
"created" : ISODate("2016-12-15T10:22:58.801Z"),
"__v" : 0

}
my query,
  exports.searchInvoiceByStudent = function (req, res) {
  var data = {},
  id = req.params.id,
  item = {'record_type':'Invoice','student':id};
  Invoice.find(item).exec(function (err, invoice) {
  if (err) {
    return err;
  }
  if (invoice.length > 0) {
    data = { status: 'success', error_code: 0, data: invoice };
  } else {
    data = { status: 'fail', error_code: 1, data: invoice };
  }
  res.jsonp({ 'details': invoice });
  });
};

But i am getting an empty array,can any one please suggest help.Thanks.
Comment: Can you edit your question to include the schema definition for `Invoice`?
Answer: You could use something like this:
 exports.searchInvoiceByStudent = function (req, res) {
  var data = {},
  id = req.params.id,
  item = {'record_type':'Invoice','student':id};
  Invoice.find({student : id, record_type: 'Invoice}, function (err, invoice) {
  if (err) {
    return err;
  }
  if (invoice.length > 0) {
    data = { status: 'success', error_code: 0, data: invoice };
  } else {
    data = { status: 'fail', error_code: 1, data: invoice };
  }
  res.jsonp({ 'details': invoice });
  });

This version uses a direct callback (instead of the exec).
Or if you like the promise (the promise is returned by exec), you must add your query- result- listener using Promise#addBack(listener), which is missing in your code example.
The mongoose docs mention this example (for the promise- case):
// using the promise returned from executing a query
var query = MyModel.find({ name: /john/i }, null, { skip: 10 });
var promise = query.exec();
promise.addBack(function (err, docs) {});


Why does it say "The command help is already an existing command or alias." -Python

Question: Complete newbie here, I'm trying to make a discord bot but, I have a problem where it says "The command help is already an existing command or alias." whenever I run it.
import discord, random
from random import randint
from discord.ext import commands

TOKEN = ""

intents=discord.Intents.all()
bot = commands.Bot(command_prefix='?', intents=intents)

@bot.event
async def on_ready() :
    print(f'{bot.user} has connected to Discord !!')

@bot.command()
async def help(ctx) :
    await ctx.send('commands:')
    await ctx.send('1. Random - Random number')
    await ctx.send('2. Ping - say "Hello"')

@bot.command()
async def random(ctx) :
    await ctx.send(randint(1, 100))
    enter code here

bot.run(TOKEN)

Comment: A solution would be ```@bot.command(name='help')``` for function ```my_help```
Comment: take a look at this post https://stackoverflow.com/questions/62644195/discord-py-change-the-default-help-command
Comment: !help is a default command
Comment: there are certain keywords that you do not want to name functions as. `help` is one of those....  change `help` to `my_help` and also the same for `random` which is an `imported module` at the top....
Comment: @D.L but this changes the behavior of the bot he clearly wants to write !help and not !my_help
Answer: As mentioned in the comments help is a default command, but you can disable it
with
help_command=None in your commands.Bot function
import discord, random
from random import randint
from discord.ext import commands

TOKEN = ""

intents=discord.Intents.all()
bot = commands.Bot(command_prefix='?', intents=intents,help_command=None)

@bot.event
async def on_ready() :
    print(f'{bot.user} has connected to Discord !!')

@bot.command(name='help')
async def my_help(ctx) :
    await ctx.send('commands:')
    await ctx.send('1. Random - Random number')
    await ctx.send('2. Ping - say "Hello"')

@bot.command(name='random')
async def my_random(ctx) :
    await ctx.send(randint(1, 100))
    enter code here

bot.run(TOKEN)

Comment: Maybe also rename the functions to avoid shadowing the prior meanings of `help` and `random` and specify the names explicitly, as you suggest in the question's comments?


Yum install php-pecl-memcached - No package found (Have epel-release-6-8.noarch.rpm)

Question: I believed I've downloaded and updated the EPEL rpm but I can't install php-pecl-memcached..
I'm very new to this, any help is appreciated.
#rpm -Uvh epel-release-6-8.noarch.rpm warning: epel-release-6-8.noarch.rpm: Header V3 RSA/SHA256 Signature, key ID
0608b895: NOKEY Preparing...
########################################### [100%]
        package epel-release-6-8.noarch is already installed

# yum update Loaded plugins: fastestmirror, security Loading mirror speeds from cached hostfile  * base: mirror.us.leaseweb.net  * epel:
mirror.symnds.com  * extras: mirror.ash.fastserv.com  * updates:
mirror.vcu.edu Setting up Update Process No Packages marked for Update

#yum install php-pecl-memcached Loaded plugins: fastestmirror, security Loading mirror speeds from cached hostfile  * base:
mirror.us.leaseweb.net  * epel: mirror.symnds.com  * extras:
mirror.ash.fastserv.com  * updates: mirror.vcu.edu Setting up Install
Process No package php-pecl-memcached available. Error: Nothing to do

Comment: do a `yum list all | grep php-pecl-memcached` to see if it's available.
Comment: Can you please try this command `# yum list | grep -i php | grep -i pecl | grep -i memcache` and give me the output
Comment: nothing appeared.
Comment: no output again
Comment: That means that the yum repos you have installed do not list this package as being available.
Answer: You have almost certainly mistakenly excluded some packages with yum's exclude option in your yum.conf or a file which it includes. For instance you may have:
exclude=php*

This would prevent any package whose name begins with PHP from ever being shown to you.
To fix the problem, remove the exclusion from your yum configuration.
(This was probably done as a misguided attempt to version-lock the PHP packages. Use the yum versionlock plugin to accomplish this instead.)
Comment: Thank you! Removed php exlusion and it works! I'm unsure why php was excluded since I didn't do any modifications to the file.  Nonetheless it works now. TY Happy Holidays everyone
Answer: Expanding on @Michael Hamptons answer. You could have debugged this issue like this as well.
1. First confirm same system as OP
% uname -a
Linux data01 2.6.32-279.14.1.el6.x86_64 #1 SMP Tue Nov 6 23:43:09 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux
% cat /etc/redhat-release
CentOS release 6.3 (Final)

2. Show yum cmds when there is no exclude=php* present in /etc/yum.conf
% repoquery *pecl* --location
http://eq-centosrepo.hopto.org/6.3/os/x86_64/Packages/php-pecl-apc-3.1.9-2.el6.x86_64.rpm
http://eq-centosrepo.hopto.org/6.3/os/x86_64/Packages/php-pecl-apc-devel-3.1.9-2.el6.x86_64.rpm
http://eq-centosrepo.hopto.org/6.3/os/x86_64/Packages/php-pecl-memcache-3.0.5-4.el6.x86_64.rpm

3. Show repos
% yum repolist
Loaded plugins: fastestmirror, security
Loading mirror speeds from cached hostfile
 * base: yum.singlehop.com
 * extras: mirror.anl.gov
 * updates: mirrors.seas.harvard.edu
repo id                                                  repo name                                                            status
base                                                     CentOS-6 - Base                                                      6,346
extras                                                   CentOS-6 - Extras                                                       17
updates                                                  CentOS-6 - Updates                                                   1,048
repolist: 7,411

4. Add an exclude=php* to /etc/yum.conf
% vim /etc/yum.conf
...
...
exclude=php*
...

5. Confirm php* packages are excluded
# with repoquery

% repoquery *pecl* --location
%

# with yum

% yum list all php-pecl*
Loaded plugins: fastestmirror, security
Loading mirror speeds from cached hostfile
 * base: yum.singlehop.com
 * extras: mirror.anl.gov
 * updates: mirrors.seas.harvard.edu
Error: No matching Packages to list

6. Tell yum to ignore the excludes using --disableexcludes=all switch
% yum list all php-pecl* --disableexcludes=all
Loaded plugins: fastestmirror, security
Loading mirror speeds from cached hostfile
 * base: yum.singlehop.com
 * extras: mirror.anl.gov
 * updates: mirrors.seas.harvard.edu
Available Packages
php-pecl-apc.x86_64                                                    3.1.9-2.el6                                              base
php-pecl-apc-devel.x86_64                                              3.1.9-2.el6                                              base
php-pecl-memcache.x86_64                                               3.0.5-4.el6                                              base

Answer: First, check to see if you have the package installed already...
# yum list installed php-pecl-memcached.x86_64

or
# rpm -qi php-pecl-memcached

That will give you an indication of the current state of the system. From here, it looks like you already have this installed... but those two commands will help you check for sure.
-- edit --
The yum repolist output shows the EPEL repository enabled, as well as the Powerstack repo. These two have similar packages. In Powerstack, which is probably handling your PHP and Apache, you need to:
yum install php-pecl-memcache
The package has a slightly different name than in EPEL. Try that.
Comment: Packages aren't installed.
First output Error: No matching Packages to list
Second output package php-pecl-memcached is not installed
thanks!
Comment: Run a `yum clean all` and try `yum install php-pecl-memcached` again.
Comment: cleaned successfully, tried again to install but end result was
`Setting up Install Process
No package php-pecl-memcached available.
Error: Nothing to do`
Comment: What OS and version are you using?
Comment: CentOS release 6.3 (Final)
Comment: `yum repolist` outputs what?
Comment: 'base            CentOS-6 - Base                                        5,980+366  |
epel            Extra Packages for Enterprise Linux 6 - x86_64       6,907+1,351  |
extras          CentOS-6 - Extras                                             17  |
powerstack      PowerStack for CentOS 6                                    31+53   |
updates         CentOS-6 - Updates                                        989+59   |
repolist: 13,924'
Comment: See my edit above.
Comment: I've actually tried that but nothing shows up either. `No package php-pecl-memcache available.
Error: Nothing to do`


How we can use promises in node js?

Question: As in asynchronous programming we used to callbacks and promises.
Here I am stuck in a problem that may be used to promises. I google it a lot but there is nothing found that solved my problem.
Here My code that I am doing to send push notification in android device.
router.post('/check-notifications', function(req, res, next) {

    var user_id = req.body.user_id;

    var response = {};
    var gcm = require('push-notify').gcm({

        apiKey: gcm_apiKey,
        retries: 0
    });

    connection.query('select device_id from devices where user_id = '+ user_id, function (err, result) {
        if ( result.length ) {

            for (var i = 0; i < result.length; i++) {

                console.log(i + 'before notify');
                gcm.send({

                    registrationId: result[i]['device_id'],
                    data: result[0]
                });

                console.log(i + 'before transmitted');
                gcm.on('transmitted', function (result, message, registrationId) {
                    console.log('transmitted');
                });

                gcm.on('transmissionError', function (error, message, registrationId) {
                    console.log(message);
                });

                console.log(i + 'after notify');

            }
        }
    });

    response['success'] = true;
    response['msg'] = 'sent successfully';
    res.json(response);
});

Output :
0before notify
0before transmitted
0after notify
1before notify
1before transmitted
1after notify
transmitted
transmitted
transmitted
transmitted

And I think It should be like this.
0before notify
0before transmitted
transmitted
0after notify
1before notify
1before transmitted
transmitted
1after notify

Comment: Why you think so? `gcm.send` is async, and code inside for loop is not waiting for notification transmission. If you want to chain async requests, you may use Control-flow libraries, like async, for solving.
Comment: So I don't aware about to use async library that you are talking. can you suggest me to how we can use?
Answer: You can use async.mapSeries method for chaining notifications. Replace for loop to:
async.mapSeries(result, function(item, callback) {
    gcm.send({
        registrationId: item['device_id'],
        data: data
    });
    gcm.on('transmitted', function(result, message, registrationId) {
        console.log('transmitted');
        callback(null, message, registrationId);
    });

    gcm.on('transmissionError', function(error, message, registrationId) {
        callback(error, message, registrationId);
    });
}, function (err, results) {
    if (err) throw err;
    response['success'] = true;
    response['msg'] = 'sent successfully';
    res.json(response);
})

Comment: Because all examples add multiple `on transmitted` events, one for every result. And you have `request * request` lines at console.
Comment: I don't why transmitted log printing four times as we have only 2 rows in result array? that's why four time notification received.
same as @kazenorin's answer
Answer: I recommend using Bluebird JS for Promise flow-control.
var Promise = require('bluebird'); // Require bluebird, and call it 'Promise', the code below is version 3.x syntax

var connection = {'query': '???'}; // assuming `connection` is already defined somewhere else
var gcm_apiKey = '???'; // assuming `gcm_apiKey` is already defined

router.post('/check-notifications', function (req, res, next) {

    var user_id = req.body.user_id;

    var gcm = require('push-notify').gcm({
        apiKey: gcm_apiKey,
        retries: 0
    });

    // assuming `connection` is already defined somewhere else
    // Make an async version of connection.query
    connection.queryAsync = Promise.promisify(connection.query);

    connection.queryAsync('select device_id from devices where user_id = ' + user_id)
        // Bluebird's Promise.map would execute the following block once per result, asynchronously.
        // The sequence of who runs first and who completes first is undefined
        .map(function (result, i) {
            // the `result` argument here is `result[i]` of the original code, since we're in the map context

            // Here we have to create a promise to consume events
            return new Promise(function (resolve, reject) {

                console.log(i + 'before notify');
                gcm.send({
                    registrationId: result['device_id'],
                    data: result // original code is written as result[0], which I don't quite understand. Always sending the first result?
                });

                // This does not make sense console logging here, as it is not actually 'before transmitted'
                // It's just binding onto the event
                // console.log(i + 'before transmitted');
                gcm.on('transmitted', function (result, message, registrationId) {
                    // Check registrationId
                    if (registrationId === result['device_id']) {
                      console.log('transmitted');
                      resolve(result); // use 'result' as the Promise's resolved value
                    }
                });

                gcm.on('transmissionError', function (error, message, registrationId) {
                    // Check registrationId
                    if (registrationId === result['device_id']) {
                      console.log(message);
                      reject(message); // reject errors and send the message as the promise's reject reason
                    }
                });

                // Technically, you should log it as "after event binding"
                console.log(i + 'after notify');

            });
        }).then(function (results) {
            // `results` should contain all the result from the 'transmitted' event

            var response = {};
            response['success'] = true;
            response['msg'] = 'sent successfully';
            res.json(response);
        });

});

Note: The is actually more or less doable without any libraries but with native Promises, but the syntax would be more cluttering.
Comment: It seems at good. but I don't why transmitted log printing four times as we have only 2 rows in result array? that's why four time notification received.
Comment: Since you're receiving 4 times in both @Dima Fitiskin's and my answer, probably the 'transmitted' event is emitted twice.
Comment: Edited answer to check registrationId, as @Dima Fitiskin's pointed out that the transmitted event was not local to each 'send', causing every instance to trigger its 'on transmitted' multiple times.

How we can use promises in node js?


Validate This EF4 Validation Approach?

Question: I'm very new to EF4. I've posted a couple of times I think regarding inheritance, validation but my overall aim is to reduce the amount of code I write as much as possible. I'm not interested (yet) in POCOs, masses of ObjectContext fiddling: I want the benefit of EF and minimum of coding.
So, the thorny issue of validation. Take a look at this simplified example and (aside from DRY Buddies and dodgy usings aliases), is this looking like a half-decent approach?
namespace Model
{
    using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
    using DataAnnotations = System.ComponentModel.DataAnnotations;
    using Validation = Microsoft.Practices.EnterpriseLibrary.Validation;

    [HasSelfValidation]
    [DataAnnotations.MetadataType(typeof(PersonValidator))]
    public partial class Person
    {
        [SelfValidation]
        public Validation.ValidationResults Validate()
        {
            var validationResults = Validation.Validation.Validate(this);

            if (string.IsNullOrEmpty(this.LastName) || this.LastName.Length > 4)
            {
                validationResults.AddResult(new Validation.ValidationResult("This is a test error message for a custom validation error.", this, null, null, null));
            }

            return validationResults;
        }
    }

    [HasSelfValidation]
    public class PersonValidator
    {
        [NotNullValidator(MessageTemplate = "First Name must be supplied.")]
        [ContainsCharactersValidator("Rcd", ContainsCharacters.All, MessageTemplate = "{1} must contains characters \"{3}\" ({4}).")]
        [StringLengthValidator(5, 50, MessageTemplate = "{1} (\"{0}\") must be between {3} ({4}) and {5} ({6}) characters in length.")]
        public string FirstName { get; set; }

        [NotNullValidator(MessageTemplate = "Last Name must be supplied.")]
        [ContainsCharactersValidator("Wes", ContainsCharacters.All, MessageTemplate = "{1} must contains characters \"{3}\" ({4}).")]
        [StringLengthValidator(5, 50, MessageTemplate = "{1} (\"{0}\") must be between {3} ({4}) and {5} ({6}) characters in length.")]
        public string LastName { get; set; }
    }
}

There's something rather cool about this. I can call the above like this:
var validationResults = person.Validate();

BUT, if I just want some basic checking, I can strip out Validate(), the [SelfValidation] stuff, keep the attributes and then just call:
var validationResults = Validation.Validate(person);

I only need to include as much validation as I need and there's ZERO configuration in web.config.
How's the cut of my jib? :)
Richard
Comment: personally, i don't think you should validate in your model for things like "length of lastname". That is validation of *input*, which should be done in the presentation tier. Last-minute validation should be done by EF itself which will validate the fields against the underlying database constraints (e.g `NVARCHAR(4)` - which prevents anything > 4 characters). at what point in your application would you call `person.Validate`?
Comment: Like I said, a simple example. Imagine it in the context of a real world app with real world validation that would take too long to code up as an example.
Comment: I guess (again simply!) call like:using (var context = new ModelContainer()) { var person = new Person(); var validationResults = Validation.Validate(person); if (validationResults.IsValid) { context.AddToPeople(person); } else { WriteValidationResults(validationResults); }} but that EF stuff is still new to me, so...
Comment: CTP 5 has DataAnnotations validation built in. Can you wait?
Comment: I recently noticed the built in support CTP 5 has for DataAnnotations BUT seems code-only at this point? I want model / database first. Typical :) For now, I'm going with the answer below and I gues it'll be happy refactoring time in 6 months or so.
Answer: I'm personally not a fan of calling validation directly in code, and especially not directly on a entity itself. There will be a lot of places were you will call Validate and it is easy to forget to call Validate. Instead, let the ObjectContext invoke the underlying validation framework automatically for ALL entities that have changed, and throw a special exception (that can be caught in the presentation layer) when validation errors occur.
You can do this by hooking onto the ObjectContext.SavingChanges event and trigger validation there. You can write your partial ObjectContext as follows:
public partial class ModelContainer
{
    partial void OnContextCreated()
    {
        this.SavingChanges +=
            (sender, e) => Validate(this.GetChangedEntities());
    }

    private IEnumerable<object> GetChangedEntities()
    {
        const EntityState AddedAndModified =
            EntityState.Added | EntityState.Modified;

        var entries = this.ObjectStateManager
            .GetObjectStateEntries(AddedAndModified);

        return entries.Where(e => e != null);
    }

    private static void Validate(IEnumerable<object> entities)
    {
        ValidationResults[] invalidResults = (
            from entity in entities
            let type = entity.GetType()
            let validator = ValidationFactory.CreateValidator(type)
            let results = validator.Validate(entity)
            where !results.IsValid
            select results).ToArray();

        if (invalidResults.Length > 0)
            throw new ValidationException(invalidResults);
    }
}

You can read more about it here.
Comment: I know it's a bit old. But this is a very nice approach +1

Validate This EF4 Validation Approach?


How to do base64 encoding in Jekyll

Question: I'm stucking with this problem.
Is there anyway to encode string to base64 in Jekyll?
I want to make json files for every posts in my blog before or after I push the codes to Github Pages.
- 2017-08-26-post1.md
- 2017-08-26-post1.md

- 2017-08-26-post1.json
- 2017-08-26-post1.json

maybe something like {{ some_string | base64_encoded }}
Answer: You could create your own liquid tag and supply your string as parameter. Then convert that string to base64 using ruby https://ruby-doc.org/stdlib-2.1.3/libdoc/base64/rdoc/Base64.html and output it to your page.
Something like this may help, which was an example I found here - https://blog.sverrirs.com/2016/04/custom-jekyll-tags.html:
class AdsInlineTag < Liquid::Tag
  def initialize(tag_name, input, tokens)
    super
    @input = input
  end

  def render(context)
    # Split the input variable (omitting error checking)
    input_split = split_params(@input)
    adclient = input_split[0].strip
    adslot = input_split[1].strip

    # Write the output HTML string
    output =  "

"

    # Render it on the page by returning it
    return output;
  end

  def split_params(params)
    params.split("|")
  end
end
Liquid::Template.register_tag('ads', AdsInlineTag)

Hope this helps, I will try and make a simple base64 liquid tag for jekyll and will update if I get it working.
Answer: Here is an example of an working base64 filter written in Ruby:
require "base64"

module Base64Filter
  def base64_encode (input)
    Base64.encode64(input)
  end
end

Liquid::Template.register_filter(Base64Filter) # register filter globally

In jekyll create a new file base64_filter.rb and put it in the _plugins folder in your root. A server restart is needed if you are in serve mode.
Then you can use it with e.g.:
{{ site.email | base64_encode }}

Note: Github Pages does not support plugins!

How to do base64 encoding in Jekyll


How to stop apache showing a page when its ip is requested? I only want to show a page if a domain is requested

Question: i am running apache on (for example) 127.1.1.1, but have it set up so example1.com reads from /home/example1.com/, example2.com reads from /home/example2.com/
if i go to example1.com (or any other domain) it works fine - shows the correct files.
if i go to xxxxx.example1.com (that is, ANY sub domain), it shows the first entry in my vhosts file (so shows the first site i added).
if i go to 127.1.1.1 (its obv. not that ip...), it also shows that first site i added
how can i stop this? i believe just adding a "fake" first entry in my vhosts will still enable connecting to the site via IP or via any subdomain, so that won't work.
Comment: @ineednotes, ensure to associate your account from Super User at http://superuser.com/users/16149?tab=accounts
Answer: You can configure a default virtual host and redirect traffic to a sorry page.
<code><VirtualHost _default_:*>
DocumentRoot /home/defaultvhost
RewriteEngine On
RewriteRule /.* http://mydomain.com/sorry.html [R]
</VirtualHost>
</code>


Locating a specific position on the page

Question: I want to provide a clickable link on drupal such that it easily locates the position of the content in a page. e.g http://asblab.mie.utoronto.ca/people , I want to have a link , that automatically scrolls this page to locate "Past lab member" without requiring me to create a new node. Thank you in advance.
Answer: If you put whatever you want in a div or span with an id, you can then use that id for an anchor.  For example, GO HERE will GO HERE
Comment: @meekahu Also check out this http://help.typepad.com/anchor-tags.html for more info if needed.


Uploadify to use to upload files from server itself

Question: Is there a way to upload files directly from the server itself where the site is hosted.
I really want to do that way cause all my old photo files are on the server and I want my uploadify to do grab those files directly from that server location specified.
This will need frequently for my future use.
please give a solutions if uploadify support the same
Comment: can't you just move (`mv`) or copy (`cp`) them in shell?
Comment: sorry, I also need these individual file information to store in the database and use them dynamically in future. so that I prefer uploadify to do uploading and in the same time write details to database and do create thumbnails of photofiles also
Answer: Uploadify works just one direction: client -> server. You simply can use ftp or sftp to download your photos if that task you only need to do once.


Python and HTML Producing Tables

Question: I'm having trouble with trying to produce two columns using python and html. So I just want it to only have two columns with any amount of rows. Here is a visual of what I'm trying to produce:

This is my python code:
file_name = 'test.html'

test_file = open('test.html', 'w')

test_file.write('''<!DOCTYPE html>

        <title> Dogs </title>

''')

dog_names = ['Bob', 'Kenny', 'Robin', 'Ben', 'Tom', 'Steve']

dog_amount = len(dog_names)
index = 0

while dog_amount > index:
    name = dog_names[index]
    test_file.write('''

''' + name + '''

\n''')
    index += 1

test_file.write('''

 ''')

and this is what is produced in the html file:
<!DOCTYPE html>

        <title> Dogs </title>

Bob

Kenny

Robin

Ben

Tom

Steve

Answer: I think this should work.
while dog_amount > index:
    test_file.write('''

''' + dog_names[index]+ '''

''' + dog_names[index+1]+ '''

\n''')
    index += 2

Python and HTML Producing Tables


Visual Studio Forms: Sometimes, selecting a data grid cell doesn't set the cell's Selected property to true?

Question: I am working with a data grid for Visual Studio forms. When I select a given cell, I want to keep track of the index of the row that cell is on, using the following code:
selectedRows.Clear();
for (int i = 0; i < dataGrid.RowCount; i++)
{
            if (dataGrid[column, i].Selected)
            {
                selectedRows.Add(i);
            }
}

This works 80% of the time. However, occasionally, when I select the name cell of a row, it highlights the cell blue, which leads me to believe I selected it, but the index is not added to selectedRows. Is there something I am missing here?
Am I correct in assuming that sometimes the cells Selected property is simply not set to true, which is causing this error, even though I have clearly selected the cell?
P.S. I have checked that the "column" variable is correct.
Comment: in dataGridView properties (MultiSelected) =False and (SelectionMode)=CellSelect
dataGridView1.CurrentCell.RowIndex -- get Row Index
dataGridView1.CurrentCell.OwningRow -- get Row
dataGridView1 .CurrentRow  -- get Row
Answer: You can use the Cell click event and do something like this:
private void Datagridview1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        int index = e.RowIndex;
        if (!selectedRows.Exists(x =>x == index))
        {
           selectedRows.Add(index)
        }
    }

Comment: This will not work for my purposes since I need to check for multiple selections, and otherwise this is basically the same code as I have above. The problem is that the cell appears to be selected in the form, but the cell.Selected property is set to false.


$(\mathbb{Z}\times\mathbb{Z} \times\mathbb{Z} )/ \langle(3,3,3)\rangle$ is isomorphic to what?

Question: The solution told me it is isomorphic to $\mathbb{Z}_3\times \mathbb{Z} \times \mathbb{Z}$, but why couldn't we argue that $(1,0,0), (0,1,0)$ and $(0,0,1)$ all generates infinite groups, so it is isomorphic to $\mathbb{Z}\times\mathbb{Z} \times\mathbb{Z}$?
Comment: Because $(1,1,1)$ has order $3$, and there is no such element in $\Bbb Z\times \Bbb Z\times \Bbb Z$.
Comment: Because for a proposed homomorphism $(\Bbb Z\times \Bbb Z\times \Bbb Z)/\langle(3,3,3)\rangle\to X$ that you want to obtain from some $f\colon \Bbb Z\times\Bbb Z\times\Bbb Z\to X$, you must always verify that $(3,3,3)\in\ker f$.
Comment: In $\Bbb Z$, you have that $1$, $2$ and $3$ generate infinite groups. This does not mean that $\Bbb Z\cong \Bbb Z\times \Bbb Z\times \Bbb Z$.
Answer: This is the way I thought initially.
In vector spaces, if $\{v_1,v_2,v_3\}$ is a basis, then $\{v_1+v_2+v_3,v_2,v_3\}$ is also a basis (since every element in one set can be obtained from elements of other set and these sets have same cardinality).
Similarly, $\mathbb{Z}\times \mathbb{Z}\times \mathbb{Z}$ can be considered as group with (basis) generating set $\{(1,1,1), (0,1,0), (0,0,1)\}$ instead of $\{(1,0,0), (0,1,0), (0,0,1)\}$; then the answer to your question is almost clear. I hope this clarifies your question a little and you can fill the details.


Drupal 7 and Image Style problems

Question: I have created several image styles in Drupal 7 (thumbnail, medium, large and xlarge). I also have created a script that imports data from a CSV-file, and copy images to the system.
The script seems to work fine and all images are attached to nodes correctly. Using Views I have created a block that shows nodes of a certain node type, and thumbnails attached to said node. Links to the images is OK in HTML.
Now the problem starts. Some images (thumbnails and large) get created, but some doesn't.
I can not find a reason why the images that doesn't get created should not be created. At first I thought maybe the image size was to big, but this isn't the case. Some images that gets created are bigger than ones that doesn't, and all images are bellow the systems 32 MB limit (from 3 to about 15 MB).
I have no idea where to start looking. All images copied during the import seems fine when opening on my system (OS X).
Can anyone point me to where I can get started at finding what the problem might be?
Thanks!
Comment: Oh, and one more thing. Some thumbnails that get created does not have a large style image created.
Comment: Jeez how embarrassing! This was a file permission problem :O
Answer: As I commented on the question, this was a file permission problem..

Drupal 7 and Image Style problems


Why smtp server can not be telnet?

Question: https://www.webdigi.co.uk/blog/2009/how-to-check-if-an-email-address-exists-without-sending-an-email/
I am following the above instruction to telnet an email server of gmail. But I got an error. Could anybody let me know what is wrong? Thanks.
<code>$ nslookup -q=mx gmail.com
Server:     188.8.131.52
Address:    220.127.116.11#53

Non-authoritative answer:
gmail.com   mail exchanger = 40 alt4.gmail-smtp-in.l.google.com.
gmail.com   mail exchanger = 20 alt2.gmail-smtp-in.l.google.com.
gmail.com   mail exchanger = 30 alt3.gmail-smtp-in.l.google.com.
gmail.com   mail exchanger = 10 alt1.gmail-smtp-in.l.google.com.
gmail.com   mail exchanger = 5 gmail-smtp-in.l.google.com.

Authoritative answers can be found from:

$  telnet gmail-smtp-in.l.google.com. 25
Trying 220.127.116.11...
Trying 2607:f8b0:4003:c07::1a...
telnet: Unable to connect to remote host: Network is unreachable
</code>
Comment: Firewall blocking port 25 and that blog post is really old. That method is unreliable at best
Comment: Are you able to telnet any other smtp server? E. g.: telnet smtp.mail.com 25
Answer: To use port 25 you need to use a relay service for google apps - unless you want to only be able to send to other Gmail users - which requires setup in the admin portal if you are on Google apps not just consumer Gmail.
If you're just trying to test connection/confirm email without a mail app try port 465 or 587.
Google apps smtp guide

Why smtp server can not be telnet?


Power Series Help

Question:
Possible Duplicate:
Prove that if $\sum a_k z_1^k$ converges, then $\sum a_k z^k$ also converges, for $|z|<|z_1|$

I have to prove that : Given a power series $\sum_n a_n x^n$ diverges for $x = x'$ then it diverges for every $x$  such that $| x | > |x'|$ . Please suggest how to proceed.
I am trying to use the First comparison test, knowing the series $\sum_n a_n x'^n$ is not convergent which implies that it is not absolutely convergent.
Then comparing the $n$'th terms of the series we have
$$
| a_n x'^n | < | a_n x ^n |
$$
Since the series on the left is not convergent, we have that the series on the right is not convergent either.
But I am getting the not absolute convergence of the series by this approach...Please help !
Comment: @preeti: There may be a theorem in your textbook stating that if $\sum_n a_n x^n$ converges at $x$, then it converges at $x'$ whenever $|x'|<|x|$?
Comment: @preeti: If you figured it out, do consider writing it up here as an answer. That way you get experience writing down an argument, you get feedback on it, the question won't get stuck in the unanswered files etc. You may have to wait a few hours though before the system lets you do that.
Comment: Have you tried to use the contrapositive assumption?
Comment: @JyrkiLahtonen: thanks for your reply. i guess you mean by assuming on the contrary, the series to be convergent. but again getting stuck on the fact convergence does not yield absolute convergence.
Comment: @JyrkiLahtonen:Thanks for the help. You are right !
Comment: @JyrkiLahtonen: Thanks, will do so.
Answer: Try to prove it by contradiction. Have you proven that

Theorem: If a power series converges for a number $z=z_0\neq0$ then it will converge absolutely for any $z$ such that $|z|<|z_0|$.

Suppose that a series diverges for $z=z_0$. Then assume it converges for $z=z_1$ such taht $|z_1|>|z_0|$. Then what would happen to the series for $z_0$ given the above theorem is true?

Power Series Help


How to achieve if else statement while querying with database?

Question: I want to export some data from test_records table depend upon supplied from date and to date. I from and to date not supplied I want to export whole data. So how I can achieve that. Below is my code.
$from_date = strtotime($form_state['values']['fromdate']." 00:00:00");
$to_date   = strtotime($form_state['values']['todate']." 23:59:59");

$result = db_select('test_records', 'n')
      ->fields('n')
      ->condition('submitted_time',  array($from_date, $to_date), 'BETWEEN')
      ->execute()
      ->fetchAll();

I am using one condition that will compare submitted_time in database with supplied from and to dates.  But When I pass nothing, it should get all the data from that table. Any suggestion will be appreciated.
Answer: I'm not sure if you can add if statement to a query but as you already have the values of $form_state['values']['fromdate'] and $form_state['values']['todate'] you can just add an if statement. If those two don't have values then execute a different query without the condition('submitted_time',  array($from_date, $to_date), 'BETWEEN') condition.


I want to call a mymodule.functions.inc file

Question: Hi all drupalers i am new in drupal coding i wrote a new drupal module that works perfecr but my boss wanted to put all my functions of my .module file in a new folder called 'includes' and in a files that called mymodule.functions.inc now i got an error in my code that says called of undefined function... How I can call this mymodule.functions.inc file in my mymodule.module file?? I need a real help hear guys plz help me out :)
Answer: You need to use the module_load_include function.
EDIT: As @Darvanen mentions this needs to go in your <code>.module</code> file preferably inside a suitable hook. Have you seen the Including code section of the Coding standards page?
Comment: In your `.module` file which you will still need to have.  The `.module` file is a good place to put your menu hooks, constants and include calls.
Comment: yes i read it but where i could call dat module_load_include?
Comment: I guess you will add a `module_load_include` at the top of your `.module`, if so: [don't](https://api.drupal.org/api/drupal/includes!module.inc/function/module_load_include/7). "Do not use this function in a global context since it requires Drupal to be fully bootstrapped, use require_once DRUPAL_ROOT . '/path/file' instead."


Wordpress Multisite, site em diretório distinto

Question: tenho uma dúvida, no multisite do Wordpress eu quero saber se tem como eu criar um site em diretório distinto.
por exemplo o site principal é em:

wordpress.omegainc.com.br

e o site secundário quero que fique em

omegainc.com.br/teste/blog

isso é possível?
tentei o plugin mapping domain mas não consegui obter exite, pelo oque percebi ele faz o contrario, quando acessado o subsite ele direciona para o domínio que vc quer, pelo menos isso que percebi.
Comment: Um pouco estranha essa configuração... Dúvida: seu MS está configurado com diretórios? Se não me engano, o Domain Mapping permite adicionar mais de um site/domínio sendo que só um é o primário
Comment: esta para subdominios
Comment: Não cheguei a conferir, mas pode ser interessante: http://stackoverflow.com/search?q=%5Bwordpress%5D+%5B.htaccess%5D+subdomain+directory+multisite
Answer: Se sua instalação principal está em omegainc.com.br você pode criar as páginas que quiser em /teste/blog e personalizar como preferir. Assim a função multisite fica apenas para seu subdomínio wordpress.
Agora caso queira 3 coisas totalmente independentes de temas, plugins e configuração teria que usar instalações diferentes para a raiz, subdomínio e diretório. Dessa forma fica mais semântico, é importante considerar.


Laravel 5.6 Login Attempt Fails - Method RequestGuard::attempt does not exist is returned on Login Submit

Question: I had implemented multi-auth for my application and it was working fine until it just stopped.I've scoured the internet for a solution but to no avail. So I do have  Admin Login Controller and the default Laravel Login controller which uses make:auth and implements authenticable for users. My admin login is working fine but the user login fails and returns this
BadMethodCallException Method Illuminate\Auth\RequestGuard::attempt does not exist.

The same thing happens when I try to register a user but this time it returns it returns
BadMethodCallException
Method Illuminate\Auth\RequestGuard::login does not exist.

Despite the error the user registration passes and the fields are actually populated in the users table from the registration form. Since I'm using the default auth I'm expecting it to automatically login , and i guess this is where the problem arises on the attemp method.
It's imperative to note that I am using Passport on the user Model for another module.
Below is how my Login Controller looks like
namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

}

And my Admin Login Controller
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */
    use AuthenticatesUsers;
    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = 'admin/dashboard';
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest:admin', ['except' => 'logout']);
    }
    /**
     * Show the application's login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showLoginForm()
    {
        return view('admin.admin-login');
    }

    /**
     * Get the guard to be used during authentication.
     *
     * @param Request $request
     * @return \Illuminate\Contracts\Auth\StatefulGuard
     */
    public function login(Request $request)
    {
        // Validate the form data
        $this->validate($request, [
            'email' => 'required|email',
            'password' => 'required|min:8'
        ]);
        // Attempt to log the user in
        if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password])) {
            // if successful, then redirect to their intended location
            return redirect()->intended(route('admin.dashboard'));
        }
        // if unsuccessful, then redirect back to the login with the form data
        return redirect()->back()->with('flash_message_error', 'Invalid Access: Please Login With Your Credentials.');
    }
    public function logout()
    {
        Auth::guard('admin')->logout();
        return redirect('admin')->with('flash_message_error', 'Successfully Logged Out');;
    }

}

This is my guard  config/auth.php
'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
        'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],
        'admin-api' => [
            'driver' => 'passport',
            'provider' => 'admins',
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Admin::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
        ],
        'admins' => [
            'provider' => 'admins',
            'table' => 'password_resets',
            'expire' => 15,
        ],
    ],

];

And finally below is my user Model
namespace App;

use App\Modules\Event\Bookings;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;
use GrahamCampbell\Markdown\Facades\Markdown;

/**
 * @method static find($user_id)
 * @method static count()
 */
class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'fname','lname', 'email','organization','phone_number', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',

    ];

    public function participant()
    {
        return $this->hasMany(Bookings::class);
    }

    public function posts()
    {
        return $this->hasMany(Posts::class, 'author_id');
    }
    public function gravatar()
    {
        $email = $this->email;
        $default = "https://upload.wikimedia.org/wikipedia/commons/thumb/5/50/User_icon-cp.svg/200px-User_icon-cp.svg.png";
        $size = 60;

        return "https://www.gravatar.com/avatar/" . md5( strtolower( trim( $email ) ) ) . "?d=" . urlencode( $default ) . "&s=" . $size;
    }
        public function getRouteKeyName()
    {
        return 'slug';
    }
    public function getBioHtmlAttribute()
    {
        return $this->bio ? Markdown::convertToHtml(e($this->bio)) : NULL ;

    }

}

Below is My Admin Model
namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

/**
 * @method static find($user_id)
 */
class Admin extends Authenticatable
{
    use Notifiable;

    protected $guard = 'admin';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',

    ];

}

I tried to use api as the default guard and it only worked temporarily and started to return the same error, I know attempt method only works on web middleware so what could be the problem? I've removed the vendor folder and reinstalled it using composer update still nothing.. just stuck.
Would immensly appraciate the help.
Comment: Possible duplicate of [Method Illuminate\Auth\RequestGuard::attempt does not exist](https://stackoverflow.com/questions/49026557/method-illuminate-auth-requestguardattempt-does-not-exist)
Comment: Update your Admin Model instead of your User Model Cause you are going to Logged in from Admin Table
Comment: Need your Admin model for better understanding as you use Admin model for Authentication
Comment: Hi @sukel I've edited the post and added the admin model
Answer: So to answer this question, after racking my brain, I decided to clear the application, configuration, and route caches,that did the trick for me.
php artisan cache:clear

You can run the above statement in your console when you wish to clear the application cache. What it does is that this statement clears all caches inside storage\framework\cache.
php artisan route:cache

This clears your route cache. So if you have added a new route or have changed a route controller or action you can use this one to reload the same.
php artisan config:cache

This will clear the caching of the env file and reload it
Finally you can run
composer dump-autoload -o

Composer dump-autoload won't download a thing.
It just regenerates the list of all classes that need to be included in the project (autoload_classmap.php).
Comment: Thank you so much :)


Comparing consistency of ratios of two proportions over time

Question: I have two different metrics (supply and demand) distributed over same parameters( Type of occupation). I want to check if the ratio of supply proportion to demand proportion is consistent over time or does it change with time. Which hypothesis test can be used to test this?
Notes:

The Supply distribution is discrete, log-normal with values ranging
from 390 to 92000.
The Demand distribution is discrete, log-normal with values ranging
from 33 to 6700.
Number of occupations in real data is around 250.

See the image for Example Data

Here I want to test if the changes in Ratio over time are statistically significant.
Comment: Are you looking to do this test for _each_ of your ~250 occupations, based on ~3 data points each? Or some kind of aggregate? In general, you might want to look into [changepoint detection](https://en.wikipedia.org/wiki/Change_detection).
Comment: Thanks for asking this - I need it at aggregate level. Also thanks for suggesting changepoint detection, I am going through it.
Comment: Relatedly: do you actually only have 3 years, or is there more that you just didn't show?
Comment: @Dougal, sorry for delayed response, I have only 3 years.
Answer: With only three years for each occupation, I would start out with visualization. Make a lineplot with 250 lines, years along the x-axis. Plotting ratios directly, that will confound levels with slope, but if there are groups of occupations with rather different slopes, that should stand<out in the plot. You could augment the plot with line coloring according to value of an estimated slope.
More formally, you could try some kind of regression clustering, see for instance linear regression inappropriate when there are multiple underlying groups, but with only three points per line maybe a bayesian variant ...


Why do we usually choose to minimize the sum of square errors (SSE) when fitting a model?

Question: The question is very simple: why, when we try to fit a model to our data, linear or non-linear, do we usually try to minimize the sum of the squares of errors to obtain our estimator for the model parameter? Why not choose some other objective function to minimize? I understand that, for technical reasons, the quadratic function is nicer than some other functions, e.g., sum of absolute deviation. But this is still not a very convincing answer. Other than this technical reason, why in particular are people in favor of this 'Euclidean type' of distance function? Is there a specific meaning or interpretation for that?
The logic behind my thinking is the following:
When you have a dataset, you first set up your model by making a set of functional or distributional assumptions (say, some moment condition but not the entire distribution). In your model, there are some parameters (assume it is a parametric model), then you need to find a way to consistently estimate these parameters and hopefully, your estimator will have low variance and some other nice properties. Whether you minimize the SSE or LAD or some other objective function, I think they are just different methods to get a consistent estimator. Following this logic, I thought people use least square must be 1) it produces consistent estimator of the model 2) something else that I don't know.
In econometrics, we know that in linear regression model, if you assume the error terms have 0 mean conditioning on the predictors and homoscedasticity and errors are uncorrelated with each other, then minimizing the sum of square error will give you a CONSISTENT estimator of your model parameters and by the Gauss-Markov theorem, this estimator is BLUE. So this would suggest that if you choose to minimize some other objective function that is not the SSE, then there is no guarantee that you will get a consistent estimator of your model parameter. Is my understanding correct? If it is correct, then minimizing SSE rather than some other objective function can be justified by consistency, which is acceptable, in fact, better than saying the quadratic function is nicer.
In pratice, I actually saw many cases where people directly minimize the sum of square errors without first clearly specifying the complete model, e.g., the distributional assumptions (moment assumptions) on the error term. Then this seems to me that the user of this method just wants to see how close the data fit the 'model' (I use quotation mark since the model assumptions are probably incomplete) in terms of the square distance function.
A related question (also related to this website) is: why, when we try to compare different models using cross-validation, do we again use the SSE as the judgment criterion? i.e., choose the model that has the least SSE? Why not another criterion?
Comment: Related: http://stats.stackexchange.com/questions/147001/
Answer: While your question is similar to a number of other questions on site, aspects of this question (such as your emphasis on consistency) make me think they're not sufficiently close to being duplicates.

Why not choose some other objective function to minimize?

Why not, indeed? If you objective is different from least squares, you should address your objective instead!
Nevertheless, least squares has a number of nice properties (not least, an intimate connection to estimating means, which many people want, and a simplicity which makes it an obvious first choice when teaching or trying to implement new ideas).
Further, in many cases people don't have a clear objective function, so there's an advantage to choosing what's readily available and widely understood.
That said, least squares also has some less-nice properties (sensitivity to outliers, for example) -- so sometimes people prefer a more robust criterion.

minimize the sum of square error will give you CONSISTENT estimator of your model parameters

Least squares is not a requirement for consistency. Consistency isn't a very high hurdle -- plenty of estimators will be consistent. Almost all estimators people use in practice are consistent.

and by Gauss-Markov theorem, this estimator is BLUE.

But in situations where all linear estimators are bad (as would be the case under extreme heavy-tails, say), there's not much advantage in the best one.

if you choose to minimize some other objective function that is not the SSE, then there is no guarantee that you will get consistent estimator of your model parameter. Is my understanding correct?

it's not hard to find consistent estimators, so no that's not an especially good justification of least squares

why when we try to compare different models using cross validation, we again, use the SSE as the judgment criterion? [...] Why not other criterion?

If your objective is better reflected by something else, why not indeed?
There is no lack of people using other objective functions than least squares. It comes up in M-estimation, in least-trimmed estimators, in quantile regression, and when people use LINEX loss functions, just to name a few.

was thinking that when you have a dataset, you first set up your model, i.e. make a set of functional or distributional assumptions. In your model, there are some parameters (assume it is a parametric model),

Presumably the parameters of the functional assumptions are what you're trying to estimate - in which case, the functional assumptions are what you do least squares (or whatever else) around; they don't determine the criterion, they're what the criterion is estimating.
On the other hand, if you have a distributional assumption, then you have a lot of information about a more suitable objective function -- presumably, for example, you'll want to get efficient estimates of your parameters -- which in large samples will tend to lead you toward MLE, (though possibly in some cases embedded in a robustified framework).

then you need to find a way to consistently estimate these parameters. Whether you minimize the SSE or LAD or some other objective function,

LAD is a quantile estimator. It's a consistent estimator of the parameter it should estimate in the conditions in which it should be expected to be, in the same way that least squares is. (If you look at what you show consistency for with least squares, there's corresponding results for many other common estimators. People rarely use inconsistent estimators, so if you see an estimator being widely discussed, unless they're talking about its inconsistency, it's almost certainly consistent.*)
* That said, consistency isn't necessarily an essential property. After all, for my sample, I have some particular sample size, not a sequence of sample sizes tending to infinity. What matters are the properties at the $n$ I have, not some infinitely larger $n$ that I don't have and will never see. But much more care is required when we have inconsistency - we may have a good estimator at $n$=20, but it may be terrible at $n$=2000; there's more effort required, in some sense, if we want to use inconsistent estimators as a matter of course.
If you use LAD to estimate the mean of an exponential, it won't be consistent for that (though a trivial scaling of its estimate would be) -- but by the same token if you use least squares to estimate the median of an exponential, it won't be consistent for that (and again, a trivial rescaling fixes that).
Comment: I guess I did not express my concern clearly. I was thinking that when you have a dataset, you first set up your model, i.e. make a set of functional or distributional assumptions. In your model, there are some parameters (assume it is a parametric model), then you need to find a way to consistently estimate these parameters. Whether you minimize the SSE or LAD or some other objective function, I think they are just different methods to get the estimator. Following this logic, I thought people use least square must be 1) it produces consistent estimator of the model 2) something else
Comment: Presumably the parameters of the functional assumptions are what you're trying to estimate - in which case, the functional assumptions are what you do least squares (or whatever else) around; they don't determine the criterion. On the other hand, if you have a distributional assumption, then you have a lot of information about a more suitable objective function -- presumably, for example, you'll want to get *efficient* estimates of your parameters -- which in large samples will tend to lead you toward MLE, (though possibly in some cases embedded in a robustified framework).
Comment: This answer fit into my mindset. But I still have a question, what do you mean by 'they don't determine the criterion'? Does this mean that e.g., in econometric 101 in linear regression, under the functional (no distributional) assumption, in order to get the consistent estimator, you got to use ols, you can't use some arbitary objective function to minimize, since no guarantee for deriving consistent estimator from there?
Comment: On "don't determine" -- let me expand in my answer. On consistency: I stated the opposite up in my answer. Let me state it again: least squares is *not* a requirement for consistency. This includes the situation you just mentioned; there are an infinity of alternative estimators that would be consistent. Almost all estimators people use in practice are consistent. I'll edit my answer to be more explicit.
Comment: for your updated answer, the last paragraph, so for some models, there are some ways that WON'T produce consistent parameters for your model parameters, although you can apply those method anyway and compter will give you some numbers, right? So can I say that for a model people build, in order to derive estimators for the parameters in the model, people CANNOT arbitrarily choose an objective function to optimize JUST based on the technical nice properties of it?
Comment: You also mentioned that 'in many cases people don't have a clear objective function, so there's an advantage to choosing what's readily available and widely understood' This one sounds like sometimes people just arbitarily pick a nice function to optimize and get their estimator without deeply understand his OWN model.
Comment: People usually have a good idea of the functional form they want, but often couldn't say much about the distribution of observations about the model (nor much about their loss function). Take a look at many of the questions here -- people daily ask for "what's best" in some context or other without stating what criterion they want to optimize nor giving any information that would lead to one, even after repeated requests for clarification of what they seek to do 'best' at.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/20598/discussion-between-chen-jin-and-glen-b).
Answer: You asked a statistics question, and I hope that my control system engineer answer is a stab at it from enough of a different direction to be enlightening.
Here is a "canonical" information-flow form for control system engineering:

The "r" is for reference value.  It is summed with an "F" transform of the output "y" to produce an error "e".  This error is the input for a controller, transformed by the control transfer function "C" into a control input for the plant "P".   It is meant to be general enough to apply to arbitrary plants.  The "plant" could be a car engine for cruise control, or the angle of input of an inverse-pendulum.
Let's say you have a plant with a known transfer function with phenomenology suitable to the the following discussion, a current state, and a desired end state. (table 2.1 pp68)  There are an infinite number of unique paths that the system, with different inputs, could traverse to get from the initial to final state.  The textbook controls engineer "optimal approaches" include time optimal (shortest time/bang-bang), distance optimal (shortest path), force optimal (lowest maximum input magnitude), and energy optimal (minimum total energy input).
Just like there are an infinite number of paths, there are an infinite number of "optimals" - each of which selects one of those paths.  If you pick one path and say it is best then you are implicitly picking a "measure of goodness" or "measure of optimality".
In my personal opinion, I think folks like L-2 norm (aka energy optimal, aka least squared error) because it is simple, easy to explain, easy to execute, has the property of doing more work against bigger errors than smaller ones, and leaves with zero bias.  Consider h-infinity norms where the variance is minimized and bias is constrained but not zero.  They can be quite useful, but they are more complex to describe, and more complex to code.
I think the L2-norm, aka the energy-minimizing optimal path, aka least squared error fit, is easy and in a lazy sense fits the heuristic that "bigger errors are more bad, and smaller errors are less bad".  There are literally an infinite number of algorithmic ways to formulate this, but squared error is one of the most convenient.  It requires only algebra, so more people can understand it. It works in the (popular) polynomial space.  Energy-optimal is consistent with much of the physics that comprise our perceived world, so it "feels familiar".  It is decently fast to compute and not too horrible on memory.
If I get more time I would like to put pictures, codes, or bibliographic references.
Answer: I think that, when fitting models, we usually choose to minimize the sum of squared errors ($SSE$) due to the fact that $SSE$ has a direct (negative) relation with $R^2$, a major goodness-of-fit (GoF) statistic for a model, as follows ($SST$ is sum of squares total):
$$ R^2 = 1 - \frac{SSE}{SST} $$
Omitting the discussion of why an adjusted $R^2$ is a better (unbiased) GoF statistic due to correction for sample size and number of coefficients (see this or this), it seems to me that this connection is important as $R^2$ family of statistics is the one that represents relative measures of the fit versus absolute measures, such as root mean squared error ($RMSE$).
Moreover, the fact that $R^2$ is equal to the percentage of the variance in the dependent variable that can be explained by all of the independent variables taken together, makes $R^2$ and, thus, indirectly, $SSE$, measures of explanatory power (or predictive power) of a model. In fact, for predictive models, some people recommend using a similar to $SSE$ statistic - predicted residual sum of squares ($PRESS$). For details, see this post and this post, which are relevant to your question in the end of the post.
Concluding and answering your main question, I think that we usually minimize $SSE$, because it is equivalent to maximizing explanatory or predictive power of a statistical model in question.
Comment: Adjusted $R^2$ is [unbiased when the population $R^2$ is zero](http://davegiles.blogspot.co.uk/2013/10/in-what-sense-is-adjusted-r-squared.html) but is it unbiased in general, ie when some slopes are non-zero in the population?
Comment: @Silverfish: Thank you for the comment. I just read the post you've referred to and it seems that you're right: adjusted $R^2$ is what I would call _conditionally unbiased_. Alternatively, it can be labeled as "an _approximately unbiased_ estimate of the population $R^2$" (emphasis mine; see slide 13 in [this document](http://dept.stat.lsa.umich.edu/~kshedden/Courses/Stat600/Notes/decomposing-variance.pdf)).
Comment: On $R^2$: [Explained variation](https://en.wikipedia.org/wiki/Explained_variation) says "R^2 gives the 'percentage of variance explained' by the regression, an expression that,
for most social scientists, is of doubtful meaning but great rhetorical value." On the other hand, Glen_b says rightly "there's an advantage to choosing what's readily available and widely understood."
Comment: @denis: I don't disagree with what Glen_b said above. As for _explained variation_, I'm not sure about why you brought it up - the term seems to be similar to $R^2$ and, thus, shares both advantages and disadvantages of it.
Answer: You might also look at minimizing the maximum error instead of least squares fitting. There is an ample literature on the subject. For a search word, try "Tchebechev" also spelled "Chebyshev" polynomials.
Comment: The max is an L-infinity norm.  If you look at Nutonian/Formulize/Eureqa, they have a nice zoo of cost functionals (error forms) including interquartile absolute error, hinge loss error, ROC-AUC, and signed difference.   http://formulize.nutonian.com/documentation/eureqa/general-reference/error-metrics/
Comment: I thought the above comment was sarcastic, but it wasn't.
Answer: It looks people use squares because it allow to be within Linear Algebra realm and not touch other more complicated stuff like convex optimization which is more powerfull, but it lead to usin solvers without nice closed-form solutions.
Also idea from this math realm which has name convex optimization has not spread a lot.
"...Why do we care about square of items. To be honest because we can analyze it...If you say that it correspond to Energy and they buy it then move on quickly...." -- https://youtu.be/l1X4tOoIHYo?t=1416, EE263, L8, 23:36.
Also here Stephen P. Boyd describes in 2008 that people use hammer and adhoc:
L20, 01:05:15 -- https://youtu.be/qoCa7kMLXNg?t=3916
Answer: On a side note:
When factoring in uncertainty over the values of our target variable t, we can express the probability distribution of t as $$p(t|x,w,\beta) = \mathbb{N}(t|y(x,\textbf{w}),\beta^{-1})$$
assuming t follows a Gaussian conditioned on the polynomial y. Using training data $\{\textbf{x}, \textbf{t}\}$ the likelihood for the model parameters $\textbf{w}$ is given by $$ p(\textbf{t}|\textbf{x}, \textbf{w}, \beta) = \prod_{n=1}^ {N}\mathbb{N}(t_n|y(x_n, \textbf{w}),\beta^{-1}).$$
Maximizing the log likelihood of the form $$-\frac{\beta}{2}\sum_{n=1}^{N}\{y(x_n, \textbf{w})-t_n\}^2 + \frac{N}{2}\ln\beta-\frac{N}{2}\ln(2\pi)$$
is the same as minimizing the negative log likelihood. We cab drop the second and the third term since they're constant with regards to $\textbf{w}$. Also the scaling factor $\beta$ in the first term can be dropped, since a constant factor does not change the location of the maximum/minimum, leaving us with
$$-\frac{1}{2}\sum_{n=1}^{N}\{y(x_n, \textbf{w})-t_n\}^2.$$
Thus the SSE has arisen as a consequence of maximizing likelihood under the assumption of a Gaussian noise distribution.


What if residuals are normally distributed, but y is not?

Question: I've got a weird question. Assume that you have a small sample where the dependent variable that you're going to analyze with a simple linear model is highly left skewed. Thus you assume that $u$ is not normally distributed, because this would result in normally distributed $y$. But when you compute the QQ-Normal plot there is evidence, that the residuals are normally distributed. Thus anyone can assume that the error term is normally distributed, although $y$ is not. So what does it mean, when the error term seems to be normally distributed, but $y$ does not?
Answer: It is reasonable for the residuals in a regression problem to be normally distributed, even though the response variable is not.  Consider a univariate regression problem where $y \sim \mathcal{N}(\beta x, \sigma^2)$. so that the regression model is appropriate, and further assume that the true value of $\beta=1$.  In this case, while the residuals of the true regression model are normal, the distribution of $y$ depends on the distribution of $x$, as the conditional mean of $y$ is a function of $x$.  If the dataset has a lot of values of $x$ that are close to zero and progressively fewer the higher the value of $x$, then the distribution of $y$ will be skewed to the right.  If values of $x$ are distributed symmetrically, then $y$ will be distributed symmetrically, and so forth.  For a regression problem, we only assume that the response is normal conditioned on the value of $x$.
Comment: (+1) I don't think this can be repeated often enough! See also [the same issue discussed here](http://stats.stackexchange.com/questions/11351/left-skewed-vs-symmetric-distribution-observed/11352#11352).
Comment: I am rather (pleasantly) surprised by the number of votes as well ;o)  To obtain the data used to fit the regression model, you have taken a sample from some joint distribution $p(y,x)$, from which you want to estimate $E(y|x)$.  However as $y$ is a (noisy) function of $x$, the distribution of samples of $y$ must depend on the distribution of samples of $x$, for that particular sample.  You may not be interested in the "true" distribution of $x$, but the sample distribution of y depends on the sample of x.
Comment: Consider an example of estimating temperature ($y$) as a function of lattitude ($x$).  The distribution of $y$ values in our sample will depend on where we choose to site out weather stations.  If we place them all either at the poles or the equator, then we will have a bimodal distribution.  If we place them on a regular equal area grid, we will get a unimodal distribution of $y$ values, even though the physics of climate is the same for both samples.  Of course this will affect your fitted regression model, and the study of that sort of thing is known as "covariate shift".  HTH
Comment: Sorry for the pedantic question, but if $\beta = 1$ and $y = \beta x  + \epsilon$ and if we have a bunch of values of $x$ close to zero and progressively less values larger values of $x$, doesn't that mean most $y$ values are also close to zero and progressively less values for larger values of $y$? If that's the case, wouldn't it be a right skewed distribution rather than a left skewed distribution?
Comment: Thanks @David (not pedantic at all), have edited the answer.
Comment: I understand your answer and it sounds correct. At least you earned a lot of positive votes :) But I'm not happy at all. So in your example $\beta=1$ the assumptions you've made are $y\sim N(1\cdot x,\sigma^{2})$. But when I'm estimating the regression I'm estimating $E(y|x)$. Thus $x$ should be given at the time I'm estimating the mean. From this it should follow that x is a value and I do not care of how it was distributed before realizing it. So $y\sim N(value,\sigma^{2})$ is the distribution of $y$. I do not understand where the $x$ is affecting the $y$.
Comment: I suspect also that the $E(y|x)$ is conditional on the implicit assumption that the data used were an i.i.d. sample from the operational joint distribution $p(y,x)$.
Comment: But what if X is not a random variable but just a bunch of values we choose to select when observing Y, e.g., if Y is GPA and X is study hours, we select to evaluate the GPA obtained at , say 1,2,...10 hours? In what way would the distribution of Y depend on X?
Answer: @DikranMarsupial is exactly right, of course, but it occurred to me that it might be nice to illustrate his point, especially since this concern seems to come up frequently.  Specifically, the residuals of a regression model should be normally distributed for the p-values to be correct.  However, even if the residuals are normally distributed, that doesn't guarantee that $Y$ will be (not that it matters... ); it depends on the distribution of $X$.
Let's take a simple example (which I am making up).  Let's say we're testing a drug for isolated systolic hypertension (i.e., the top blood pressure number is too high).  Let's further stipulate that systolic bp is normally distributed within our patient population, with a mean of 160 & SD of 3, and that for each mg of the drug that patients take each day, systolic bp goes down by 1mmHg.  In other words, the true value of $\beta_0$ is 160, and $\beta_1$ is -1, and the true data generating function is:
$$
BP_{sys}=160-1\times\text{daily drug dosage}+\varepsilon  \\
\text{where }\varepsilon\sim\mathcal N(0, 9)
$$
In our fictitious study, 300 patients are randomly assigned to take 0mg (a placebo), 20mg, or 40mg of this new medicine per day.  (Notice that $X$ is not normally distributed.)  Then, after an adequate period of time for the drug to take effect, our data might look like this:

(I jittered the dosages so that the points wouldn't overlap so much that they were hard to distinguish.)  Now, let's check out the distributions of $Y$ (i.e., it's marginal / original distribution), and the residuals:

The qq-plots show us that $Y$ is not remotely normal, but that the residuals are reasonably normal.  The kernel density plots give us a more intuitively accessible picture of the distributions.  It is clear that $Y$ is tri-modal, whereas the residuals look much like a normal distribution is supposed to look.
But what about the fitted regression model, what is the effect of the non-normal $Y$ & $X$ (but normal residuals)?  To answer this question, we need to specify what we might be worried about regarding the typical performance of a regression model in situations like this.  The first issue is, are the betas, on average, right?  (Of course, they'll bounce around some, but in the long run, are the sampling distributions of the betas centered on the true values?)  This is the question of bias.  Another issue is, can we trust the p-values we get?  That is, when the null hypothesis true, is $p<.05$ only 5% of the time?  To determine these things, we can simulate data from the above data generating process and a parallel case where the drug has no effect, a large number of times.  Then we can plot the sampling distributions of $\beta_1$ and check to see if they're centered on the true value, and also check how often the relationship was 'significant' in the null case:
<code>set.seed(123456789)                       # this make the simulation repeatable

b0 = 160;   b1 = -1;   b1_null = 0        # these are the true beta values
x  = rep(c(0, 20, 40), each=100)          # the (non-normal) drug dosages patients get

estimated.b1s  = vector(length=10000)     # these will store the simulation's results
estimated.b1ns = vector(length=10000)
null.p.values  = vector(length=10000)

for(i in 1:10000){
  residuals = rnorm(300, mean=0, sd=3)
  y.works = b0 + b1*x      + residuals
  y.null  = b0 + b1_null*x + residuals    # everything is identical except b1

  model.works = lm(y.works~x)
  model.null  = lm(y.null~x)
  estimated.b1s[i]  = coef(model.works)[2]
  estimated.b1ns[i] = coef(model.null)[2]
  null.p.values[i]  = summary(model.null)$coefficients[2,4]
}
mean(estimated.b1s)       # the sampling distributions are centered on the true values
[1] -1.000084
mean(estimated.b1ns)
[1] -8.43504e-05
mean(null.p.values<.05)   # when the null is true, p<.05 5% of the time
[1] 0.0532
</code>

These results show that everything works out fine.
I won't go through the motions, but if $X$ had been normally distributed, with otherwise the same setup, the original / marginal distribution of $Y$ would have been normally distributed just as the residuals (albeit with a larger SD).  I also didn't illustrate the effects of a skewed distribution of $X$ (which is was the impetus behind this question), but @DikranMarsupial's point is just as valid in that case, and it could be illustrated similarly.
Comment: @loganecolss, that might be better as a new question. At any rate, *yes* it has to do w/ whether the p-values are correct. If your residuals are sufficiently non-normal & your N is low, then the sampling distribution will differ from how it is theorized to be. Since the p-value is how much of that sampling distribution is beyond your test statistic, the p-value will be wrong.
Comment: So the assumption of residuals being normally distributed is only for p-values to be correct? Why the p-values might go wrong if residual is not normal?
Comment: @24n8, the residuals are the distribution of Y conditioned on X.  Regarding the assumptions of an OLS regression model, it is only the distribution of the residuals that matters.  Nonetheless, people often look at the marginal distribution of Y, which is perfectly fine, it just doesn't matter if it's normal.  That is the whole point of this thread.
Comment: @24n8, to be more technical, the errors need to be normally distributed, not the residuals.  But we don't have access to the errors & the residuals are an estimate of them.  It is common for people to talk about the residuals.
Comment: "However, even if the residuals are normally distributed, that doesn't guarantee that
 will be (not that it matters... ); it depends on the distribution of ". hmm, if we condition on $X$ as is done typically doesn't that remove $X$ from consideration. i thought in most cases of interest, we want to know the distribution of $Y$ when conditoined on $X$
Comment: Also, when you say "residuals being normally distributed for p-values to be correct," I thought the underlying hypothesis test assumes that the unobserved errors (not residuals) are normally distributed?
Answer: In a regression model fitting, we should check for the normality of the response at each level of $X$, but not collectively as a whole since it's meaningless for this purpose. If you really need to check the normality of $Y$, then check it for each $X$ level.
Comment: The marginal distribution of the response isn't "meaningless" at all; it's the marginal distribution of the response (and often should hint at models other than plain regression with normal errors). You're right in emphasising that conditional distributions are important once we entertain the model in question, but this doesn't add helpfully to existing excellent answers.
Comment: Some clarification: "check normality of dependent variable for each level of independent variable" same as "checking normality of residuals". From: https://stats.stackexchange.com/questions/435025/in-a-regression-model-fitting-should-we-should-check-for-the-normality-of-the-r
Comment: Actually this is not true.  See https://stats.stackexchange.com/a/486951/102879


Is there any way express $2^{6/x} - 2^{x+1} + 12 = 0$ taking $2^x$ as some variable, say $a$?

Question: I tried raising to $x$ on both sides, getting $2^6 - 2^{x(x+1)} + 12^x = 0$, but we still can't simplify the $2^{x(x+1)}$ in terms of $2^x$. Is there any method of simplifying the equation, taking $2^x$ as some variable, say $a$?
Edit: I got this equation by simplifying the following expression:
$$\sqrt[x]{64} - \sqrt[3]{2^{3x + 3}} + 12 = 0$$
Comment: What you tried is not valid. Generally speaking, $(a+b+c)^p \neq a^p + b^p + c^p$ (the "freshman's dream").
Comment: You know that $(a+b)^x$ isn't the same as $a^x+b^x$, right?
Comment: Or you could notice that 2^4-2^2=12, and arrive at x=3 _slightly_ more systematically!
Comment: My goal is to create an equation taking $2^x$ as some variable, say $a$, then solve for $x$ with the solution of that equation with $a$. For example, if the eqn. was $2^{2x} - 2^{x+1} + 12 = 0$, then taking $2^x$ as $a$, we would get $a^2 - 2a + 12 = 0$
Comment: I don't think this equation can be solved in that way. By the way, it can be verified that $x=3$ is the unique real solution of the equation.
Comment: @SangchulLee you are correct, but how do we derive that $x = 3$?
Comment: If you have no fancy way of reducing an equation into a simpler one, what remains is a trial and error. And that's what I did. It is a bit of a bummer, but I would be surprised if there is any better approach.
Comment: Anyway, here is my thought process that led me to the answer: If the problem was designed to be solvable by hand, then it probably has a rational solution, or even an integer solution. Since it is hard to cancel out irrational numbers by subtraction, a root of the equation would probably make the term $2^{6/x}$ a rational number as well. So tried $x=1,2,3,6$, and $x=3$ worked.
Comment: My guess is that the point of the question is to prove that the root is unique. It's not hard to find $x=3$, it's more interesting to look at whether that's the only root.
Answer: As others have mentioned, the idea of substituting $a=2^x$ won't get you very far with this question, because the $2^\frac{6}{x}$ term will still cause problems.
It's not strictly true to say that trial and error is the only way to proceed, though. We can be more rigorous than just observing that $3$ is a root; we can show that it's the only real root of the equation. I suspect this is what whoever asked the question is after.
Rewrite the equation as $f(x)=g(x)$ where
$$f(x)=2^\frac{6}{x},\quad g(x)=2^{x+1}-12$$
$g(x)$ is clearly a strictly increasing function in $x$, and is defined for all real $x$.
$f(x)$ is not defined at $x=0$, but is everywhere else.
$f(x)>0$ for all $x\neq0$; the $g(x)<0$ for all $x<\log_2 {6}$, so we can restrict ourselves to looking for roots where $x\ge1$. Note that $f(1)>g(1)$.
It's fairly easy to see that the LHS is a strictly decreasing function for $x>1$ (direct from the definition) so the two curves
$$y=f(x);\quad y=g(x)$$
intersect in exactly one point $x>1$.
So, if we find a point where the two functions are equal, it is that unique intersection point.
If the numbers weren't so nice (if, eg, we replaced the $12$ in the question with an $11$), we'd need to use a numerical method (eg Newton's method, or bisection), but a sketch of the curves and a simple table of values quickly finds the unique root $x=3$.
Answer: $$2^\frac{6}{x}-2^{x+1}+12=0$$
$$(2^\frac{1}{x})^6-2\ 2^x+12=0$$
E.g. with help of Lindemann–Weierstrass theorem, we find that the terms $2^\frac{1}{x},2^x$ are algebraically independent. Therefore, they cannot both fulfill the same algebraic equation simultaneously. $2^\frac{1}{x}$ cannot be expressed as an algebraic function of $2^x$ and vice versa therefore.
We see, your equation is a polynomial equation of more than one algebraically independent monomials ($2^\frac{1}{x},2^x$) and with no univariate factor. We therefore don't know how to rearrange the equation for $x$ by applying only finite numbers of elementary functions (operations) we can read from the equation.
It seems your equation can be solved neither with Lambert W nor with Generalized Lambert W or Hyper Lambert W.


Old .Net app crashed. What does this event log info mean?

Question: A .NET application running in one of our systems 24/7 suddenly crashed without logging any errors.
The only error information we were able to retrieve is in the windows events log, with this codes:
faulting module msvcr80.dll,
version 8.0.50727.3053,
stamp 4889d619,
debug? 0,
fault address 0x000144dc.

Has anyone experienced an issue like this before? Does anybody have an idea of what the location in the ms library is about or where to find such information? Where can I start in trying to resolve this issue?
Edit: the application wasn't changed recently and every error should be trapped and logged, so the behavior seems really strange. What I really wanted to know is what function is located at the given offset, so that maybe we can figure out where the crash happened.
Comment: Has it crashed before? How often does it crash?
Comment: Are you sure the event log entry is related? If so, then presumably the app does p/invoke or is a mixed mode assembly?
Comment: Could be a million things - does it crash randomly?  When you're doing something specific?  On a certain O/S only?  You say 'suddenly' - are you absolutely positively 100% sure that the only thing that changed was the date/time?  And at what date/time did it suddenly start crashing?
Answer: That's the C++ runtime library (from 2005 I think).
It can be flagged as being the cause for many things, from malware attacks to C++ code losing access to databases to actual program bugs. Generally when exceptions are not handled.
The main point here though is that if all has been running okay and it has suddenly been flagged then I would look to see what changed on the system on which it is used to cause the crash.
Only by making it occur again will you be able to track down what code actually caused the crash.
edit
Check for any updates put onto the machine recently for any of the software. Not just yours, but Microsoft, antivirus, etc. It is possible thta one of these is the culprit. I know someone who had been using Office 2000 quite happily until a recent update for AVG overwrote the C runtime dll and he could no longer print anything or receive emails.
I know that its not ideal but you will probably have to pass this onto Microsoft as it is buried within their DLL.
Comment: Hi, thanks for the response. I've updated the question if you could take a look? Thanks.
Answer: If its 24/7 and suddenly crashed; I would ask about changes/updates in the system that were made in the recent past.
The file msvcr80.dll is a Visual Studio 2005 VC++ Runtime library; doesn't help much in digging the exact cause.
This discussion might help.
Comment: Hi, thanks for the response. I've updated the question if you could take a look? Thanks.
Comment: @DaveDev: I meant, change in the System/OS; It seems some security updates/patches were added recently.
Comment: Someone probably installed windows updates or another app which updated the C++ runtime.
Answer: At first glance it seems like it's anti-virus or update related, but it really could just be just a fluke, or a sign of failing hardware. I would setup process monitor and log in detail what the application's doing if it happens again. If this is a onetime occurrence I wouldn't worry about it much.
http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx
Comment: As the other guys' answers made good points, none were on the mark. As nothing has changed on the server, I'll put it down to this: http://www.newscientist.com/blog/technology/2008/03/do-we-need-cosmic-ray-alerts-for.html. I've accepted this for the suggestion "If this is a onetime occurrence I wouldn't worry about it much"


Get witness disk current vote via PowerShell

Question: I am trying to verify functionality of dynamic quorum in a new failover cluster setup.
Is there a command in PowerShell that I can use to see the current vote for the witness disk? I have been digging through TechNet, and have been unsuccessful locating the command (if it even exists in the first place).
Answer: In Windows Server 2012 R2, "The clustering service will automatically assign the witness a vote, the witness dynamic vote, depending on if there is an odd or even number of votes present for the cluster nodes."
Dynamic Witness in Windows Server 2012 R2 Failover Clustering
"To check the vote status of the witness, use the Windows PowerShell command below. A return of 1 means the witness has a vote; a return of 0 means the witness doesn't have a vote."
(Get-Cluster).WitnessDynamicWeight