问:
Using res.locals.user to show user object in all frontend views
I am trying to use res.locals.user to show the user object in the frontend.

Below you can see in my main app.js file the middleware I have created:

```<code>...
const passport = require('passport')

const auth = require('./routes/auth')
const index = require('./routes/index')

const app = express()

// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')
app.use(logger(process.env.LOG_ENV))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
  extended: false,
}))
app.use(express.static(path.join(__dirname, '/../public')))
app.use(cookieParser())

app.use(session({
  secret: 'super-mega-hyper-secret',
  resave: false,
  saveUninitialized: true,
}))
app.use(passport.initialize())
app.use(passport.session())
app.use((req, res, next) => { //This middleware checks the local user
  res.locals.user = req.user
  next()
})
...
</code>```

My passport file looks like the following:

```<code>const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
const serviceAuth = require('../service/auth')

passport.serializeUser((user, done) => {
  done(null, user.id)
})

passport.deserializeUser(async(id, done) => {
  const user = await serviceAuth.findById(id)
  done(null, user)
})

// Sign in with username and Password
passport.use('local', new LocalStrategy({
  usernameField: 'username',
}, async(username, password, done) => {
  const user = await serviceAuth.signin(username, password)
  done(null, user)
}))

/**
 * Login Required middleware.
 */
exports.isAuthenticated = (req, res, next) => {
  if (req.isAuthenticated()) {
    res.locals.user = req.session.user
    return next()
  }
  res.redirect('/')
}
</code>```

However, I get the following error, when trying to display in my pug view the user object:

```<code>TypeError: /home/ubuntu/workspace/src/views/includes/_sidebar.pug:6
    4|          .user-panel
    5|                  .pull-left.info
  > 6|                          p= user.name
    7|                          p= user.role
    8|
    9|          // Sidebar Menu

Cannot read property 'name' of undefined
</code>```

Any suggestions why the user object is not available in the views AFTER I have properly logged in a user?

答:
In your isAuthenticated function, the req.session.user is undefined
Passport.js store user object in req.use for each authenticated route, session only store userId.

Your middleware in app.js file is OK, but the isAuthenticated overwrite  res.locals.user to undefined.

In my opinion you need remove the middleware (because it use in all routes) and change isAuthenticated like this:

```<code>exports.isAuthenticated = (req, res, next) => {
  if (req.isAuthenticated()) {
    res.locals.user = req.user
    return next()
  }
  res.redirect('/')
}
</code>```

Body:
I am trying to use res.locals.user to show the user object in the frontend.

Below you can see in my main app.js file the middleware I have created:

...
const passport = require('passport')

const auth = require('./routes/auth')
const index = require('./routes/index')

const app = express()

// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')
app.use(logger(process.env.LOG_ENV))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
  extended: false,
}))
app.use(express.static(path.join(__dirname, '/../public')))
app.use(cookieParser())

app.use(session({
  secret: 'super-mega-hyper-secret',
  resave: false,
  saveUninitialized: true,
}))
app.use(passport.initialize())
app.use(passport.session())
app.use((req, res, next) => { //This middleware checks the local user
  res.locals.user = req.user
  next()
})
...

My passport file looks like the following:

const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
const serviceAuth = require('../service/auth')

passport.serializeUser((user, done) => {
  done(null, user.id)
})

passport.deserializeUser(async(id, done) => {
  const user = await serviceAuth.findById(id)
  done(null, user)
})

// Sign in with username and Password
passport.use('local', new LocalStrategy({
  usernameField: 'username',
}, async(username, password, done) => {
  const user = await serviceAuth.signin(username, password)
  done(null, user)
}))

/**
 * Login Required middleware.
 */
exports.isAuthenticated = (req, res, next) => {
  if (req.isAuthenticated()) {
    res.locals.user = req.session.user
    return next()
  }
  res.redirect('/')
}

However, I get the following error, when trying to display in my pug view the user object:

TypeError: /home/ubuntu/workspace/src/views/includes/_sidebar.pug:6
    4|          .user-panel
    5|                  .pull-left.info
  > 6|                          p= user.name
    7|                          p= user.role
    8|
    9|          // Sidebar Menu

Cannot read property 'name' of undefined

Any suggestions why the user object is not available in the views AFTER I have properly logged in a user?

Body:
In your isAuthenticated function, the req.session.user is undefined
Passport.js store user object in req.use for each authenticated route, session only store userId.

Your middleware in app.js file is OK, but the isAuthenticated overwrite  res.locals.user to undefined.

In my opinion you need remove the middleware (because it use in all routes) and change isAuthenticated like this:

exports.isAuthenticated = (req, res, next) => {
  if (req.isAuthenticated()) {
    res.locals.user = req.user
    return next()
  }
  res.redirect('/')
}


来源: stackexchange

问:
a puzzle about definition of the time complexity
Wikipedia defines time complexity as

In computer science, the time complexity of an algorithm quantifies
  the amount of time taken by an algorithm to run as a function of the
  length of the string representing the input.

What's mean of the strong part?

I know algorithm may be treated as a function but why its input must be "the length of the string representing"?

答:
The defition is derived from the context of Turing machines where you define different states. Every function which you can compute with a computer is also computeable with turing machine.(i would say that computer computes a function on the basis of turing machine)

Every fucntion is just a mapping from one domain to other domain or same domain.

Before going to Turing machines look at the concept of finite-automata.It has finite states.If your input is of length n then it's possible that it only needs two stats but it has to visit those states n times where n is legnth of the string.

Not a good sketch but look at the image below ,our final state is C , means if

end with a string in c our string will be accepted.

We use unary numberal system. We want to check if this this string gets accepted by our automata: string is 010101010

When we read 0 from A we move to B and if we read again a 0 we will move to C and if we end with 0 our string gets accepted otherwise we move to A again.

In computer you represent numbers as strings with length n and in order to compute it you have to visit each character of the string.

Turing machines work on the same way but finite-automata only is limited to regular languages. How this is a big theory

Did you ever try to think how computer computes a function 2*x where x is your input.
It's fun :D . Suppose i want to compute 20*2 and i represent this number with unary numeral system because it's easy. so we represetn 0 with  , 1 with 11 , 2 with 111 and etc so if we convert 20 to unary sytem we get 1111. You can think of a turing machine or computer(not advanced) , a system with linear memory.

Suppose empty spots in your memory are presented with # .

With you input you have something like this: ###1111#### where # means empty slot in memory, with your input head of your turing machine is at first 1 so you keep moving forward until you find first # once you find this you just replace it with * which is just a helping symbol and change the right side of # with 1 now move back and change one more 1 to * and write one 1 on the right side when you find a # keep doing this and you will be left with all * on the left hand side and all 1s on the right side, Now change all *s back to 1 and you have 2*x. Here is the trace and you have 2*x where x was your input.

The point is that the only thing these machines remember is the state.

#####1111#######

#####111*1######

#####11**11#####

#####1***111####

#####****1111###

#####11111111###

ContentLicense: CC BY-SA 3.0


答:
Your x input does not and should not match, because it only has one forward slash but your pattern expects two.  If you want to allow either one or two forward slashes then one possible modification to your pattern is the following:

```<code>str_match(x, "^(.*?)\\/.*?\\.instid_(.*?)\\.bin(\\d+)")[,c(2,3,4)]
</code>```

You might find the above pattern acceptable because you are only capturing what comes before the first slash.  The other two captures happen after the .instid_ token and at the very end after the bin extension.  But these would all seem to not depend on the number of slashes in the path.

Demo

Title: How to make R regex capture special character (e.g. dot (.) and underscore ( _ ) )?

Body:
I have three strings:

x <- "PB0038.1_Jundm2_1/Jaspar.instid_chr1:183286850-183287250.bin1"
y <- "Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin22"
z <- "Arid3a/MA0151.1/Jaspar.instid_chr1:183286849-183287249.bin10"

The regex

^(.*?)\\/.*?\\/.*?\\.instid_(.*?)\\.bin(\\d+)

Works fine for string y, z but not x.

> stringr::str_match(y,"^(.*?)\\/.*?\\/.*?\\.instid_(.*?)\\.bin(\\d+)")[,c(2,3,4)]
[1] "Ddit3::Cebpa"             "chr1:183286845-183287245" "22"
> stringr::str_match(z,"^(.*?)\\/.*?\\/.*?\\.instid_(.*?)\\.bin(\\d+)")[,c(2,3,4)]
[1] "Arid3a"                   "chr1:183286849-183287249" "10"
> stringr::str_match(x,"^(.*?)\\/.*?\\/.*?\\.instid_(.*?)\\.bin(\\d+)")[,c(2,3,4)]
[1] NA NA NA

How can I modify it?

The desired end result for x is

"PB0038.1_Jundm2_1",  "chr1:183286850-183287250" "1"

Body:
Your x input does not and should not match, because it only has one forward slash but your pattern expects two.  If you want to allow either one or two forward slashes then one possible modification to your pattern is the following:

str_match(x, "^(.*?)\\/.*?\\.instid_(.*?)\\.bin(\\d+)")[,c(2,3,4)]

You might find the above pattern acceptable because you are only capturing what comes before the first slash.  The other two captures happen after the .instid_ token and at the very end after the bin extension.  But these would all seem to not depend on the number of slashes in the path.

Demo


问:
Css Change color of element by click on the other element
I have pagination
How can I change background of pagination__link with text "left" when click on the other links? It is necessary to use  only CSS.

答:
You can do this, but frankly it's messy, using CSS flexible-boxes along with the relatively new :focus-within pseudo-class. This does require reversing the order of
 elements within the
 however:

.pagination {
  /* sets the display to use the flex layout: */
  display: flex;
  /* ensures the contents of the
 are shown in
     columns and in reverse-order: */
  flex-direction: column-reverse;
}

/* selects first the
 that has a focused element
   within it, then finds all subsequent
 elements,
   using the general-sibling combinator ('~') that
   also matches the :last-child pseudo-class (there can,
   obviously, be only one) then finds the  element(s)
   which is a child of that
 element: */
li:focus-within ~ li:last-child > a {
  background - color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="pagination">
  <li class="pagination__item pagination__item--active">

      Page 2

  </li>
  <li class="pagination__item">

      Page 1

  </li>
  <li class="pagination__item">

          left

  </li>
</ul></code>```

External JS Fiddle demo.

References:

:focus-within.

flex-direction.

General Sibling Combinator (~)

"Using CSS Flexible Boxes" (MDN).

Body:
You can do this, but frankly it's messy, using CSS flexible-boxes along with the relatively new :focus-within pseudo-class. This does require reversing the order of <li> elements within the <ul> however:

.pagination {
  /* sets the display to use the flex layout: */
  display: flex;
  /* ensures the contents of the <ul> are shown in
     columns and in reverse-order: */
  flex-direction: column-reverse;
}

/* selects first the <li> that has a focused element
   within it, then finds all subsequent <li> elements,
   using the general-sibling combinator ('~') that
   also matches the :last-child pseudo-class (there can,
   obviously, be only one) then finds the <a> element(s)
   which is a child of that <li> element: */
li:focus-within ~ li:last-child > a {
  background - color: red;
}

<ul class="pagination">
  <li class="pagination__item pagination__item--active">
    <a class="pagination__link" href="#">
      Page 2
    </a>
  </li>
  <li class="pagination__item">
    <a class="pagination__link" href="#">
      Page 1
    </a>
  </li>
  <li class="pagination__item">
    <a class="pagination__link" href="#">
          left
        </a>
  </li>
</ul>

External JS Fiddle demo.

References:

:focus-within.

flex-direction.

General Sibling Combinator (~)

"Using CSS Flexible Boxes" (MDN).


问:
How can I have the same javascript variable on the same page?
Our service offers the ability to drop in some javascript on your page and display some tracking data, but I'd like for customers to be able to embed multiple instances of the embed code on the same page.

The problem right now is that I can't include the same variables names on the page.

For instance:

```<code><script type="text/javascript">
  var ttp_number = "1Z8E26R80281495993"; // Tracking number

  var ttp_key="123456";
  (function(){
    document.write('<div id="ttp"></div>');
    s=document.createElement('script');
    s.type="text/javascript";
    s.src="http://c.trackthepack.com/j/e?" + Math.random();
    setTimeout("document.getElementById('ttp').appendChild(s);",1);
  })()
</script>
</code>```

Then if they wanted to be able to embed that again, I'd have to change all variable names:

```<code><script type="text/javascript">
  var ttp_number_001 = "446888240962"; // Tracking number

  var ttp_key_001="123456";
  (function(){
    document.write('<div id="ttp_001"></div>');
    s_001=document.createElement('script');
    s_001.type="text/javascript";
    s_001.src="http://c.trackthepack.com/j/e?" + Math.random();
    setTimeout("document.getElementById('ttp_001').appendChild(s_001);",1);
  })()
</script>
</code>```

I'm okay with having them change the contents of the function() block, but the ttp_number and ttp_key need to stay the same variable name.

Right now, when I have multiple embeds on the page, they all inherit the contents of the variables in the last embed code.

So, the ultimate question here...how do I fix that?

答:
Why are you cachebusting with Math.random()? Does the JavaScript at http://c.trackthepack.com/j/e change often? If not, you should let the cache do its job.

But if so, could you make it dynamic enough to inspect the arguments it's called with and use those arguments directly, instead of relaying them via the global window object, so that you load http://c.trackthepack.com/j/e?n=446888240962&k=123456 and it doesn't have to look them up when the script runs?

ContentLicense: CC BY-SA 2.5

Body:
Our service offers the ability to drop in some javascript on your page and display some tracking data, but I'd like for customers to be able to embed multiple instances of the embed code on the same page.

The problem right now is that I can't include the same variables names on the page.

For instance:

Then if they wanted to be able to embed that again, I'd have to change all variable names:

I'm okay with having them change the contents of the function() block, but the ttp_number and ttp_key need to stay the same variable name.

Right now, when I have multiple embeds on the page, they all inherit the contents of the variables in the last embed code.

So, the ultimate question here...how do I fix that?


问:
Using Tkinter in Jupyter Notebook
I have just started using Tkinter and trying to create a simple pop-up box in python. I have copy pasted a simple code from a website:

```<code>from Tkinter import *

master = Tk()
Label(master, text="First Name").grid(row=0)
Label(master, text="Last Name").grid(row=1)

e1 = Entry(master)
e2 = Entry(master)

e1.grid(row=0, column=1)
e2.grid(row=1, column=1)

mainloop( )
</code>```

This code is taking really long time to run, it has been almost 5 minutes!
Is it not possible to just run this snippet?
Can anybody tell me how to use Tkinter?

I am using jupyter notebook and python version 2.7. I would request a solution for this version only.

答:
Your code is working just fine. Nevertheless for those using python3 module name has changed from Tkinter to tkinter all in lowercase. Edit the name and you're good to go!

In a nutshell.

python2:

```<code>from Tkinter import *
</code>```

python3:

```<code>from tkinter import *
</code>```

Look at the screenshot below

Title: Using Tkinter in Jupyter Notebook

Body:
I have just started using Tkinter and trying to create a simple pop-up box in python. I have copy pasted a simple code from a website:

from Tkinter import *

master = Tk()
Label(master, text="First Name").grid(row=0)
Label(master, text="Last Name").grid(row=1)

e1 = Entry(master)
e2 = Entry(master)

e1.grid(row=0, column=1)
e2.grid(row=1, column=1)

mainloop( )

This code is taking really long time to run, it has been almost 5 minutes!
Is it not possible to just run this snippet?
Can anybody tell me how to use Tkinter?

I am using jupyter notebook and python version 2.7. I would request a solution for this version only.

Body:
Your code is working just fine. Nevertheless for those using python3 module name has changed from Tkinter to tkinter all in lowercase. Edit the name and you're good to go!

In a nutshell.

python2:

from Tkinter import *

python3:

from tkinter import *

Look at the screenshot below


问:
Formatting JSON as an Array in ASP.NET MVC
I'm having a hard time in returning the formatted JSON as an array. My current code already returns JSON as an array but I want to get rid of these bracket first [] to get my desired output.

Controller

```<code>public JsonResult GenerateGanttChart()
    {
        SPMS_GanttChartLayers ddl = new SPMS_GanttChartLayers();
        var data = ddl.GenerateGanttChart();
        return Json(data, JsonRequestBehavior.AllowGet);
    }
</code>```

Layer

```<code>public IEnumerable<SPMS_GanttChartRootModel> GenerateGanttChart()
    {
        List<SPMS_GanttChartModel> child_data = new List<SPMS_GanttChartModel>();
        {
            using (SqlConnection con = new SqlConnection(Conn.MyConn()))
            {
                SqlCommand com = new SqlCommand("dbo.sp_SPMS_GanttChart 7078, 1", con);
                con.Open();
                SqlDataReader reader = com.ExecuteReader();
                while (reader.Read())
                {
                    SPMS_GanttChartModel value = new SPMS_GanttChartModel();
                    value.id = Convert.ToInt32(reader.GetValue(0));
                    value.start_date = Convert.ToString(reader.GetValue(1));
                    value.duration = Convert.ToInt32(reader.GetValue(2));
                    value.text = Convert.ToString(reader.GetValue(3));
                    child_data.Add(value);
                }
            }

        }
        List<SPMS_GanttChartRootModel> array = new List<SPMS_GanttChartRootModel>();
        {
            SPMS_GanttChartRootModel value = new SPMS_GanttChartRootModel();
            value.data = child_data;
            array.Add(value);
        };
        return array;
    }
</code>```

Current Output

```<code>[{
"data": [{
    "id": 1,
    "start_date": "11/07/2017 08:00:00 AM",
    "duration": 23,
    "text": "Project #1"
}, ... ]
}]
</code>```

Desired Output

```<code>{
"data": [{
    "id": 1,
    "start_date": "11/07/2017 08:00:00 AM",
    "duration": 23,
    "text": "Project #1"
}, ... ]
}
</code>```

答:
Currently you are returning a List<SPMS_GanttChartRootModel> from your GenerateGanttChart method.

Return the SPMS_GanttChartRootModel object.

```<code>SPMS_GanttChartRootModel value = new SPMS_GanttChartRootModel();
value.data = child_data;
return value;
</code>```

Also make sure your method's return type is SPMS_GanttChartRootModel now

```<code>public SPMS_GanttChartRootModel  GenerateGanttChart()
{
    var child_data = new List<SPMS_GanttChartModel>();
    {
        //your existing code to populate this collection
    };

     var value = new SPMS_GanttChartRootModel();
     value.data = child_data;
     return value;
}
</code>```

and in your action method, pass this single object to the Json method

```<code>public JsonResult GenerateGanttChart()
{
    var ddl = new SPMS_GanttChartLayers();
    var data = ddl.GenerateGanttChart();
    return Json(data, JsonRequestBehavior.AllowGet);
}
</code>```

Body:
I'm having a hard time in returning the formatted JSON as an array. My current code already returns JSON as an array but I want to get rid of these bracket first [] to get my desired output.

Controller

public JsonResult GenerateGanttChart()
    {
        SPMS_GanttChartLayers ddl = new SPMS_GanttChartLayers();
        var data = ddl.GenerateGanttChart();
        return Json(data, JsonRequestBehavior.AllowGet);
    }

Layer

public IEnumerable<SPMS_GanttChartRootModel> GenerateGanttChart()
    {
        List<SPMS_GanttChartModel> child_data = new List<SPMS_GanttChartModel>();
        {
            using (SqlConnection con = new SqlConnection(Conn.MyConn()))
            {
                SqlCommand com = new SqlCommand("dbo.sp_SPMS_GanttChart 7078, 1", con);
                con.Open();
                SqlDataReader reader = com.ExecuteReader();
                while (reader.Read())
                {
                    SPMS_GanttChartModel value = new SPMS_GanttChartModel();
                    value.id = Convert.ToInt32(reader.GetValue(0));
                    value.start_date = Convert.ToString(reader.GetValue(1));
                    value.duration = Convert.ToInt32(reader.GetValue(2));
                    value.text = Convert.ToString(reader.GetValue(3));
                    child_data.Add(value);
                }
            }

        }
        List<SPMS_GanttChartRootModel> array = new List<SPMS_GanttChartRootModel>();
        {
            SPMS_GanttChartRootModel value = new SPMS_GanttChartRootModel();
            value.data = child_data;
            array.Add(value);
        };
        return array;
    }

Current Output

[{
"data": [{
    "id": 1,
    "start_date": "11/07/2017 08:00:00 AM",
    "duration": 23,
    "text": "Project #1"
}, ... ]
}]

Desired Output

{
"data": [{
    "id": 1,
    "start_date": "11/07/2017 08:00:00 AM",
    "duration": 23,
    "text": "Project #1"
}, ... ]
}

Body:
Currently you are returning a List<SPMS_GanttChartRootModel> from your GenerateGanttChart method.

Return the SPMS_GanttChartRootModel object.

SPMS_GanttChartRootModel value = new SPMS_GanttChartRootModel();
value.data = child_data;
return value;

Also make sure your method's return type is SPMS_GanttChartRootModel now

public SPMS_GanttChartRootModel  GenerateGanttChart()
{
    var child_data = new List<SPMS_GanttChartModel>();
    {
        //your existing code to populate this collection
    };

     var value = new SPMS_GanttChartRootModel();
     value.data = child_data;
     return value;
}

and in your action method, pass this single object to the Json method

public JsonResult GenerateGanttChart()
{
    var ddl = new SPMS_GanttChartLayers();
    var data = ddl.GenerateGanttChart();
    return Json(data, JsonRequestBehavior.AllowGet);
}


问:
Compile an asm bootloader with external c code
I write a boot loader in asm and want to add some compiled C code in my project.

I created a test function here:

test.c

```<code>__asm__(".code16\n");

void print_str() {
    __asm__ __volatile__("mov $'A' , %al\n");
    __asm__ __volatile__("mov $0x0e, %ah\n");
    __asm__ __volatile__("int $0x10\n");
}
</code>```

And here is the asm code (the boot loader):

hw.asm

```<code>[org 0x7C00]
[BITS 16]
[extern print_str] ;nasm tip

start:
mov ax, 0
mov ds, ax
mov es, ax
mov ss, ax
mov sp, 0x7C00

mov si, name
call print_string

mov al, ' '
int 10h

mov si, version
call print_string

mov si, line_return
call print_string

call print_str ;call function

mov si, welcome
call print_string

jmp mainloop

mainloop:
mov si, prompt
call print_string

mov di, buffer
call get_str

mov si, buffer
cmp byte [si], 0
je mainloop

mov si, buffer
;call print_string
mov di, cmd_version
call strcmp
jc .version

jmp mainloop

.version:
mov si, name
call print_string

mov al, ' '
int 10h

mov si, version
call print_string

mov si, line_return
call print_string
jmp mainloop

name db 'MOS', 0
version db 'v0.1', 0
welcome db 'Developped by Marius Van Nieuwenhuyse', 0x0D, 0x0A, 0
prompt db '>', 0
line_return db 0x0D, 0x0A, 0
buffer times 64 db 0

cmd_version db 'version', 0

%include "functions/print.asm"
%include "functions/getstr.asm"
%include "functions/strcmp.asm"

times 510 - ($-$$) db 0
dw 0xaa55
</code>```

I need to call the c function like a simple asm function
Without the extern and the call print_str, the asm script boot in VMWare.

I tried to compile with:

```<code>nasm -f elf32
</code>```

But i can't call org 0x7C00

答:
Compiling & Linking NASM and GCC Code

This question has a more complex answer than one might believe, although it is possible. Can the first stage of a bootloader (the original 512 bytes that get loaded at physical address 0x07c00) make a call into a C function? Yes, but it requires rethinking how you build your project.

For this to work you can no longer us -f bin with NASM. This also means you can't use the org 0x7c00 to tell the assembler what address the code expects to start from. You'll need to do this through a linker (either us LD directly or GCC for linking). Since the linker will lay things out in memory we can't rely on placing the boot sector signature 0xaa55 in our output file. We can get the linker to do that for us.

The first problem you will discover is that the default linker scripts used internally by GCC don't lay things out the way we want. We'll need to create our own. Such a linker script will have to set the origin point (Virtual Memory Address aka VMA) to 0x7c00, place the code from your assembly file before the data and place the boot signature at offset 510 in the file. I'm not going to write a tutorial on Linker scripts. The Binutils Documentation contains almost everything you need to know about linker scripts.

```<code>OUTPUT_FORMAT("elf32-i386");
/* We define an entry point to keep the linker quiet. This entry point
 * has no meaning with a bootloader in the binary image we will eventually
 * generate. Bootloader will start executing at whatever is at 0x07c00 */
ENTRY(start);
SECTIONS
{
    . = 0x7C00;
    .text : {
        /* Place the code in hw.o before all other code */
        hw.o(.text);
        *(.text);
    }

    /* Place the data after the code */
    .data : SUBALIGN(2) {
        *(.data);
        *(.rodata*);
    }

    /* Place the boot signature at LMA/VMA 0x7DFE */
    .sig 0x7DFE : {
        SHORT(0xaa55);
    }

    /* Place the uninitialised data in the area after our bootloader
     * The BIOS only reads the 512 bytes before this into memory */
    .bss : SUBALIGN(4) {
        __bss_start = .;
        *(COMMON);
        *(.bss)
        . = ALIGN(4);
        __bss_end = .;
    }
    __bss_sizeb = SIZEOF(.bss);

    /* Remove sections that won't be relevant to us */
    /DISCARD/ : {
        *(.eh_frame);
        *(.comment);
    }
}
</code>```

This script should create an ELF executable that can be converted to a flat binary file with OBJCOPY. We could have output as a binary file directly but I separate the two processes out in the event I want to include debug information in the ELF version for debug purposes.

Now that we have a linker script we must remove the ORG 0x7c00 and the boot signature. For simplicity sake we'll try to get the following code (hw.asm) to work:

```<code>extern print_str
global start
bits 16

section .text
start:
xor ax, ax         ; AX = 0
mov ds, ax
mov es, ax
mov ss, ax
mov sp, 0x7C00

call print_str     ; call function

/* Halt the processor so we don't keep executing code beyond this point */
cli
hlt
</code>```

You can include all your other code, but this sample will still demonstrate the basics of calling into a C function.

Assume the code above you can now generate the ELF object from hw.asm producing hw.o using this command:

```<code>nasm -f elf32 hw.asm -o hw.o
</code>```

You compile each C file with something like:

```<code>gcc -ffreestanding -c kmain.c -o kmain.o
</code>```

I placed the C code you had into a file called kmain.c . The command above will generate kmain.o. I noticed you aren't using a cross compiler so you'll want to use -fno-PIE to ensure we don't generate relocatable code. -ffreestanding tells GCC the C standard library may not exist, and main may not be the program entry point. You'd compile each C file in the same way.

To link this code to a final executable and then produce a flat binary file that can be booted we do this:

```<code>ld -melf_i386 --build-id=none -T link.ld kmain.o hw.o -o kernel.elf
objcopy -O binary kernel.elf kernel.bin
</code>```

You specify all the object files to link with the LD command. The LD command above will produce a 32-bit ELF executable called kernel.elf. This file can be useful in the future for debugging purposes. Here we use OBJCOPY to convert kernel.elf to a binary file called kernel.bin. kernel.bin can be used as a bootloader image.

You should be able to run it with QEMU using this command:

```<code>qemu-system-i386 -fda kernel.bin
</code>```

When run it may look like:

You'll notice the letter A appears on the last line. This is what we'd expect from the print_str code.

GCC Inline Assembly is Hard to Get Right

If we take your example code in the question:

```<code>__asm__ __volatile__("mov $'A' , %al\n");
__asm__ __volatile__("mov $0x0e, %ah\n");
__asm__ __volatile__("int $0x10\n");
</code>```

The compiler is free to reorder these __asm__ statements if it wanted to. The int $0x10 could appear before the MOV instructions. If you want these 3 lines to be output in this exact order you can combine them into one like this:

```<code>__asm__ __volatile__("mov $'A' , %al\n\t"
                     "mov $0x0e, %ah\n\t"
                     "int $0x10");
</code>```

These are basic assembly statements. It's not required to specify __volatile__on them as they are already implicitly volatile, so it has no effect. From the original poster's answer it is clear they want to eventually use variables in __asm__ blocks. This is doable with extended inline assembly (the instruction string is followed by a colon : followed by constraints.):

With extended asm you can read and write C variables from assembler and perform jumps from assembler code to C labels. Extended asm syntax uses colons (‘:’) to delimit the operand parameters after the assembler template:

```<code>asm [volatile] ( AssemblerTemplate
                : OutputOperands
                [ : InputOperands
                [ : Clobbers ] ])
</code>```

This answer isn't a tutorial on inline assembly. The general rule of thumb is that one should not use inline assembly unless you have to. Inline assembly done wrong can create hard to track bugs or have unusual side effects. Unfortunately doing 16-bit interrupts in C pretty much requires it, or you write the entire function in assembly (ie: NASM).

This is an example of a print_chr function that take a nul terminated string and prints each character out one by one using Int 10h/ah=0ah:

```<code>#include <stdint.h>
__asm__(".code16gcc\n");

void print_str(char *str) {
    while (*str) {
        /* AH=0x0e, AL=char to print, BH=page, BL=fg color */
        __asm__ __volatile__ ("int $0x10"
                              :
                              : "a" ((0x0e<<8) | *str++),
                                "b" (0x0000));
    }
}
</code>```

hw.asm would be modified to look like this:

```<code>extern print_str
global start
bits 16

section .text
start:
xor ax, ax         ; AX = 0
mov ds, ax
mov es, ax
mov ss, ax
mov sp, 0x7C00

call print_str     ; call function

/* Halt the processor so we don't keep executing code beyond this point */
cli
hlt
</code>```0

The idea when this is assembled/compiled (using the commands in the first section of this answer) and run is that it print out the welcome message. Unfortunately it will almost never work, and may even crash some emulators like QEMU.

code16 is Almost Useless and Should Not be Used

In the last section we learn that a simple function that takes a parameter ends up not working and may even crash an emulator like QEMU. The main problem is that the __asm__(".code16\n"); statement really doesn't work well with the code generated by GCC. The Binutils AS documentation says:

‘.code16gcc’ provides experimental support for generating 16-bit code from gcc, and differs from ‘.code16’ in that ‘call’, ‘ret’, ‘enter’, ‘leave’, ‘push’, ‘pop’, ‘pusha’, ‘popa’, ‘pushf’, and ‘popf’ instructions default to 32-bit size. This is so that the stack pointer is manipulated in the same way over function calls, allowing access to function parameters at the same stack offsets as in 32-bit mode. ‘.code16gcc’ also automatically adds address size prefixes where necessary to use the 32-bit addressing modes that gcc generates.

.code16gcc is what you really need to be using, not .code16. This force GNU assembler on the back end to emit address and operand prefixes on certain instructions so that the addresses and operands are treated as 4 bytes wide, and not 2 bytes.

The hand written code in NASM doesn't know it will be calling C instructions, nor does NASM have a directive like .code16gcc. You'll need to modify the assembly code to push 32-bit values on to the stack in real mode. You will also need to override the call instruction so that the return address needs to be treated as a 32-bit value, not 16-bit. This code:

```<code>extern print_str
global start
bits 16

section .text
start:
xor ax, ax         ; AX = 0
mov ds, ax
mov es, ax
mov ss, ax
mov sp, 0x7C00

call print_str     ; call function

/* Halt the processor so we don't keep executing code beyond this point */
cli
hlt
</code>```1

Should be:

```<code>extern print_str
global start
bits 16

section .text
start:
xor ax, ax         ; AX = 0
mov ds, ax
mov es, ax
mov ss, ax
mov sp, 0x7C00

call print_str     ; call function

/* Halt the processor so we don't keep executing code beyond this point */
cli
hlt
</code>```2

GCC has a requirement that the direction flag be cleared before calling any C function. I added the CLD instruction to the top of the assembly code to make sure this is the case. GCC code also needs to have CS to 0x0000 to work properly. The FAR JMP does just that.

You can also drop the __asm__(".code16gcc\n"); on modern GCC that supports the -m16 option. -m16 automatically places a .code16gcc into the file that is being compiled.

Since GCC also uses the full 32-bit stack pointer it is a good idea to initialize ESP with 0x7c00, not just SP. Change mov sp, 0x7C00 to mov esp, 0x7C00. This ensures the full 32-bit stack pointer is 0x7c00.

The modified kmain.c code should now look like:

```<code>#include <stdint.h>

void print_str(char *str) {
    while (*str) {
        /* AH=0x0e, AL=char to print, BH=page, BL=fg color */
        __asm__ __volatile__ ("int $0x10"
                              :
                              : "a" ((0x0e<<8) | *str++),
                                "b" (0x0000));
    }
}
</code>```

and hw.asm:

```<code>extern print_str
global start
bits 16

section .text
start:
    xor ax, ax            ; AX = 0
    mov ds, ax
    mov es, ax
    mov ss, ax
    mov esp, 0x7C00
    jmp 0x0000:setcs      ; Set CS to 0
setcs:
    cld                   ; GCC code requires direction flag to be cleared

    push dword welcome
    call dword print_str  ; call function
    cli
    hlt

section .data
welcome db 'Developped by Marius Van Nieuwenhuyse', 0x0D, 0x0A, 0
</code>```

These commands can be build the bootloader with:

```<code>gcc -fno-PIC -ffreestanding -m16 -c kmain.c -o kmain.o
ld -melf_i386 --build-id=none -T link.ld kmain.o hw.o -o kernel.elf
objcopy -O binary kernel.elf kernel.bin
</code>```

When run with qemu-system-i386 -fda kernel.bin it should look simialr to:

In Most Cases GCC Produces Code that Requires 80386+

There are number of disadvantages to GCC generated code using .code16gcc:

ES=DS=CS=SS must be 0

Code must fit in the first 64kb

GCC code has no understanding of 20-bit segment:offset addressing.

For anything but the most trivial C code, GCC doesn't generate code that can run on a 286/186/8086. It runs in real mode but it uses 32-bit operands and addressing not available on processors earlier than 80386.

If you want to access memory locations above the first 64kb then you need to be in Unreal Mode(big) before calling into C code.

If you want to produce real 16-bit code from a more modern C compiler I recommend OpenWatcom C

The inline assembly is not as powerful as GCC

The inline assembly syntax is different but it is easier to use and less error prone than GCC's inline assembly.

Can generate code that will run on antiquated 8086/8088 processors.

Understands 20-bit segment:offset real mode addressing and supports the concept of far and huge pointers.

wlink the Watcom linker can produce basic flat binary files usable as a bootloader.

Zero Fill the BSS Section

The BIOS boot sequence doesn't guarantee that memory is actually zero. This causes a potential problem for the zero initialized region BSS. Before calling into C code for the first time the region should be zero filled by our assembly code. The linker script I originally wrote defines a symbol __bss_start that is the offset of the BSS memory and __bss_sizeb is the size in bytes. Using this info you can use the STOSB instruction to easily zero fill it. At the top of hw.asm you can add:

```<code>extern __bss_sizeb
extern __bss_start
</code>```

And after the CLD instruction and before calling any C code you can do the zero fill this way:

```<code>; Zero fill the BSS section
mov cx, __bss_sizeb       ; Size of BSS computed in linker script
mov di, __bss_start       ; Start of BSS defined in linker script
rep stosb                 ; AL still zero, Fill memory with zero
</code>```

Other Suggestions

To reduce the bloat of the code generated by the compiler it can be useful to use -fomit-frame-pointer. Compiling with -Os can optimize for space (rather than speed). We have limited space (512 bytes) for the initial code loaded by the BIOS so these optimizations can be beneficial. The command line for compiling could appear as:

```<code>gcc -fno-PIC -fomit-frame-pointer -ffreestanding -m16 -Os -c kmain.c -o kmain.o
</code>```

Body:
I write a boot loader in asm and want to add some compiled C code in my project.

I created a test function here:

test.c

__asm__(".code16\n");

void print_str() {
    __asm__ __volatile__("mov $'A' , %al\n");
    __asm__ __volatile__("mov $0x0e, %ah\n");
    __asm__ __volatile__("int $0x10\n");
}

And here is the asm code (the boot loader):

hw.asm

[org 0x7C00]
[BITS 16]
[extern print_str] ;nasm tip

start:
mov ax, 0
mov ds, ax
mov es, ax
mov ss, ax
mov sp, 0x7C00

mov si, name
call print_string

mov al, ' '
int 10h

mov si, version
call print_string

mov si, line_return
call print_string

call print_str ;call function

mov si, welcome
call print_string

jmp mainloop

mainloop:
mov si, prompt
call print_string

mov di, buffer
call get_str

mov si, buffer
cmp byte [si], 0
je mainloop

mov si, buffer
;call print_string
mov di, cmd_version
call strcmp
jc .version

jmp mainloop

.version:
mov si, name
call print_string

mov al, ' '
int 10h

mov si, version
call print_string

mov si, line_return
call print_string
jmp mainloop

name db 'MOS', 0
version db 'v0.1', 0
welcome db 'Developped by Marius Van Nieuwenhuyse', 0x0D, 0x0A, 0
prompt db '>', 0
line_return db 0x0D, 0x0A, 0
buffer times 64 db 0

cmd_version db 'version', 0

%include "functions/print.asm"
%include "functions/getstr.asm"
%include "functions/strcmp.asm"

times 510 - ($-$$) db 0
dw 0xaa55

I need to call the c function like a simple asm function
Without the extern and the call print_str, the asm script boot in VMWare.

I tried to compile with:

nasm -f elf32

But i can't call org 0x7C00

Body:
Compiling & Linking NASM and GCC Code

This question has a more complex answer than one might believe, although it is possible. Can the first stage of a bootloader (the original 512 bytes that get loaded at physical address 0x07c00) make a call into a C function? Yes, but it requires rethinking how you build your project.

For this to work you can no longer us -f bin with NASM. This also means you can't use the org 0x7c00 to tell the assembler what address the code expects to start from. You'll need to do this through a linker (either us LD directly or GCC for linking). Since the linker will lay things out in memory we can't rely on placing the boot sector signature 0xaa55 in our output file. We can get the linker to do that for us.

The first problem you will discover is that the default linker scripts used internally by GCC don't lay things out the way we want. We'll need to create our own. Such a linker script will have to set the origin point (Virtual Memory Address aka VMA) to 0x7c00, place the code from your assembly file before the data and place the boot signature at offset 510 in the file. I'm not going to write a tutorial on Linker scripts. The Binutils Documentation contains almost everything you need to know about linker scripts.

OUTPUT_FORMAT("elf32-i386");
/* We define an entry point to keep the linker quiet. This entry point
 * has no meaning with a bootloader in the binary image we will eventually
 * generate. Bootloader will start executing at whatever is at 0x07c00 */
ENTRY(start);
SECTIONS
{
    . = 0x7C00;
    .text : {
        /* Place the code in hw.o before all other code */
        hw.o(.text);
        *(.text);
    }

    /* Place the data after the code */
    .data : SUBALIGN(2) {
        *(.data);
        *(.rodata*);
    }

    /* Place the boot signature at LMA/VMA 0x7DFE */
    .sig 0x7DFE : {
        SHORT(0xaa55);
    }

    /* Place the uninitialised data in the area after our bootloader
     * The BIOS only reads the 512 bytes before this into memory */
    .bss : SUBALIGN(4) {
        __bss_start = .;
        *(COMMON);
        *(.bss)
        . = ALIGN(4);
        __bss_end = .;
    }
    __bss_sizeb = SIZEOF(.bss);

    /* Remove sections that won't be relevant to us */
    /DISCARD/ : {
        *(.eh_frame);
        *(.comment);
    }
}

This script should create an ELF executable that can be converted to a flat binary file with OBJCOPY. We could have output as a binary file directly but I separate the two processes out in the event I want to include debug information in the ELF version for debug purposes.

Now that we have a linker script we must remove the ORG 0x7c00 and the boot signature. For simplicity sake we'll try to get the following code (hw.asm) to work:

extern print_str
global start
bits 16

section .text
start:
xor ax, ax         ; AX = 0
mov ds, ax
mov es, ax
mov ss, ax
mov sp, 0x7C00

call print_str     ; call function

/* Halt the processor so we don't keep executing code beyond this point */
cli
hlt

You can include all your other code, but this sample will still demonstrate the basics of calling into a C function.

Assume the code above you can now generate the ELF object from hw.asm producing hw.o using this command:

nasm -f elf32 hw.asm -o hw.o

You compile each C file with something like:

gcc -ffreestanding -c kmain.c -o kmain.o

I placed the C code you had into a file called kmain.c . The command above will generate kmain.o. I noticed you aren't using a cross compiler so you'll want to use -fno-PIE to ensure we don't generate relocatable code. -ffreestanding tells GCC the C standard library may not exist, and main may not be the program entry point. You'd compile each C file in the same way.

To link this code to a final executable and then produce a flat binary file that can be booted we do this:

ld -melf_i386 --build-id=none -T link.ld kmain.o hw.o -o kernel.elf
objcopy -O binary kernel.elf kernel.bin

You specify all the object files to link with the LD command. The LD command above will produce a 32-bit ELF executable called kernel.elf. This file can be useful in the future for debugging purposes. Here we use OBJCOPY to convert kernel.elf to a binary file called kernel.bin. kernel.bin can be used as a bootloader image.

You should be able to run it with QEMU using this command:

qemu-system-i386 -fda kernel.bin

When run it may look like:

You'll notice the letter A appears on the last line. This is what we'd expect from the print_str code.

GCC Inline Assembly is Hard to Get Right

If we take your example code in the question:

__asm__ __volatile__("mov $'A' , %al\n");
__asm__ __volatile__("mov $0x0e, %ah\n");
__asm__ __volatile__("int $0x10\n");

The compiler is free to reorder these __asm__ statements if it wanted to. The int $0x10 could appear before the MOV instructions. If you want these 3 lines to be output in this exact order you can combine them into one like this:

__asm__ __volatile__("mov $'A' , %al\n\t"
                     "mov $0x0e, %ah\n\t"
                     "int $0x10");

These are basic assembly statements. It's not required to specify __volatile__on them as they are already implicitly volatile, so it has no effect. From the original poster's answer it is clear they want to eventually use variables in __asm__ blocks. This is doable with extended inline assembly (the instruction string is followed by a colon : followed by constraints.):

With extended asm you can read and write C variables from assembler and perform jumps from assembler code to C labels. Extended asm syntax uses colons (‘:’) to delimit the operand parameters after the assembler template:

asm [volatile] ( AssemblerTemplate
                : OutputOperands
                [ : InputOperands
                [ : Clobbers ] ])

This answer isn't a tutorial on inline assembly. The general rule of thumb is that one should not use inline assembly unless you have to. Inline assembly done wrong can create hard to track bugs or have unusual side effects. Unfortunately doing 16-bit interrupts in C pretty much requires it, or you write the entire function in assembly (ie: NASM).

This is an example of a print_chr function that take a nul terminated string and prints each character out one by one using Int 10h/ah=0ah:

#include <stdint.h>
__asm__(".code16gcc\n");

void print_str(char *str) {
    while (*str) {
        /* AH=0x0e, AL=char to print, BH=page, BL=fg color */
        __asm__ __volatile__ ("int $0x10"
                              :
                              : "a" ((0x0e<<8) | *str++),
                                "b" (0x0000));
    }
}

hw.asm would be modified to look like this:

push welcome
call print_str ;call function

The idea when this is assembled/compiled (using the commands in the first section of this answer) and run is that it print out the welcome message. Unfortunately it will almost never work, and may even crash some emulators like QEMU.

code16 is Almost Useless and Should Not be Used

In the last section we learn that a simple function that takes a parameter ends up not working and may even crash an emulator like QEMU. The main problem is that the __asm__(".code16\n"); statement really doesn't work well with the code generated by GCC. The Binutils AS documentation says:

‘.code16gcc’ provides experimental support for generating 16-bit code from gcc, and differs from ‘.code16’ in that ‘call’, ‘ret’, ‘enter’, ‘leave’, ‘push’, ‘pop’, ‘pusha’, ‘popa’, ‘pushf’, and ‘popf’ instructions default to 32-bit size. This is so that the stack pointer is manipulated in the same way over function calls, allowing access to function parameters at the same stack offsets as in 32-bit mode. ‘.code16gcc’ also automatically adds address size prefixes where necessary to use the 32-bit addressing modes that gcc generates.

.code16gcc is what you really need to be using, not .code16. This force GNU assembler on the back end to emit address and operand prefixes on certain instructions so that the addresses and operands are treated as 4 bytes wide, and not 2 bytes.

The hand written code in NASM doesn't know it will be calling C instructions, nor does NASM have a directive like .code16gcc. You'll need to modify the assembly code to push 32-bit values on to the stack in real mode. You will also need to override the call instruction so that the return address needs to be treated as a 32-bit value, not 16-bit. This code:

push welcome
call print_str ;call function

Should be:

    jmp 0x0000:setcs
setcs:
    cld
    push dword welcome
    call dword print_str ;call function

GCC has a requirement that the direction flag be cleared before calling any C function. I added the CLD instruction to the top of the assembly code to make sure this is the case. GCC code also needs to have CS to 0x0000 to work properly. The FAR JMP does just that.

You can also drop the __asm__(".code16gcc\n"); on modern GCC that supports the -m16 option. -m16 automatically places a .code16gcc into the file that is being compiled.

Since GCC also uses the full 32-bit stack pointer it is a good idea to initialize ESP with 0x7c00, not just SP. Change mov sp, 0x7C00 to mov esp, 0x7C00. This ensures the full 32-bit stack pointer is 0x7c00.

The modified kmain.c code should now look like:

#include <stdint.h>

void print_str(char *str) {
    while (*str) {
        /* AH=0x0e, AL=char to print, BH=page, BL=fg color */
        __asm__ __volatile__ ("int $0x10"
                              :
                              : "a" ((0x0e<<8) | *str++),
                                "b" (0x0000));
    }
}

and hw.asm:

extern print_str
global start
bits 16

section .text
start:
    xor ax, ax            ; AX = 0
    mov ds, ax
    mov es, ax
    mov ss, ax
    mov esp, 0x7C00
    jmp 0x0000:setcs      ; Set CS to 0
setcs:
    cld                   ; GCC code requires direction flag to be cleared

    push dword welcome
    call dword print_str  ; call function
    cli
    hlt

section .data
welcome db 'Developped by Marius Van Nieuwenhuyse', 0x0D, 0x0A, 0

These commands can be build the bootloader with:

gcc -fno-PIC -ffreestanding -m16 -c kmain.c -o kmain.o
ld -melf_i386 --build-id=none -T link.ld kmain.o hw.o -o kernel.elf
objcopy -O binary kernel.elf kernel.bin

When run with qemu-system-i386 -fda kernel.bin it should look simialr to:

In Most Cases GCC Produces Code that Requires 80386+

There are number of disadvantages to GCC generated code using .code16gcc:

ES=DS=CS=SS must be 0

Code must fit in the first 64kb

GCC code has no understanding of 20-bit segment:offset addressing.

For anything but the most trivial C code, GCC doesn't generate code that can run on a 286/186/8086. It runs in real mode but it uses 32-bit operands and addressing not available on processors earlier than 80386.

If you want to access memory locations above the first 64kb then you need to be in Unreal Mode(big) before calling into C code.

If you want to produce real 16-bit code from a more modern C compiler I recommend OpenWatcom C

The inline assembly is not as powerful as GCC

The inline assembly syntax is different but it is easier to use and less error prone than GCC's inline assembly.

Can generate code that will run on antiquated 8086/8088 processors.

Understands 20-bit segment:offset real mode addressing and supports the concept of far and huge pointers.

wlink the Watcom linker can produce basic flat binary files usable as a bootloader.

Zero Fill the BSS Section

The BIOS boot sequence doesn't guarantee that memory is actually zero. This causes a potential problem for the zero initialized region BSS. Before calling into C code for the first time the region should be zero filled by our assembly code. The linker script I originally wrote defines a symbol __bss_start that is the offset of the BSS memory and __bss_sizeb is the size in bytes. Using this info you can use the STOSB instruction to easily zero fill it. At the top of hw.asm you can add:

extern __bss_sizeb
extern __bss_start

And after the CLD instruction and before calling any C code you can do the zero fill this way:

; Zero fill the BSS section
mov cx, __bss_sizeb       ; Size of BSS computed in linker script
mov di, __bss_start       ; Start of BSS defined in linker script
rep stosb                 ; AL still zero, Fill memory with zero

Other Suggestions

To reduce the bloat of the code generated by the compiler it can be useful to use -fomit-frame-pointer. Compiling with -Os can optimize for space (rather than speed). We have limited space (512 bytes) for the initial code loaded by the BIOS so these optimizations can be beneficial. The command line for compiling could appear as:

gcc -fno-PIC -fomit-frame-pointer -ffreestanding -m16 -Os -c kmain.c -o kmain.o

ContentLicense: CC BY-SA 4.0


问:
PyTorch loss function evaluation
I am trying to optimise a function (fit) using the acceleration of GPU in PyTorch. This is the straight Python code, where I doing the evaluation of fit:

```<code>import numpy as np
...
for j in range(P):
    e[:,j] = z - h[:,j];
    fit[j] = 1/(sqrt(2*pi)*sigma*N)*np.sum(exp(-(e[:,j]**2)/(2*sigma**2)));
</code>```

The dimension of the variables are:
  z[Nx1], h[NxP], e[NxP], fit[1xP].
  where P is the number of dimension of fit and N is the length of each dimension.

I am aware that for loops should be avoided, so where it is my attempt to do it using PyTorch through torch.cuda.FloatTensor.

```<code>import torch
dtype = torch.cuda.FloatTensor
e     = z - h;
fit   = 1/(torch.sqrt(2*pi)*sigma*N)*torch.sum(torch.exp(-(torch.pw(e,2))/(2*torch.pow(sigma,2))));
</code>```

Unfortunately it is not working. What is wrong?
  Thank you!

答:
I guess you are getting size mismatch error at the following line.

```<code>e = z - h
</code>```

In your example, z is a vector (2d tensor of shape Nx1) and h is a 2d tensor of shape NxP. So, you can't directly subtract h from z.

You can do the following to avoid size mismatch error.

```<code>e = z.expand(*h.size()) - h
</code>```

Here, z.expand(*h.size()) will convert the tensor z from Nx1 to NxP shape by duplicating the column vector P times.

Title: PyTorch loss function evaluation

Body:
I am trying to optimise a function (fit) using the acceleration of GPU in PyTorch. This is the straight Python code, where I doing the evaluation of fit:

import numpy as np
...
for j in range(P):
    e[:,j] = z - h[:,j];
    fit[j] = 1/(sqrt(2*pi)*sigma*N)*np.sum(exp(-(e[:,j]**2)/(2*sigma**2)));

The dimension of the variables are:
  z[Nx1], h[NxP], e[NxP], fit[1xP].
  where P is the number of dimension of fit and N is the length of each dimension.

I am aware that for loops should be avoided, so where it is my attempt to do it using PyTorch through torch.cuda.FloatTensor.

import torch
dtype = torch.cuda.FloatTensor
e     = z - h;
fit   = 1/(torch.sqrt(2*pi)*sigma*N)*torch.sum(torch.exp(-(torch.pw(e,2))/(2*torch.pow(sigma,2))));

Unfortunately it is not working. What is wrong?
  Thank you!

Body:
I guess you are getting size mismatch error at the following line.

e = z - h

In your example, z is a vector (2d tensor of shape Nx1) and h is a 2d tensor of shape NxP. So, you can't directly subtract h from z.

You can do the following to avoid size mismatch error.

e = z.expand(*h.size()) - h

Here, z.expand(*h.size()) will convert the tensor z from Nx1 to NxP shape by duplicating the column vector P times.


问:
Cannot install tflearn in python 3
I have tensorflow 1.11.9 for python 3 and am trying to install tflearn.

I tried installation using:

"pip3 install git+https://github.com/tflearn/tflearn.git"

"pip3 install tflearn"

"pip install git+https://github.com/tflearn/tflearn.git"

"pip install git+https://github.com/tflearn/tflearn.git"

Nothing seems to work. pip install is installing a tflearn version for python 2 (I have python2.7 and 3.4 on Ubuntu 14.04), whereas pip3 is claiming that installation is successful, but I get an error saying

"No module named 'tensorflow.contrib.rnn.python.ops.core_rnn'".

Can anyone suggest what am I doing wrong? I would be happy to provide any further information that might be required. Thanks in advance.

答: I think your tensorflow version is probably a bit low. Current one is 1.4</p>

Title: Cannot install tflearn in python 3


问:
selenium movetoelement not working after navigate back
I am using

```<code>WebElement element = driver.findElement(By.xpath(".//*[@id='topNav"+menue+"']"));
      new Actions(driver).moveToElement(element).perform();
</code>```

This code for the first time works fine and I can click on link and go to new page.

Now I need to go back to previous page which is home page, so I use:

```<code>driver.navigate().back();
</code>```

after this line even if I do the same first two line above not working

and I used

driver.navigate.refresh();

or

```<code>driver.navigate().to("mysite.com");
</code>```

still not working.

selenium version is 2.53.1  and firefox version 46.0
and I tried the other version of selenium and firefox

please let me know what is the problem.

Thank you

答:
I resolved this problem this way:

First before executing:

driver.navigate().back(), when we are in the initial home page,  save the current page:

String home =driver.getCurrentUrl();

Then every time I need to go back to home page instead of using:

driver.navigate().back();     I just use:

driver.get(home);

and now we are in the home page and moveToElemnt works fine:

Actions action = new Actions(driver);

action.moveToElement(element).build().perform();

Thanks

Body:
I am using

WebElement element = driver.findElement(By.xpath(".//*[@id='topNav"+menue+"']"));
      new Actions(driver).moveToElement(element).perform();

This code for the first time works fine and I can click on link and go to new page.

Now I need to go back to previous page which is home page, so I use:

driver.navigate().back();

after this line even if I do the same first two line above not working

and I used

driver.navigate.refresh();

or

driver.navigate().to("mysite.com");

still not working.

selenium version is 2.53.1  and firefox version 46.0
and I tried the other version of selenium and firefox

please let me know what is the problem.

Thank you


问:
Split string between two special characters
The Objective

I want to retrieve all the emails between the special characters < > of the string into an array of emails

```<code>$list = '"momo rabit" <m.rabit@sfr.fr>, "youn" <youn@hotmail.fr>, "yourmail" <yourmail@gmail.com>, "yovan" <y.yovan@orange.fr>, "popol" <popol.paul@alice.fr>';
</code>```

What I tried

Based on this answer, it should work.

```<code>$list = htmlspecialchars($list);
preg_match_all("/<(.*?)>/", $list, $list_step);
var_dump($list_step); // Return empty arrays
</code>```

I also tried without success

preg-split

str_getcsv

答:
The answer is pretty easy. The htmlspecialchars converts the < and > to < and >. So either change the regex or remove that function.

```<code>$list = '"momo rabit" <m.rabit@sfr.fr>, "youn" <youn@hotmail.fr>, "yourmail" <yourmail@gmail.com>, "yovan" <y.yovan@orange.fr>, "popol" <popol.paul@alice.fr>';
//$list = htmlspecialchars($list);
preg_match_all("/<(.*?)>/", $list, $list_step);
var_dump($list_step); // Return empty arrays
</code>```

Demo: https://3v4l.org/VUY1U

Alternative:

```<code>$list = '"momo rabit" <m.rabit@sfr.fr>, "youn" <youn@hotmail.fr>, "yourmail" <yourmail@gmail.com>, "yovan" <y.yovan@orange.fr>, "popol" <popol.paul@alice.fr>';
$list = htmlspecialchars($list);
preg_match_all("/<(.*?)>/", $list, $list_step);
var_dump($list_step); // Return empty arrays
</code>```

Demo: https://3v4l.org/gI07A

Body:
The Objective

I want to retrieve all the emails between the special characters < > of the string into an array of emails

$list = '"momo rabit" <m.rabit@sfr.fr>, "youn" <youn@hotmail.fr>, "yourmail" <yourmail@gmail.com>, "yovan" <y.yovan@orange.fr>, "popol" <popol.paul@alice.fr>';

What I tried

Based on this answer, it should work.

$list = htmlspecialchars($list);
preg_match_all("/<(.*?)>/", $list, $list_step);
var_dump($list_step); // Return empty arrays

I also tried without success

preg-split

str_getcsv

Body:
The answer is pretty easy. The htmlspecialchars converts the < and > to &lt; and &gt;. So either change the regex or remove that function.

$list = '"momo rabit" <m.rabit@sfr.fr>, "youn" <youn@hotmail.fr>, "yourmail" <yourmail@gmail.com>, "yovan" <y.yovan@orange.fr>, "popol" <popol.paul@alice.fr>';
//$list = htmlspecialchars($list);
preg_match_all("/<(.*?)>/", $list, $list_step);
var_dump($list_step); // Return empty arrays

Demo: https://3v4l.org/VUY1U

Alternative:

$list = '"momo rabit" <m.rabit@sfr.fr>, "youn" <youn@hotmail.fr>, "yourmail" <yourmail@gmail.com>, "yovan" <y.yovan@orange.fr>, "popol" <popol.paul@alice.fr>';
$list = htmlspecialchars($list);
preg_match_all("/&lt;(.*?)&gt;/", $list, $list_step);
var_dump($list_step); // Return empty arrays

Demo: https://3v4l.org/gI07A


问:
One to many linq Eager load
I am working with the following technologies: C#, SQL Server, ASP.NET and Entity Framework and Linq.
I have a many to many relation , using eager load. I want to get all the courses where a student is inscribed. As you can see I have a one to many relation from student to inscribe table.

The model classes:

```<code>public class Courses
{
    [Required]
    public int Id { get; set; }
    //more properties here
     public student stud { get; set; }
}

public class Enroll
{
    [Key]
    public intId { get; set; }
    //properties here
    [Required]
    public string StudentId{ get; set; }
    public Courses Courses{ get; set; }
}
public class student{
 public intId { get; set; }
  //other properties
  public Inscripe Inscription {get;set}
}
</code>```

This is what my controller:

```<code>public IEnumerable<course> GetCoursesStudent(Int studentId)
{
     //some code here to validate
     var result = _dbContext
.Enroll.Include(c => c.Courses)
.Where(c => c.StudentId == studentId)
.SelectMany(c => c.Courses).ToList();
}
</code>```

problem :
I receive an error from the SelectMany: the type aregument for method Queribly.selectMany(IQueryableExpression>> can not be infered from the usage.

How can I fix it?

答:
The type you specified for the IEnumerable is wrong. It should be "Courses" instead of "course":

```<code>public IEnumerable<Courses> GetCoursesStudent(Int studentId)
{
    var result = _dbContext
        .Enroll
        .Include(c => c.Courses)
        .Where(c => c.StudentId == studentId)
        .SelectMany(c => c.Courses)
        .ToList();
}
</code>```

And the "Courses" property of Enroll class should be an enumerable:

```<code>public class Enroll
{
    [Key]
    public intId { get; set; }

    [Required]
    public string StudentId { get; set; }
    public IEnumerable<Courses> Courses { get; set; }
}
</code>```

Title: One to many linq Eager load

Body:
I am working with the following technologies: C#, SQL Server, ASP.NET and Entity Framework and Linq.
I have a many to many relation , using eager load. I want to get all the courses where a student is inscribed. As you can see I have a one to many relation from student to inscribe table.

The model classes:

public class Courses
{
    [Required]
    public int Id { get; set; }
    //more properties here
     public student stud { get; set; }
}

public class Enroll
{
    [Key]
    public intId { get; set; }
    //properties here
    [Required]
    public string StudentId{ get; set; }
    public Courses Courses{ get; set; }
}
public class student{
 public intId { get; set; }
  //other properties
  public Inscripe Inscription {get;set}
}

This is what my controller:

public IEnumerable<course> GetCoursesStudent(Int studentId)
{
     //some code here to validate
     var result = _dbContext
.Enroll.Include(c => c.Courses)
.Where(c => c.StudentId == studentId)
.SelectMany(c => c.Courses).ToList();
}

problem :
I receive an error from the SelectMany: the type aregument for method Queribly.selectMany(IQueryableExpression>> can not be infered from the usage.

How can I fix it?

Body:
The type you specified for the IEnumerable is wrong. It should be "Courses" instead of "course":

public IEnumerable<Courses> GetCoursesStudent(Int studentId)
{
    var result = _dbContext
        .Enroll
        .Include(c => c.Courses)
        .Where(c => c.StudentId == studentId)
        .SelectMany(c => c.Courses)
        .ToList();
}

And the "Courses" property of Enroll class should be an enumerable:

public class Enroll
{
    [Key]
    public intId { get; set; }

    [Required]
    public string StudentId { get; set; }
    public IEnumerable<Courses> Courses { get; set; }
}


问:
Javascript (JS) application working on Chrome but not on mozilla firefox/safari
Here is my problem, i created a web application where you need to load a file (image) then it appears in a canvas after a resizing in order not to excess 1500 px. Then i use a canvas zoom programmed like this (another canvas where i zoom on the mouse position):

```<code>var x1, wdth1, psx1, wdth2, y1, heg1, psy1, heg2;
function drawZoom(x, y) {
    $('#zoom').css({
        'left': x - (parseInt($('#zoom').css('width')) / 2),
        'top': y - (parseInt($('#zoom').css('height')) / 2)
    });
    // console.log([x,y]);
    $('#zoom').show(function () {
        if (x < 25) {
            x1 = 0;
            wdth1 = (x + zoom_level / 2) * ratio;
            psx1 = (25 - x) * 2;
            wdth2 = 100 - psx1;
        } else if (x > width_canvas - zoom_level/ 2) {
            x1 = (x - zoom_level/ 2) * ratio;
            wdth1 = (width_canvas - x + zoom_level/ 2) * ratio;
            psx1 = 0;
            wdth2 = 100 - 2 * (x + zoom_level/ 2 - width_canvas);
        } else {
            x1 = (x - zoom_level/ 2) * ratio;
            wdth1 = zoom_level* ratio;
            psx1 = 0;
            wdth2 = 100;
        }
        if (y < 25) {
            y1 = 0;
            heg1 = (y + zoom_level/ 2) * ratio;
            psy1 = (25 - y) * 2;
            heg2 = 100 - psy1;
        } else if (y >= height_canvas - zoom_level/ 2) {
            y1 = (y - zoom_level/ 2) * ratio;
            heg1 = (height_canvas - y + zoom_level/ 2) * ratio - 1;
            psy1 = 0;
            heg2 = 100 - 2 * (y + zoom_level/ 2 - height_canvas);
        } else {
            y1 = (y - zoom_level/ 2) * ratio;
            heg1 = zoom_level* ratio;
            psy1 = 0;
            heg2 = 100;
        }
        // console.log(heg1);
        zoomctx.fillStyle = "black";
        zoomctx.fillRect(0, 0, 100, 100);
        zoomctx.drawImage(canvas, x1, y1, wdth1, heg1, psx1, psy1, wdth2, heg2);
    });
    zoomctx.beginPath();
    zoomctx.moveTo(0, 50);
    zoomctx.lineTo(100, 50);
    zoomctx.moveTo(50, 0);
    zoomctx.lineTo(50, 100);
    zoomctx.closePath();
    zoomctx.stroke();
}
</code>```

then i save the positions of the click and use them in order to calculate a distance etc.... (another story)
so i have a reset button, when you start clicking and fail one of the 4 click needed you can restart, it deletes all the points and restarts the fonction.

ISSUES :

-Chrome: works like a charm, no problem, nice zoom, smooth navigation, restart works perfectly etc....

-Firefox: i have a black circle on the left top corner (it's the zoom but it's all black, not working), it doesn't move, i can click and restart but i can't see where i click and the process after clicking doesn't work.

-Safari: the image appears well, the zoom is ok when i first load the image, i can click 4 times and the rest of the program works fine but if i restart then the zoom is like shifted when i put my mouse somewhere and the zoom doesn't show me the right place.

so i have no issue on chrome, and 2 different issues on safari and mozilla firefox, no error in the console.

i'm a beginner so i dont know if the is some constraints as the "webkit" in CSS for JS.

Tell me if you need more info ! Thanks !

答:
Canvas drawing isn't supported in Firefox, but there are Mozilla specific alternatives.  See https://caniuse.com/#search=Canvas

As far as your issues with the positioning after resetting the zoom in safari, please post your reset button functionality. Chances are, you are missing some reinitialization of your position/coordinate tracking.

Body:
Here is my problem, i created a web application where you need to load a file (image) then it appears in a canvas after a resizing in order not to excess 1500 px. Then i use a canvas zoom programmed like this (another canvas where i zoom on the mouse position):

var x1, wdth1, psx1, wdth2, y1, heg1, psy1, heg2;
function drawZoom(x, y) {
    $('#zoom').css({
        'left': x - (parseInt($('#zoom').css('width')) / 2),
        'top': y - (parseInt($('#zoom').css('height')) / 2)
    });
    // console.log([x,y]);
    $('#zoom').show(function () {
        if (x < 25) {
            x1 = 0;
            wdth1 = (x + zoom_level / 2) * ratio;
            psx1 = (25 - x) * 2;
            wdth2 = 100 - psx1;
        } else if (x > width_canvas - zoom_level/ 2) {
            x1 = (x - zoom_level/ 2) * ratio;
            wdth1 = (width_canvas - x + zoom_level/ 2) * ratio;
            psx1 = 0;
            wdth2 = 100 - 2 * (x + zoom_level/ 2 - width_canvas);
        } else {
            x1 = (x - zoom_level/ 2) * ratio;
            wdth1 = zoom_level* ratio;
            psx1 = 0;
            wdth2 = 100;
        }
        if (y < 25) {
            y1 = 0;
            heg1 = (y + zoom_level/ 2) * ratio;
            psy1 = (25 - y) * 2;
            heg2 = 100 - psy1;
        } else if (y >= height_canvas - zoom_level/ 2) {
            y1 = (y - zoom_level/ 2) * ratio;
            heg1 = (height_canvas - y + zoom_level/ 2) * ratio - 1;
            psy1 = 0;
            heg2 = 100 - 2 * (y + zoom_level/ 2 - height_canvas);
        } else {
            y1 = (y - zoom_level/ 2) * ratio;
            heg1 = zoom_level* ratio;
            psy1 = 0;
            heg2 = 100;
        }
        // console.log(heg1);
        zoomctx.fillStyle = "black";
        zoomctx.fillRect(0, 0, 100, 100);
        zoomctx.drawImage(canvas, x1, y1, wdth1, heg1, psx1, psy1, wdth2, heg2);
    });
    zoomctx.beginPath();
    zoomctx.moveTo(0, 50);
    zoomctx.lineTo(100, 50);
    zoomctx.moveTo(50, 0);
    zoomctx.lineTo(50, 100);
    zoomctx.closePath();
    zoomctx.stroke();
}

then i save the positions of the click and use them in order to calculate a distance etc.... (another story)
so i have a reset button, when you start clicking and fail one of the 4 click needed you can restart, it deletes all the points and restarts the fonction.

ISSUES :

-Chrome: works like a charm, no problem, nice zoom, smooth navigation, restart works perfectly etc....

-Firefox: i have a black circle on the left top corner (it's the zoom but it's all black, not working), it doesn't move, i can click and restart but i can't see where i click and the process after clicking doesn't work.

-Safari: the image appears well, the zoom is ok when i first load the image, i can click 4 times and the rest of the program works fine but if i restart then the zoom is like shifted when i put my mouse somewhere and the zoom doesn't show me the right place.

so i have no issue on chrome, and 2 different issues on safari and mozilla firefox, no error in the console.

i'm a beginner so i dont know if the is some constraints as the "webkit" in CSS for JS.

Tell me if you need more info ! Thanks !


问:
How can I add notification timer like whatsapp call notification?
I have a notification builder. I want to add notification timer like whatsapp call notification. So if I call updateNotifTime function, is not working.

```<code>NotificationCompat.Builder builder = new NotificationCompat.Builder(context, callChannelId)
                .setSmallIcon(R.drawable.call_icon)
                .setContentIntent(pendingIntent)
                .setOngoing(true)
                .setShowWhen(true)
                .setWhen(System.currentTimeMillis())
                .setPriority(NotificationCompat.PRIORITY_HIGH);

public void updateNotifTime() {
    this.callingElapsedRunnable = new Runnable() {
                @Override
                public void run() {

                    elapsedTime += 1000;

                    String timer = DateUtils.calculateTime(elapsedTime);

                    builder.setWhen(elapsedTime);

                    callingElapsedHandler.postDelayed(this, 1000);
                }
            };

callingElapsedHandler.postDelayed(callingElapsedRunnable, 1000);
    }
</code>```

答:
```<code>private void sendNotification(String from, String messageText) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(from)
            .setContentText(messageText)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, notificationBuilder.build());
}
</code>```

Body:
I have a notification builder. I want to add notification timer like whatsapp call notification. So if I call updateNotifTime function, is not working.

NotificationCompat.Builder builder = new NotificationCompat.Builder(context, callChannelId)
                .setSmallIcon(R.drawable.call_icon)
                .setContentIntent(pendingIntent)
                .setOngoing(true)
                .setShowWhen(true)
                .setWhen(System.currentTimeMillis())
                .setPriority(NotificationCompat.PRIORITY_HIGH);

public void updateNotifTime() {
    this.callingElapsedRunnable = new Runnable() {
                @Override
                public void run() {

                    elapsedTime += 1000;

                    String timer = DateUtils.calculateTime(elapsedTime);

                    builder.setWhen(elapsedTime);

                    callingElapsedHandler.postDelayed(this, 1000);
                }
            };

callingElapsedHandler.postDelayed(callingElapsedRunnable, 1000);
    }


问:
How can I access a property of an html element?
I'm trying to get the "validacion" property of an HTML element.

```<code>console.log (element[0]);
</code>```

This returns me:

```<code><input class="estilo_input_text ng-pristine ng-untouched ng-valid ng-empty" id="asunto" name="asunto" ng-model="asunto" placeholder="Asunto" type="text" validacion="required">
</code>```

How can I access the "validacion" property?

答:
You can simply do with getAttribute:

```<code>console.log(element[0].getAttribute("validacion"));
</code>```

Body:
I'm trying to get the "validacion" property of an HTML element.

console.log (element[0]);

This returns me:

<input class="estilo_input_text ng-pristine ng-untouched ng-valid ng-empty" id="asunto" name="asunto" ng-model="asunto" placeholder="Asunto" type="text" validacion="required">

How can I access the "validacion" property?

Body:
You can simply do with getAttribute:

console.log(element[0].getAttribute("validacion"));


问:
How to get the all booking list from bookeo api?
I am new to the bookeo booking API and I do not understand how I can get the booking list using php ..

https://www.bookeo.com/apiref/index.html#!/Bookings/bookings_get

答:
```<code>1.The simplest way to launch a request is use the function: file_get_contents. But it only works for GET method.

2.Otherwise,you can use the curl library which is very powerful.

```
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, "API URL");
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($ch, CURLOPT_HEADER, 0);
   $output = curl_exec($ch);
   curl_close($ch);
   print_r($output);
```

The more detail usage you can google it.
</code>```


问:
Laravel 5.4 Authentication
Im trying to create login form and its controller but when i try to login it doesnt work can any one help me i'm very new in laravel.

here is my form

```<code><form action="/login" method="post">
        {{ csrf_field() }}

        <div class="form-group has-feedback">
            <input type="email" name="email" class="form-control" placeholder="Email">
            <span class="glyphicon glyphicon-envelope form-control-feedback"></span>
        </div>
        <div class="form-group has-feedback">
            <input type="password" name="password" class="form-control" placeholder="Password">
            <span class="glyphicon glyphicon-lock form-control-feedback"></span>
        </div>
        <div class="row">
            <div class="col-xs-7">
                <div class="checkbox">
                    <label>
                        <input type="checkbox"> Remember Me
                    </label>
                </div>
            </div>
            <!-- /.col -->
            <div class="col-xs-5">
                <button type="submit" class="btn btn-primary btn-raised btn-block ">Sign In</button>
            </div>
            <!-- /.col -->
        </div>
    </form>
</code>```

and here is my route

```<code>Route::get('/login', 'loginController@create');
Route::post('/login', 'loginController@store');
</code>```

and my loginController is

```<code>class loginController extends Controller
{
    public function __construct(){
        $this->middleware('guest', ['except' => 'destroy']);
    }

   public function create(){

       return view('pages.admin.login');
   }

    public function store(){

       if(! auth()->attempt(request(['email', 'password']))){
            return back()->withErrors([
                'message' => 'Please check your credentials'
            ]);
        }

        return redirect('/home');
    }

}
</code>```

My user modal is

```<code>    class User extends Authenticatable
{
    use Notifiable;

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

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}
</code>```

Please where i'm i doing wrong on these, when i entered email and password as my credential it just refresh and back to login page

答:
You can use php artisan make:auth and laravel will produce everything needed for a login including the controller and then you can go into your resource and edit to make it look how you imagined. </p>

<p>This is what my login controller looks like after using php artisan make:auth </p>

```<code><?php

namespace App\Http\Controllers\Auth;

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

class LoginController extends Controller
{

    use AuthenticatesUsers;

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

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

Title: Laravel 5.4 Authentication

Body:
Im trying to create login form and its controller but when i try to login it doesnt work can any one help me i'm very new in laravel.

here is my form

<form action="/login" method="post">
        {{ csrf_field() }}

            <input type="email" name="email" class="form-control" placeholder="Email">

            <input type="password" name="password" class="form-control" placeholder="Password">

                        <input type="checkbox"> Remember Me

                <button type="submit" class="btn btn-primary btn-raised btn-block ">Sign In</button>

    </form>

and here is my route

Route::get('/login', 'loginController@create');
Route::post('/login', 'loginController@store');

and my loginController is

class loginController extends Controller
{
    public function __construct(){
        $this->middleware('guest', ['except' => 'destroy']);
    }

   public function create(){

       return view('pages.admin.login');
   }

    public function store(){

       if(! auth()->attempt(request(['email', 'password']))){
            return back()->withErrors([
                'message' => 'Please check your credentials'
            ]);
        }

        return redirect('/home');
    }

}

My user modal is

    class User extends Authenticatable
{
    use Notifiable;

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

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

Please where i'm i doing wrong on these, when i entered email and password as my credential it just refresh and back to login page

Body:
You can use php artisan make:auth and laravel will produce everything needed for a login including the controller and then you can go into your resource and edit to make it look how you imagined.

This is what my login controller looks like after using php artisan make:auth

<?php

namespace App\Http\Controllers\Auth;

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

class LoginController extends Controller
{

    use AuthenticatesUsers;

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

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


问:
Android - Bluetooth device connected broadcast
I want to have a broadcast receiver listening for BT devices connecting.
Could anybody tell me which broadcast I have to listen to?
I tried android.bluetooth.device.action.ACL_CONNECTED but it doesn't seem to work.

Thank you.

答:
You can pull the device by using the following inside your BroadcastReceiver.onReceive() function:

```<code>BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
</code>```

Body:
You can pull the device by using the following inside your BroadcastReceiver.onReceive() function:

BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);


问:
CSV not importing to django models
I'm trying to create a django web app that uses data from CSV's. I've created a django model to house the data from these csv's, I've stored all the csv's in STATIC_ROOT. When I load the page, the called template (datalandingpage.html) loads with no problem. However, when I check django admin, none of the CSVs have been imported. If I were to guess, I think the shortcoming has something to do with django not being able to find the files (though I'm just guessing, I could very well be wrong since I'm a relatively new developer). Below is all the relevant code I've written as an attempt.

Edit: So it looks like my view function may be skipping straight to the render part, which may be why I don't see any errors when it runs. Any ideas as to why this may be the case?

settings.py:

```<code># Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/data')
</code>```

models.py:

```<code>from __future__ import unicode_literals
from django.db import models
from django.contrib import admin

class Data(models.Model):
     # A bunch of model objects (CharField/IntegerFields mainly)

    class Meta:
        verbose_name_plural = 'Data Sets'

    def __str__(self):
        return self.someobject
</code>```

views.py:

```<code>from __future__ import unicode_literals
from django.conf import settings
from django.shortcuts import render, render_to_response
from django.template import RequestContext
from .models import Data
import csv
import os

def landing(request):

# Opens all csv files in specified directory
directory = os.path.join(settings.STATIC_ROOT)
for files in os.walk(directory):
    for file in files:
        if file.endswith(".csv"):
            f = open(file, 'r')
            reader = csv.reader(f)

            #Checks the rows/columns and tries to find the specified string that marks the start of data
            for i, row in enumerate(reader):
                target_string = "Some string in the CSV"
                if target_string in row:
                    target_row = i
                    return target_row
                    break

            #Checks the rows/columns and tries to find the specified string that marks the end of data
            for j, row in enumerate(reader):
                end_target_string = "Another string in the CSV"
                if end_target_string in row:
                    end_target_row = j
                    return end_target_row
                    break

            #Begins parsing the csv, but skips until two rows past the target beginning string
            for k, row in enumerate(reader):

                #imports csv data when the row number is between target string and target end string
                if k >= (target_row + 2):
                    row = row.split(',')
                    DataSource = Data.objects.create()
                    DataSource.someobject1 = row[0]
                    DataSource.someobject2 = row[1]
                    DataSource.save()

                # When the parse gets to the row with the end string, it closes the file.
                elif k >= end_target_row:
                    reader.close()
                    break

        # Prints something if the file isn't a csv file
        else:
            print "This isn't a csv file"

return render(request, "Data/datalandingpage.html")
</code>```

答:
You have an issue with how you're looping over the directories and opening the files. os.walk yields for each directory walked a tuple of (root_dir, directories, files) where directories is a tuple of directory names that are found in root_dir and files is a tuple of file names found in root_dir

In your code you have the following:

```<code>for files in os.walk(directory):
    for file in files:
        if file.endswith(".csv"):
            f = open(file, 'r')
            reader = csv.reader(f)
</code>```

This would not do what you probably think it does and will undoubtedly result in an AttributeError because files in for files in os.walk(...) will always have two tuples in it and tuples do not have a .endswith method.

Furthermore, when you correctly loop over files provided by os.walk -- they are just file names. You have to join the path with the root directory.

To fix, you should modify this as follows....

```<code>for root, dirs, files in os.walk(directory):
    for filename in files:
        if filename.endswith(".csv"):
            file_path = os.path.join(root, filename)
            with open(file_path) as f:
                reader = csv.reader(f)
</code>```

Notice that this unpacks the tuples yielded by os.walk into root, dirs, files now files is actually a list of file names. Additionally, os.path.join(root, filename) is used to create the full path to the file from the name.

Also note I modified this to use the with open(...) context manager. Code under this block executes with the file opened and once the block ends the file will be closed for you.

Title: CSV not importing to django models

Body:
I'm trying to create a django web app that uses data from CSV's. I've created a django model to house the data from these csv's, I've stored all the csv's in STATIC_ROOT. When I load the page, the called template (datalandingpage.html) loads with no problem. However, when I check django admin, none of the CSVs have been imported. If I were to guess, I think the shortcoming has something to do with django not being able to find the files (though I'm just guessing, I could very well be wrong since I'm a relatively new developer). Below is all the relevant code I've written as an attempt.

Edit: So it looks like my view function may be skipping straight to the render part, which may be why I don't see any errors when it runs. Any ideas as to why this may be the case?

settings.py:

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/data')

models.py:

from __future__ import unicode_literals
from django.db import models
from django.contrib import admin

class Data(models.Model):
     # A bunch of model objects (CharField/IntegerFields mainly)

    class Meta:
        verbose_name_plural = 'Data Sets'

    def __str__(self):
        return self.someobject

views.py:

from __future__ import unicode_literals
from django.conf import settings
from django.shortcuts import render, render_to_response
from django.template import RequestContext
from .models import Data
import csv
import os

def landing(request):

# Opens all csv files in specified directory
directory = os.path.join(settings.STATIC_ROOT)
for files in os.walk(directory):
    for file in files:
        if file.endswith(".csv"):
            f = open(file, 'r')
            reader = csv.reader(f)

            #Checks the rows/columns and tries to find the specified string that marks the start of data
            for i, row in enumerate(reader):
                target_string = "Some string in the CSV"
                if target_string in row:
                    target_row = i
                    return target_row
                    break

            #Checks the rows/columns and tries to find the specified string that marks the end of data
            for j, row in enumerate(reader):
                end_target_string = "Another string in the CSV"
                if end_target_string in row:
                    end_target_row = j
                    return end_target_row
                    break

            #Begins parsing the csv, but skips until two rows past the target beginning string
            for k, row in enumerate(reader):

                #imports csv data when the row number is between target string and target end string
                if k >= (target_row + 2):
                    row = row.split(',')
                    DataSource = Data.objects.create()
                    DataSource.someobject1 = row[0]
                    DataSource.someobject2 = row[1]
                    DataSource.save()

                # When the parse gets to the row with the end string, it closes the file.
                elif k >= end_target_row:
                    reader.close()
                    break

        # Prints something if the file isn't a csv file
        else:
            print "This isn't a csv file"

return render(request, "Data/datalandingpage.html")

Body:
You have an issue with how you're looping over the directories and opening the files. os.walk yields for each directory walked a tuple of (root_dir, directories, files) where directories is a tuple of directory names that are found in root_dir and files is a tuple of file names found in root_dir

In your code you have the following:

for files in os.walk(directory):
    for file in files:
        if file.endswith(".csv"):
            f = open(file, 'r')
            reader = csv.reader(f)

This would not do what you probably think it does and will undoubtedly result in an AttributeError because files in for files in os.walk(...) will always have two tuples in it and tuples do not have a .endswith method.

Furthermore, when you correctly loop over files provided by os.walk -- they are just file names. You have to join the path with the root directory.

To fix, you should modify this as follows....

for root, dirs, files in os.walk(directory):
    for filename in files:
        if filename.endswith(".csv"):
            file_path = os.path.join(root, filename)
            with open(file_path) as f:
                reader = csv.reader(f)

Notice that this unpacks the tuples yielded by os.walk into root, dirs, files now files is actually a list of file names. Additionally, os.path.join(root, filename) is used to create the full path to the file from the name.

Also note I modified this to use the with open(...) context manager. Code under this block executes with the file opened and once the block ends the file will be closed for you.