问:
gdb weird backtrace , no function name, only?
Our program is only writen by C,  compiled with flags -g -O2 -Wall

The program sometimes crash, we got some crash info, but there is no
function name, only some '??' marks, we couldn't know where was the
error happen.

we catch sight of "Program terminated with signal SIGSEGV", but it's
can not tell we about where the error happen.

our system is  Ubuntu 16.04.3 LTS (GNU/Linux 4.4.0-98-generic x86_64)

```<code>gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.5)
</code>```

there is the crash info:

```<code> sudo gdb test core.31137
[sudo] password for dbsj:
GNU gdb (Ubuntu 7.11.1-0ubuntu1~16.5) 7.11.1
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from test...(no debugging symbols found)...done.

 warning: core file may not match specified executable file.
[New LWP 31147]
[New LWP 31149]
[New LWP 31142]
[New LWP 31137]
[New LWP 31141]
[New LWP 31148]
[New LWP 31143]
[New LWP 31139]
[New LWP 31145]
[New LWP 31144]
[New LWP 31146]
[New LWP 31140]
Core was generated by `./skynet dreamgame/config_publish/dataserver_patched'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0  0x000000000044a0f3 in ?? ()
[Current thread is 1 (LWP 31147)]
(gdb) where
#0  0x000000000044a0f3 in ?? ()
#1  0x0000000000001000 in ?? ()
#2  0x00007f4dcdd0f300 in ?? ()
#3  0x000000000044df5f in ?? ()
#4  0x00007f4dfbad8001 in ?? ()
#5  0x00007f4dd63d5140 in ?? ()
#6  0x00007f4dd63d50c0 in ?? ()
#7  0x00007f4dbc34f180 in ?? ()
#8  0x0000000000000001 in ?? ()
#9  0x00007f4dcdd12058 in ?? ()
#10 0x00007f4dd63d65d0 in ?? ()
#11 0x0000000000002000 in ?? ()
#12 0x0000000000000001 in ?? ()
#13 0x000000000044e026 in ?? ()
#14 0x0000000000001000 in ?? ()
#15 0x0000000000001000 in ?? ()
#16 0x00007f4dd63d50c0 in ?? ()
#17 0x00007f4dbbf0db40 in ?? ()
#18 0x0000000100000001 in ?? ()
#19 0x00007f4dcdd12058 in ?? ()
#20 0x00007f4dd63d65d0 in ?? ()
#21 0x00007f4dcdd0f310 in ?? ()
#22 0x00007f4dcdd0f300 in ?? ()
#23 0x00007f4dd63d6580 in ?? ()
#24 0x00007f4dd63d50c0 in ?? ()
#25 0x00007f4dbc1b0300 in ?? ()
#26 0x0000000000000040 in ?? ()
#27 0x000000000044e963 in ?? ()
#28 0x0000000000004000 in ?? ()
#29 0x0000000000000000 in ?? ()
</code>```

答:
You are probably trying to debug core dump from wrong binary.

Note these lines in output:

```<code>Reading symbols from test...(no debugging symbols found)...done.

 warning: core file may not match specified executable file.
[New LWP 31147]
[New LWP 31149]
[New LWP 31142]
[New LWP 31137]
[New LWP 31141]
[New LWP 31148]
[New LWP 31143]
[New LWP 31139]
[New LWP 31145]
[New LWP 31144]
[New LWP 31146]
[New LWP 31140]
Core was generated by `./skynet dreamgame/config_publish/dataserver_patched'.
</code>```

Try ./skynet dreamgame/config_publish/dataserver_patched instead of test:

```<code>sudo gdb ./skynet dreamgame/config_publish/dataserver_patched core.31137
</code>```

Body:
Our program is only writen by C,  compiled with flags -g -O2 -Wall

The program sometimes crash, we got some crash info, but there is no
function name, only some '??' marks, we couldn't know where was the
error happen.

we catch sight of "Program terminated with signal SIGSEGV", but it's
can not tell we about where the error happen.

our system is  Ubuntu 16.04.3 LTS (GNU/Linux 4.4.0-98-generic x86_64)

gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.5)

there is the crash info:

 sudo gdb test core.31137
[sudo] password for dbsj:
GNU gdb (Ubuntu 7.11.1-0ubuntu1~16.5) 7.11.1
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from test...(no debugging symbols found)...done.

 warning: core file may not match specified executable file.
[New LWP 31147]
[New LWP 31149]
[New LWP 31142]
[New LWP 31137]
[New LWP 31141]
[New LWP 31148]
[New LWP 31143]
[New LWP 31139]
[New LWP 31145]
[New LWP 31144]
[New LWP 31146]
[New LWP 31140]
Core was generated by `./skynet dreamgame/config_publish/dataserver_patched'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0  0x000000000044a0f3 in ?? ()
[Current thread is 1 (LWP 31147)]
(gdb) where
#0  0x000000000044a0f3 in ?? ()
#1  0x0000000000001000 in ?? ()
#2  0x00007f4dcdd0f300 in ?? ()
#3  0x000000000044df5f in ?? ()
#4  0x00007f4dfbad8001 in ?? ()
#5  0x00007f4dd63d5140 in ?? ()
#6  0x00007f4dd63d50c0 in ?? ()
#7  0x00007f4dbc34f180 in ?? ()
#8  0x0000000000000001 in ?? ()
#9  0x00007f4dcdd12058 in ?? ()
#10 0x00007f4dd63d65d0 in ?? ()
#11 0x0000000000002000 in ?? ()
#12 0x0000000000000001 in ?? ()
#13 0x000000000044e026 in ?? ()
#14 0x0000000000001000 in ?? ()
#15 0x0000000000001000 in ?? ()
#16 0x00007f4dd63d50c0 in ?? ()
#17 0x00007f4dbbf0db40 in ?? ()
#18 0x0000000100000001 in ?? ()
#19 0x00007f4dcdd12058 in ?? ()
#20 0x00007f4dd63d65d0 in ?? ()
#21 0x00007f4dcdd0f310 in ?? ()
#22 0x00007f4dcdd0f300 in ?? ()
#23 0x00007f4dd63d6580 in ?? ()
#24 0x00007f4dd63d50c0 in ?? ()
#25 0x00007f4dbc1b0300 in ?? ()
#26 0x0000000000000040 in ?? ()
#27 0x000000000044e963 in ?? ()
#28 0x0000000000004000 in ?? ()
#29 0x0000000000000000 in ?? ()

Body:
You are probably trying to debug core dump from wrong binary.

Note these lines in output:

Reading symbols from test...(no debugging symbols found)...done.

 warning: core file may not match specified executable file.
[New LWP 31147]
[New LWP 31149]
[New LWP 31142]
[New LWP 31137]
[New LWP 31141]
[New LWP 31148]
[New LWP 31143]
[New LWP 31139]
[New LWP 31145]
[New LWP 31144]
[New LWP 31146]
[New LWP 31140]
Core was generated by `./skynet dreamgame/config_publish/dataserver_patched'.

Try ./skynet dreamgame/config_publish/dataserver_patched instead of test:

sudo gdb ./skynet dreamgame/config_publish/dataserver_patched core.31137


来源: stackexchange

问:
Can Google+ API make posts?
Google+ API provides read-only access to public data for long time. Can Google+ developers inform us whether they are going to give access to make posts using API? I need to post some images with text from my website using API. I have been waiting for this for long time please.</p>

答:
You can make it used google + domain api https://developers.google.com/+/domains/ .
But you must have domain.

You can use https://github.com/google/google-api-php-client this help you post.

ContentLicense: CC BY-SA 3.0

Title: Can Google+ API make posts?


问:
Python difficulty running functions in parallel
I am currently Using python 2.6 and am attempting to run another python script multiple times with different input, and whatever attempts I do to run it in the background, it seems that the script waits for the process to complete, before moving on to the next line. I have tried using

subprocess.Popen(Some.Func(Args))

and

T1 = threading.Thread(Some.Func(Args))
 T1.start()

I would like to be able to run through multiple calls to Some class without waiting on any particular one to finish.

答:
You are not passing the arguments to your classes correctly. You want to use multiprocessing.Process or threading.Thread. Specify your target and args separately from each other. The following example demonstrates running ten processes in parallel followed by ten threads in parallel:

```<code>#! /usr/bin/env python3
import multiprocessing
import threading

def main():
    for executor in multiprocessing.Process, threading.Thread:
        engines = []
        for _ in range(10):
            runner = executor(target=for_loop, args=(0, 10000000, 1))
            runner.start()
            engines.append(runner)
        for runner in engines:
            runner.join()

def for_loop(start, stop, step):
    accumulator = start
    while accumulator < stop:
        accumulator += step

if __name__ == '__main__':
    main()
</code>```

Body:
You are not passing the arguments to your classes correctly. You want to use multiprocessing.Process or threading.Thread. Specify your target and args separately from each other. The following example demonstrates running ten processes in parallel followed by ten threads in parallel:

#! /usr/bin/env python3
import multiprocessing
import threading

def main():
    for executor in multiprocessing.Process, threading.Thread:
        engines = []
        for _ in range(10):
            runner = executor(target=for_loop, args=(0, 10000000, 1))
            runner.start()
            engines.append(runner)
        for runner in engines:
            runner.join()

def for_loop(start, stop, step):
    accumulator = start
    while accumulator < stop:
        accumulator += step

if __name__ == '__main__':
    main()


问:
why my data is add in two tables instead of one table in Asp.net mvc
I have two classes they are name Good and Category.but I have a so weird problem . in fact, when I submit my form to controller for adding good entity.one record add in good and one record add in category but i don't want to add any data in category. my controller get three argument good entity and HttpPostedFileBase file, IEnumerable<HttpPostedFileBase> files

```<code>  public class Good
    {
        public Good()
        {
            Images = new List<ImageList>();
            Category = new Category();
        }

        [Key]
        public int ProductId { get; set; }
        [Display(Name = "نام کالا")]
        public string Name { get; set; }
        [Display(Name = "نام تصویر")]
        public string ImageName { get; set; }
        public string LargeImageName { get; set; }
        [Display(Name = "نام لاتین")]
        public string EnglishName { get; set; }
        [Display(Name = "قیمت")]
        public string Price { get; set; }
        [AllowHtml]
        [Display(Name = "توضیح مختصر")]
        public string ShortDescription { get; set; }

        [Display(Name = "کلمات کلیدی")]
        public string Keyword { get; set; }
        [Display(Name = "تعداد بازدید")]
        public int PageVisit { get; set; }
        [Display(Name = "وضعیت")]
        public Boolean Status { get; set; }
        //Fk

        public int CategoryId { get; set; }
        [ForeignKey("CategoryId")]
        public Category Category { get; set; }

        public virtual ICollection<ImageList> Images { get; set; }

    }
</code>```

===============

```<code>public class Category
    {
        [Key]
        public int Id { get; set; }
        [Display(Name = "نام مجموعه")]
        public string CategoryName { get; set; }
        [Display(Name = "نام انگلیسی مجموعه")]
        public string EnglishName { get; set; }

        //navigation
        public virtual ICollection<Good> Good { get; set; }

    }
</code>```

=============================

```<code>  [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ProductId,Name,ImageName,LargeImageName,EnglishName,Price,ShortDescription,Keyword,PageVisit,Status,CategoryId")] Good good, HttpPostedFileBase file, IEnumerable<HttpPostedFileBase> files)
    {

        if (ModelState.IsValid)
        {
            if (file != null)
            {
                if (file.ContentLength > 0)
                {
                    var versions = new Dictionary<string, string>();
                    var checkSizeImage = ImageBuilder.Current.LoadImageInfo(file, null);
                    var setting = new ResizeSettings
                    {
                        MaxWidth = 600,
                        MaxHeight = 300,
                        Format = "jpg,png"
                    };

                    var path = Server.MapPath("/UploadFiles/Images/GoodGallery/");
                    versions.Add("_small", "maxwidth=270&maxheight=180&format=jpg");
                    versions.Add("_large", "maxwidth=600&maxheight=400&format=jpg");

                    foreach (var suffix in versions.Keys)
                    {
                        file.InputStream.Seek(0, System.IO.SeekOrigin.Begin);
                        ImageBuilder.Current.Build(new ImageJob(file.InputStream, path + file.FileName + suffix, new Instructions(versions[suffix]), false, true));
                    }

                    //good. = DateTime.Now.ToString();
                    var dotPosition = file.FileName.IndexOf('.');
                    var largeFileName = file.FileName.Insert(dotPosition, ".jpg_large");
                    var fileName = file.FileName.Insert(dotPosition, ".jpg_small");
                    good.LargeImageName = largeFileName;
                    good.ImageName = fileName;

                }
            }
            else
            {
                good.LargeImageName = "No_Image.png";
                good.ImageName = "No_Image.png";
            }
            if (files != null)
            {
                foreach (var file2 in files)
                {
                    if (file2 != null && file2.ContentLength > 0)
                    {
                        var versions = new Dictionary<string, string>();

                        var path = Server.MapPath("/UploadFiles/Images/GoodGallery/");
                        versions.Add("_small", "maxwidth=270&maxheight=180&format=jpg");
                        versions.Add("_large", "maxwidth=600&maxheight=400&format=jpg");
                        foreach (var suffix in versions.Keys)
                        {
                            file2.InputStream.Seek(0, System.IO.SeekOrigin.Begin);
                            ImageBuilder.Current.Build(new ImageJob(file2.InputStream, path + file2.FileName + suffix, new Instructions(versions[suffix]), false, true));
                        }

                        var dotPosition = file2.FileName.IndexOf('.');
                        var largeFileName = file2.FileName.Insert(dotPosition, ".jpg_large");
                        var smallfileName = file2.FileName.Insert(dotPosition, ".jpg_small");
                        good.Images.Add(new ImageList { LargeImageName = largeFileName, SmallImageName = smallfileName });

                    }
                }
            }
            else
            {
                good.Images.Add(new ImageList { LargeImageName = "No_Image.png", SmallImageName = "No_Image.png" });
            }
            ViewBag.Message = "فایل با موفقیت آپلود شد.";
        }

        db.Goods.Add(good);
        db.SaveChanges();

        ViewBag.CategoryId = new SelectList(db.Categories, "Id", "CategoryName", good.CategoryId);
        return View(good);

    }
</code>```

答: This is because you have Category = new Category(); in your Good class constructor.

Body:
I have two classes they are name Good and Category.but I have a so weird problem . in fact, when I submit my form to controller for adding good entity.one record add in good and one record add in category but i don't want to add any data in category. my controller get three argument good entity and HttpPostedFileBase file, IEnumerable<HttpPostedFileBase> files

  public class Good
    {
        public Good()
        {
            Images = new List<ImageList>();
            Category = new Category();
        }

        [Key]
        public int ProductId { get; set; }
        [Display(Name = "نام کالا")]
        public string Name { get; set; }
        [Display(Name = "نام تصویر")]
        public string ImageName { get; set; }
        public string LargeImageName { get; set; }
        [Display(Name = "نام لاتین")]
        public string EnglishName { get; set; }
        [Display(Name = "قیمت")]
        public string Price { get; set; }
        [AllowHtml]
        [Display(Name = "توضیح مختصر")]
        public string ShortDescription { get; set; }

        [Display(Name = "کلمات کلیدی")]
        public string Keyword { get; set; }
        [Display(Name = "تعداد بازدید")]
        public int PageVisit { get; set; }
        [Display(Name = "وضعیت")]
        public Boolean Status { get; set; }
        //Fk

        public int CategoryId { get; set; }
        [ForeignKey("CategoryId")]
        public Category Category { get; set; }

        public virtual ICollection<ImageList> Images { get; set; }

    }

===============

public class Category
    {
        [Key]
        public int Id { get; set; }
        [Display(Name = "نام مجموعه")]
        public string CategoryName { get; set; }
        [Display(Name = "نام انگلیسی مجموعه")]
        public string EnglishName { get; set; }

        //navigation
        public virtual ICollection<Good> Good { get; set; }

    }

=============================

  [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ProductId,Name,ImageName,LargeImageName,EnglishName,Price,ShortDescription,Keyword,PageVisit,Status,CategoryId")] Good good, HttpPostedFileBase file, IEnumerable<HttpPostedFileBase> files)
    {

        if (ModelState.IsValid)
        {
            if (file != null)
            {
                if (file.ContentLength > 0)
                {
                    var versions = new Dictionary<string, string>();
                    var checkSizeImage = ImageBuilder.Current.LoadImageInfo(file, null);
                    var setting = new ResizeSettings
                    {
                        MaxWidth = 600,
                        MaxHeight = 300,
                        Format = "jpg,png"
                    };

                    var path = Server.MapPath("/UploadFiles/Images/GoodGallery/");
                    versions.Add("_small", "maxwidth=270&maxheight=180&format=jpg");
                    versions.Add("_large", "maxwidth=600&maxheight=400&format=jpg");

                    foreach (var suffix in versions.Keys)
                    {
                        file.InputStream.Seek(0, System.IO.SeekOrigin.Begin);
                        ImageBuilder.Current.Build(new ImageJob(file.InputStream, path + file.FileName + suffix, new Instructions(versions[suffix]), false, true));
                    }

                    //good. = DateTime.Now.ToString();
                    var dotPosition = file.FileName.IndexOf('.');
                    var largeFileName = file.FileName.Insert(dotPosition, ".jpg_large");
                    var fileName = file.FileName.Insert(dotPosition, ".jpg_small");
                    good.LargeImageName = largeFileName;
                    good.ImageName = fileName;

                }
            }
            else
            {
                good.LargeImageName = "No_Image.png";
                good.ImageName = "No_Image.png";
            }
            if (files != null)
            {
                foreach (var file2 in files)
                {
                    if (file2 != null && file2.ContentLength > 0)
                    {
                        var versions = new Dictionary<string, string>();

                        var path = Server.MapPath("/UploadFiles/Images/GoodGallery/");
                        versions.Add("_small", "maxwidth=270&maxheight=180&format=jpg");
                        versions.Add("_large", "maxwidth=600&maxheight=400&format=jpg");
                        foreach (var suffix in versions.Keys)
                        {
                            file2.InputStream.Seek(0, System.IO.SeekOrigin.Begin);
                            ImageBuilder.Current.Build(new ImageJob(file2.InputStream, path + file2.FileName + suffix, new Instructions(versions[suffix]), false, true));
                        }

                        var dotPosition = file2.FileName.IndexOf('.');
                        var largeFileName = file2.FileName.Insert(dotPosition, ".jpg_large");
                        var smallfileName = file2.FileName.Insert(dotPosition, ".jpg_small");
                        good.Images.Add(new ImageList { LargeImageName = largeFileName, SmallImageName = smallfileName });

                    }
                }
            }
            else
            {
                good.Images.Add(new ImageList { LargeImageName = "No_Image.png", SmallImageName = "No_Image.png" });
            }
            ViewBag.Message = "فایل با موفقیت آپلود شد.";
        }

        db.Goods.Add(good);
        db.SaveChanges();

        ViewBag.CategoryId = new SelectList(db.Categories, "Id", "CategoryName", good.CategoryId);
        return View(good);

    }


问:
Why arm-linux-gnueabi-gcc and not arm-none-eabi-gcc when compiling Linux kernel and uBoot?
I have some experience compiling bare metal code for ARM cortex-m devices as well as the Linux kernel, uBoot, and applications for the Beaglebone Black (BBB) (more featured ARM with MMU, for those living under a rock). It makes sense to me that the cortex-m code should be compiled using arm-none-eabi-gcc (as there is no OS) and the application code for the BBB should be compiled with arm-linux-gnueabi-gcc (as there is an OS, for which system calls can be made and program loaders and shared objects can be utilized).

What I don't understand is why uBoot and the kernel also should be compiled with arm-linux-gnueabi-gcc. In my mind, uBoot at least, is a bare metal program with no fancy OS to account for. This has been bugging me for sometime, but I can't find an answer. Is there anyone out there that can enlighten me?

答: U-Boot was designed to mirror the Linux design philosophy as much as possible. It uses the same configuration system, general directory structure, etc. It shares some APIs with Linux - see the include/linux directory. As the comments above mention, the ABI compatibility doesn't matter at this point, but using a Linux compiler isn't philosophically inappropriate for U-Boot.</p>

ContentLicense: CC BY-SA 4.0


问:
How to have a one to one, and a many to one, relation ship EF?
Context:

I am working with entity framework core code first approach. The entity framework core is located in .Net core class library.

Situation:

Relations

I have one table named Question and a table named AnswerOption. These tables have relationships like:

A Question has one RightAnswer which is of type AnswerOption

A Question can have more AnswerOptions

A question has multiple answer options and one of them is the right answer.

Code

```<code>public class Question
{
     [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
     public int Id { get; set; }

     public virtual AnswerOption RightAnswerId { get; set; }
     public virtual AnswerOption RightAnswer { get; set; }

     public virtual ICollection<AnswerOption> AnswerOptions { get; set; }
}

public class AnswerOption
{
     [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
     public int Id { get; set; }

     public int QuestionId { get; set; }

     public virtual Question Question { get; set; }
}
</code>```

Question

When the database is created it throws the following error:

'Unable to determine the relationship represented by navigation
  property 'AnswerOption.Question' of type 'Question'. Either manually
  configure the relationship, or ignore this property using the
  '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in
  'OnModelCreating'.'

I have try'ed to set the relation ship manually whit entity framework relationship builder in the OnModelCreating() method of DbContext class but don't exactly know how to get this relationship to work.

How can I declare one to one and many to one  relationships between those tables?

答:
Here's how to do that in EF Core.  AnswerOption should have a compound key for performance, and so you can enforce that the RightAnswer for a question must be one of the AnswerOptions for that question, which requires fluent config in EF Core.  Otherwise you just have to annotate the ForeignKey and InverseProperty, and make RightAnswerId nullable, so you can insert a Question without a RightAnswer.</p>

```<code>using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
//using Microsoft.Samples.EFLogging;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace EFCore2Test
{
    public class Question
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }

        public virtual int? RightAnswerId { get; set; }

        [ForeignKey("Id,RightAnswerId")]
        public virtual AnswerOption RightAnswer { get; set; }

        public virtual ICollection<AnswerOption> AnswerOptions { get; set; }
    }

    public class AnswerOption
    {
        public int QuestionId { get; set; }

        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }

        [InverseProperty("AnswerOptions")]
        public virtual Question Question { get; set; }
    }
    public class Db : DbContext
    {
        public DbSet<Question> Questions { get; set; }
        public DbSet<AnswerOption> AnswerOptions { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<AnswerOption>().HasKey(e => new { e.QuestionId, e.Id });
            base.OnModelCreating(modelBuilder);
        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("Server=(local);Database=Test2;Trusted_Connection=True;MultipleActiveResultSets=true");
            base.OnConfiguring(optionsBuilder);
        }
    }

    class Program
    {

        static void Main(string[] args)
        {
             using (var db = new Db())
            {

                db.Database.EnsureDeleted();
               // db.ConfigureLogging(s => Console.WriteLine(s));
                db.Database.EnsureCreated();
                for (int i = 0; i < 100; i++)
                {
                    var q = new Question();
                    db.Questions.Add(q);

                    var a = new AnswerOption();
                    a.Question = q;
                    var b = new AnswerOption();
                    b.Question = q;
                    db.SaveChanges();

                    q.RightAnswer = a;
                    db.SaveChanges();
                }

            }

            Console.WriteLine("Hit any key to exit");
            Console.ReadKey();
        }
    }
}
</code>```

Body:
Context:

I am working with entity framework core code first approach. The entity framework core is located in .Net core class library.

Situation:

Relations

I have one table named Question and a table named AnswerOption. These tables have relationships like:

A Question has one RightAnswer which is of type AnswerOption

A Question can have more AnswerOptions

A question has multiple answer options and one of them is the right answer.

Code

public class Question
{
     [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
     public int Id { get; set; }

     public virtual AnswerOption RightAnswerId { get; set; }
     public virtual AnswerOption RightAnswer { get; set; }

     public virtual ICollection<AnswerOption> AnswerOptions { get; set; }
}

public class AnswerOption
{
     [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
     public int Id { get; set; }

     public int QuestionId { get; set; }

     public virtual Question Question { get; set; }
}

Question

When the database is created it throws the following error:

'Unable to determine the relationship represented by navigation
  property 'AnswerOption.Question' of type 'Question'. Either manually
  configure the relationship, or ignore this property using the
  '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in
  'OnModelCreating'.'

I have try'ed to set the relation ship manually whit entity framework relationship builder in the OnModelCreating() method of DbContext class but don't exactly know how to get this relationship to work.

How can I declare one to one and many to one  relationships between those tables?

Body:
Here's how to do that in EF Core.  AnswerOption should have a compound key for performance, and so you can enforce that the RightAnswer for a question must be one of the AnswerOptions for that question, which requires fluent config in EF Core.  Otherwise you just have to annotate the ForeignKey and InverseProperty, and make RightAnswerId nullable, so you can insert a Question without a RightAnswer.

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
//using Microsoft.Samples.EFLogging;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace EFCore2Test
{
    public class Question
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }

        public virtual int? RightAnswerId { get; set; }

        [ForeignKey("Id,RightAnswerId")]
        public virtual AnswerOption RightAnswer { get; set; }

        public virtual ICollection<AnswerOption> AnswerOptions { get; set; }
    }

    public class AnswerOption
    {
        public int QuestionId { get; set; }

        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }

        [InverseProperty("AnswerOptions")]
        public virtual Question Question { get; set; }
    }
    public class Db : DbContext
    {
        public DbSet<Question> Questions { get; set; }
        public DbSet<AnswerOption> AnswerOptions { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<AnswerOption>().HasKey(e => new { e.QuestionId, e.Id });
            base.OnModelCreating(modelBuilder);
        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("Server=(local);Database=Test2;Trusted_Connection=True;MultipleActiveResultSets=true");
            base.OnConfiguring(optionsBuilder);
        }
    }

    class Program
    {

        static void Main(string[] args)
        {
             using (var db = new Db())
            {

                db.Database.EnsureDeleted();
               // db.ConfigureLogging(s => Console.WriteLine(s));
                db.Database.EnsureCreated();
                for (int i = 0; i < 100; i++)
                {
                    var q = new Question();
                    db.Questions.Add(q);

                    var a = new AnswerOption();
                    a.Question = q;
                    var b = new AnswerOption();
                    b.Question = q;
                    db.SaveChanges();

                    q.RightAnswer = a;
                    db.SaveChanges();
                }

            }

            Console.WriteLine("Hit any key to exit");
            Console.ReadKey();
        }
    }
}


问:
SQL to show 1 for unique and 0 for reapeat
looking for a quick solution on SQL...

I used to have a clunky formula in excel: =IF(COUNTIF($C$2:C2,C2)>1,0,COUNTIF($C$2:C2,C2)) to print 1 for unique item and 0 for a repeat.

Then moved to =1-(C1-C2) and that kinda did the job... Not an accurate one Now looking for an SQL that could do a similar job... The example below for result needed:

```<code>NUMBER         UNIQUE
6573455300000  1
6573455300000  0
6573455300000  0
6573455300000  0
6573411981080  1
6573411981080  0
6573411981080  0
6573411981080  0
</code>```

Does anyone know any kind of code to achieve this?

答:
```<code>SELECT
 [number],
 case when rown = 1 then 1 else 0 end as [unique]
FROM
(
 SELECT
  [number], row_number() OVER(partition by [number] order by [number]) as rown
 FROM
  t
) a
</code>```

This doesn't strictly have to be done using a subquery but it's unlikely to make any difference to the overall performance, so it's arranged like this to help you see what is going on. If you run just the inner subquery in isolation you'll see that the most important work is done by row_number; essentially the data is partitioned into buckets based on the value of [number] something like a group by, but it doesn't suppress repeated values. Within the partition each occurrence of [number] is numbered with an incrementing counter. When a different value of [number] is encountered the numbering restarts from 1. The order by clause is just there because sql server demands you have one, and we don't know anything else about your table but if there's something else about your data where one of these occurrences would be more ideal to single out to be labelled with [unique]=1, try and find a way to make it so that row is sorted into position 1; a typical use of this pattern is "latest record" in which case the order by part would be [datecolumn] DESC

Once you have an increment of counter per number that resets itself, all we need to do is use a standard case / else statement to make it a 1 when it's 1 otherwise 0 to match your result desired

Body:
looking for a quick solution on SQL...

I used to have a clunky formula in excel: =IF(COUNTIF($C$2:C2,C2)>1,0,COUNTIF($C$2:C2,C2)) to print 1 for unique item and 0 for a repeat.

Then moved to =1-(C1-C2) and that kinda did the job... Not an accurate one Now looking for an SQL that could do a similar job... The example below for result needed:

NUMBER         UNIQUE
6573455300000  1
6573455300000  0
6573455300000  0
6573455300000  0
6573411981080  1
6573411981080  0
6573411981080  0
6573411981080  0

Does anyone know any kind of code to achieve this?

Body:
SELECT
 [number],
 case when rown = 1 then 1 else 0 end as [unique]
FROM
(
 SELECT
  [number], row_number() OVER(partition by [number] order by [number]) as rown
 FROM
  t
) a

This doesn't strictly have to be done using a subquery but it's unlikely to make any difference to the overall performance, so it's arranged like this to help you see what is going on. If you run just the inner subquery in isolation you'll see that the most important work is done by row_number; essentially the data is partitioned into buckets based on the value of [number] something like a group by, but it doesn't suppress repeated values. Within the partition each occurrence of [number] is numbered with an incrementing counter. When a different value of [number] is encountered the numbering restarts from 1. The order by clause is just there because sql server demands you have one, and we don't know anything else about your table but if there's something else about your data where one of these occurrences would be more ideal to single out to be labelled with [unique]=1, try and find a way to make it so that row is sorted into position 1; a typical use of this pattern is "latest record" in which case the order by part would be [datecolumn] DESC

Once you have an increment of counter per number that resets itself, all we need to do is use a standard case / else statement to make it a 1 when it's 1 otherwise 0 to match your result desired


Title: SQL to show 1 for unique and 0 for reapeat

Body:
using row_number():

select
    col
  , [first] = case when row_number() over (partition by col order by (select 1)) > 1 then 0 else 1 end
from t

rextester demo: http://rextester.com/FWA89661

returns:

+---------------+-------+
|      col      | first |
+---------------+-------+
| 6573411981080 |     1 |
| 6573411981080 |     0 |
| 6573411981080 |     0 |
| 6573411981080 |     0 |
| 6573455300000 |     1 |
| 6573455300000 |     0 |
| 6573455300000 |     0 |
| 6573455300000 |     0 |
+---------------+-------+


问:
How can I see what has changed in a file before committing to git?
I've noticed that while working on one or two tickets, if I step away, I'm not sure what I worked on, what changed, etcetera.

Is there a way to see the changes made for a given file before git add and then git commit?

答:
Well, my case when you don't want to care about files list. Just show them all.

When you already ran git add with your files list:

```<code>$ git diff --cached $(git diff --cached --name-only)
</code>```

In more recent versions of git, you can use --staged also, which is a synonym of --cached.

The same can be used for haven't added files but without --cached option.

```<code>$ git diff $(git diff --name-only)
</code>```

Git command alias for "cached" option:

```<code>$ git config --global alias.diff-cached '!git diff --cached $(git diff --cached --name-only)'
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Well, my case when you don't want to care about files list. Just show them all.

When you already ran git add with your files list:

$ git diff --cached $(git diff --cached --name-only)

In more recent versions of git, you can use --staged also, which is a synonym of --cached.

The same can be used for haven't added files but without --cached option.

$ git diff $(git diff --name-only)

Git command alias for "cached" option:

$ git config --global alias.diff-cached '!git diff --cached $(git diff --cached --name-only)'


答:
Use window functions.  In your case, you seem to want the first row and mark that, so row_number() looks like the solution:

```<code>select t.*,
       (case when row_number() over (partition by number order by ?) = 1
             then 1 else 0 end
        end) as flag
from t;
</code>```

The ? is for the column that specifies the ordering (which is first).  If you want just one row but don't care which, then you can use order by number or order by (select null).

UNIQUE is a SQL keyword (think "unique index"), so it is a bad name for a column.  That is why I changed to the generic flag, although you might prefer first_row_flag or something like that.

Body:
Use window functions.  In your case, you seem to want the first row and mark that, so row_number() looks like the solution:

select t.*,
       (case when row_number() over (partition by number order by ?) = 1
             then 1 else 0 end
        end) as flag
from t;

The ? is for the column that specifies the ordering (which is first).  If you want just one row but don't care which, then you can use order by number or order by (select null).

UNIQUE is a SQL keyword (think "unique index"), so it is a bad name for a column.  That is why I changed to the generic flag, although you might prefer first_row_flag or something like that.


问:
Can a debugger produce a list of all executed lines of source code of an attached process?
I'm working for a company, that does not have a habit of adding log entries in their source code.

Hence, if something goes wrong, the amount of logs, explaining what might have happened, is too small to make any real analysis.

Therefore I'm looking for a tool which can do the following:

Attach to a running process and link to the symbols file.

Follow all lines of source code which are executed.

After a certain key is pressed (like "Ctrl+C"), produce a report which looks as follows:

[]

```<code>file1.c:010:  function1(1, 2, 5)
file1.c:011:    sum(1,2)
file1.c:020:      return 3;
file1.c:012:    sum(3,5);
file1.c:020:      return 8;
file1.c:012:    return 8;
</code>```

I can imagine this question sounding very naïve, but if I can have something which just approaches this result, it might be very useful.

Does anybody know if this can be achieved using windbg, cdb, Visual Studio or any other means?

答:
do you have the source code and symbols for your exe
if yes windbg can step and print source lines

demo below for a simple recv sample

start an executable whose pdb with src info is available

```<code>:\>cdb recv

Microsoft (R) Windows Debugger Version 10.0.16299.15 X86
</code>```

windbg breaks on system breakpoint

```<code>ntdll!LdrpDoDebuggerBreak+0x2c:
771a05a6 cc              int     3
</code>```

enable loading of line information
enable stepping in source mode
enable printing of src lines

```<code>0:000> .lines
Line number information will be loaded
0:000> l+t
Source options are 1:
     1/t - Step/trace by source line
0:000> l+s
Source options are 5:
     1/t - Step/trace by source line
     4/s - List source code at prompt
</code>```

disallow all other output except src

```<code>0:000> .prompt_allow -reg -dis -sym -ea
Allow the following information to be displayed at the prompt:
(Other settings can affect whether the information is actually displayed)
   src - Source info for current instruction
Do not allow the following information to be displayed at the prompt:
   sym - Symbol for current instruction
   dis - Disassembly of current instruction
    ea - Effective address for current instruction
   reg - Register state
</code>```

go to main and step 10 times
you will see each step is showing the src

read and use controlling the target in windbg help to know about various
execution methods like step until return , step until branch etc

```<code>0:000> g recv!main
ModLoad: 69f50000 69f53000   C:\Windows\system32\api-ms-win-core-synch-l1-2-0.DLL
>   13: int __cdecl main() {
0:000> p 10
>   24:     iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
>   25:     if (iResult != NO_ERROR) {
>   30:     ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
>   31:     if (ConnectSocket == INVALID_SOCKET) {
>   38:     clientService.sin_family = AF_INET;
>   39:     clientService.sin_addr.s_addr = inet_addr( "127.0.0.1" );
>   40:     clientService.sin_port = htons( 27015 );
>   42:     iResult = connect( ConnectSocket, (SOCKADDR*) &clientService, sizeof(clientService) );
>   43:     if ( iResult == SOCKET_ERROR) {
>   44:         closesocket (ConnectSocket);
>   45:         printf("Unable to connect to server: %ld\n", WSAGetLastError());

Unable to connect to server: 0
>   66:         WSACleanup();
>   67:         return 1;
>   88: }
*** The C++ standard library and CRT step filter can be enabled to skip this fun
ction. Run .settings set Sources.SkipCrtCode = true">.settings set Sources.SkipC
rtCode = true to enable it. ***
</code>```

Body:
I'm working for a company, that does not have a habit of adding log entries in their source code.

Hence, if something goes wrong, the amount of logs, explaining what might have happened, is too small to make any real analysis.

Therefore I'm looking for a tool which can do the following:

Attach to a running process and link to the symbols file.

Follow all lines of source code which are executed.

After a certain key is pressed (like "Ctrl+C"), produce a report which looks as follows:

[]

file1.c:010:  function1(1, 2, 5)
file1.c:011:    sum(1,2)
file1.c:020:      return 3;
file1.c:012:    sum(3,5);
file1.c:020:      return 8;
file1.c:012:    return 8;

I can imagine this question sounding very naïve, but if I can have something which just approaches this result, it might be very useful.

Does anybody know if this can be achieved using windbg, cdb, Visual Studio or any other means?

Body:
do you have the source code and symbols for your exe
if yes windbg can step and print source lines

demo below for a simple recv sample

start an executable whose pdb with src info is available

:\>cdb recv

Microsoft (R) Windows Debugger Version 10.0.16299.15 X86

windbg breaks on system breakpoint

ntdll!LdrpDoDebuggerBreak+0x2c:
771a05a6 cc              int     3

enable loading of line information
enable stepping in source mode
enable printing of src lines

0:000> .lines
Line number information will be loaded
0:000> l+t
Source options are 1:
     1/t - Step/trace by source line
0:000> l+s
Source options are 5:
     1/t - Step/trace by source line
     4/s - List source code at prompt

disallow all other output except src

0:000> .prompt_allow -reg -dis -sym -ea
Allow the following information to be displayed at the prompt:
(Other settings can affect whether the information is actually displayed)
   src - Source info for current instruction
Do not allow the following information to be displayed at the prompt:
   sym - Symbol for current instruction
   dis - Disassembly of current instruction
    ea - Effective address for current instruction
   reg - Register state

go to main and step 10 times
you will see each step is showing the src

read and use controlling the target in windbg help to know about various
execution methods like step until return , step until branch etc

0:000> g recv!main
ModLoad: 69f50000 69f53000   C:\Windows\system32\api-ms-win-core-synch-l1-2-0.DLL
>   13: int __cdecl main() {
0:000> p 10
>   24:     iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
>   25:     if (iResult != NO_ERROR) {
>   30:     ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
>   31:     if (ConnectSocket == INVALID_SOCKET) {
>   38:     clientService.sin_family = AF_INET;
>   39:     clientService.sin_addr.s_addr = inet_addr( "127.0.0.1" );
>   40:     clientService.sin_port = htons( 27015 );
>   42:     iResult = connect( ConnectSocket, (SOCKADDR*) &clientService, sizeof(clientService) );
>   43:     if ( iResult == SOCKET_ERROR) {
>   44:         closesocket (ConnectSocket);
>   45:         printf("Unable to connect to server: %ld\n", WSAGetLastError());

Unable to connect to server: 0
>   66:         WSACleanup();
>   67:         return 1;
>   88: }
*** The C++ standard library and CRT step filter can be enabled to skip this fun
ction. Run .settings set Sources.SkipCrtCode = true">.settings set Sources.SkipC
rtCode = true to enable it. ***


问:
For Loop with If statement onlyreturns first element
I am trying to feed a vector into a function which checks every element and assigns the corresponding element from the list to the proper if statement.

The output should look like this:

10
  11
  17
  40
  370

Somehow I am only receiving the first element

370

and the loop is breaking up.The code looks like the following:

```<code>def dosomething(thelist):
    period_unit = []
    for period in thelist:
        period = period.lower()
        if period[-1:] == "d":
            period_unit = 1
        elif period[-1:] == "m":
            period_unit = 30
        elif period[-1:] == "w":
            period_unit = 7
        elif period[-1:] == "y":
            period_unit = 360
        elif period == "dummy":
            period_object = 0
            return period_object
        else:
            raise Exception("Something went wrong")
        period_object = 10 + period_unit
    return period_object

if __name__ == '__main__':

    date = ["dummy", "1d", "1W", "1M", "1Y"]

    test = dosomething(date )
    print(test)
</code>```

答:
You reassign period_unit everytime.

You want to do something like:

```<code>def dosomething(thelist):
    period_unit = []
    for period in thelist:
        period = period.lower()
        curr_period_unit = None
        if period == "dummy":
            curr_period_unit = 0
        elif period[-1] == "d":
            curr_period_unit = 1
        elif period[-1] == "m":
            curr_period_unit = 30
        elif period[-1] == "w":
            curr_period_unit = 7
        elif period[-1] == "y":
            curr_period_unit = 360
        else:
            raise Exception("Something went wrong")
        period_unit.append(10 + curr_period_unit)
    return period_unit
</code>```

And then it works as expected:

```<code>>>> date = ["dummy", "1d", "1W", "1M", "1Y"]
>>> dosomething(date)
[10, 11, 17, 40, 370]
>>> ' '.join(str(item) for item in dosomething(date))
'10 11 17 40 370'
</code>```

Body:
I am trying to feed a vector into a function which checks every element and assigns the corresponding element from the list to the proper if statement.

The output should look like this:

10
  11
  17
  40
  370

Somehow I am only receiving the first element

370

and the loop is breaking up.The code looks like the following:

def dosomething(thelist):
    period_unit = []
    for period in thelist:
        period = period.lower()
        if period[-1:] == "d":
            period_unit = 1
        elif period[-1:] == "m":
            period_unit = 30
        elif period[-1:] == "w":
            period_unit = 7
        elif period[-1:] == "y":
            period_unit = 360
        elif period == "dummy":
            period_object = 0
            return period_object
        else:
            raise Exception("Something went wrong")
        period_object = 10 + period_unit
    return period_object

if __name__ == '__main__':

    date = ["dummy", "1d", "1W", "1M", "1Y"]

    test = dosomething(date )
    print(test)

Body:
You reassign period_unit everytime.

You want to do something like:

def dosomething(thelist):
    period_unit = []
    for period in thelist:
        period = period.lower()
        curr_period_unit = None
        if period == "dummy":
            curr_period_unit = 0
        elif period[-1] == "d":
            curr_period_unit = 1
        elif period[-1] == "m":
            curr_period_unit = 30
        elif period[-1] == "w":
            curr_period_unit = 7
        elif period[-1] == "y":
            curr_period_unit = 360
        else:
            raise Exception("Something went wrong")
        period_unit.append(10 + curr_period_unit)
    return period_unit

And then it works as expected:

>>> date = ["dummy", "1d", "1W", "1M", "1Y"]
>>> dosomething(date)
[10, 11, 17, 40, 370]
>>> ' '.join(str(item) for item in dosomething(date))
'10 11 17 40 370'


问:
Java Tomcat 8.5 / Spring 4 Removes Multiple Spacing from URL
I'm working on an existing Spring 4 application which sits in a Tomcat (I believe 8.5) container.

The Problem:

When the String controller receives its parameters, any multiple spacing within the URL is removed, but I want it to be included

Example:

```<code>@RequestMapping(value = "/getData/{name}", method = RequestMethod.GET)
</code>```

When this is submitted with /getData/Joe%20Bloggs/, the name variable will be 'Joe Bloggs'

But when submitted with /getData/Joe%20%20%20Bloggs/, the variable remains 'Joe Bloggs'. The multiple spaces are ignored.

Any idea where this functionality is being defined, and whether this is being done by the Tomcat container or the Spring framework?

答:
Modify your requestmapping as below:</p>

```<code>@RequestMapping(value = "/getData/{name:.+}", method = RequestMethod.GET)
</code>```

Body:
I'm working on an existing Spring 4 application which sits in a Tomcat (I believe 8.5) container.

The Problem:

When the String controller receives its parameters, any multiple spacing within the URL is removed, but I want it to be included

Example:

@RequestMapping(value = "/getData/{name}", method = RequestMethod.GET)

When this is submitted with /getData/Joe%20Bloggs/, the name variable will be 'Joe Bloggs'

But when submitted with /getData/Joe%20%20%20Bloggs/, the variable remains 'Joe Bloggs'. The multiple spaces are ignored.

Any idea where this functionality is being defined, and whether this is being done by the Tomcat container or the Spring framework?

Body:
Modify your requestmapping as below:

@RequestMapping(value = "/getData/{name:.+}", method = RequestMethod.GET)


问:
Prevent pwgen -y generating backticks or quotes? (or otherwise sanitize output)
I'm using pwgen in a bash script. For security, we have to use the -y flag to include at least one special character. However, this frequently returns passwords with one or more of ` or " which break the surrounding script.

Can I prevent these characters being generated? If not, what's the cleanest way to remove, replace or otherwise sanitize pwgen's output to exclude these characters?

My current pwgen is;

```<code>intPW=$(pwgen -c -n -y -B -1 15)
</code>```

which means intPW's value could be something like;

```<code>iqui`c:ee4so4Ch
hph7eew"ohr9Ee
</code>```

I need to guarantee that every password has a symbol in it, just not one of the problematic symbols.

Anything I can think of in terms of replacement, from an if loop to a sed, breaks because I'm trying to target a backtick.

答:
If you have pwgen version 2.08, you can use the new option -r to exclude unwanted characters

```<code>pwgen -cnyB1 -r \`\" 15
</code>```

Body:
I'm using pwgen in a bash script. For security, we have to use the -y flag to include at least one special character. However, this frequently returns passwords with one or more of ` or " which break the surrounding script.

Can I prevent these characters being generated? If not, what's the cleanest way to remove, replace or otherwise sanitize pwgen's output to exclude these characters?

My current pwgen is;

intPW=$(pwgen -c -n -y -B -1 15)

which means intPW's value could be something like;

iqui`c:ee4so4Ch
hph7eew"ohr9Ee

I need to guarantee that every password has a symbol in it, just not one of the problematic symbols.

Anything I can think of in terms of replacement, from an if loop to a sed, breaks because I'm trying to target a backtick.

Body:
If you have pwgen version 2.08, you can use the new option -r to exclude unwanted characters

pwgen -cnyB1 -r \`\" 15


问:
Accessing the functions of custom QWidget class using Signals and Slots
I have a MediaView class which inherits QWidget and has GUI components. And i have another class MediaController which handles the changes made on the GUI components.

I need:
to enable buttons when i receive the signal finishedLoadingFile()

So here is a sample how my class looks:

MediaView.cpp

```<code>MediaView::MediaView(QWidget* parent) : QWidget(parent)
{
   m_controller = new MediaController(this);

   m_btnPlay = new QPushButton(m_mediaButtons);
   m_btnPlay->setIcon(QIcon(":/images/play.png"));
   m_btnPlay->setIconSize(QSize(32, 32));
   m_btnPlay->move(100, 10);
   m_btnPlay->resize(39, 38);
   m_btnPlay->setToolTip("Play");

   m_btnPause = new QPushButton(m_mediaButtons);
   m_btnPause->setIcon(QIcon(":/images/pause.png"));
   m_btnPause->setIconSize(QSize(32, 32));
   m_btnPause->move(150, 10);
   m_btnPause->resize(39, 38);
   m_btnPause->setToolTip("Pause");

   m_btnPlay->setEnabled(false);
   m_btnPause->setEnabled(false);

   connect(m_btnOpen, SIGNAL(clicked(bool)), m_controller, SLOT(loadFile()));
   connect(m_btnPlay,SIGNAL(clicked(bool)),m_controller,SLOT(buttonPlayClicked()));
   connect(m_btnPause,SIGNAL(clicked(bool)),m_controller,SLOT(buttonPauseClicked()));
}

void MediaView::enableButtons()
{
   m_btnPlay->setEnabled(true);
   m_btnPause->setEnabled(true);
}
</code>```

MediaController.cpp

```<code>MediaController::MediaController(QWidget* parent) : QWidget(parent)
{
    MediaView* view = new MediaView(this); //loop here
    connect(this, SIGNAL(loadingFileFinished(), view, SLOT(enableButtons()));
}

void MediaController::loadFile()
{
    m_filePath = "";

    m_filePath = QFileDialog::getOpenFileName(this, "Choose a .txt file with paths to gtt streams", QString(),
             QString("text file(*.txt)"));

    if (m_filePath.isEmpty())
    {
        return;
    }

    m_file = "";
    m_file.append(m_filePath.toLocal8Bit().constData());

    emit finishedLoadingFile();
}
</code>```

Issue:

I wish to call the enableButtons() in the MediaView class. But when i instantiate the MediaView class inside MediaController, app crashes because they keep calling each others constructors in a loop. Reason being, they both communicate using signals and slots so i need to instantiate objects of their respective classes.

Alternatives:

I would like to know whether if it is possible to access the widgets from MediaController class so that i can use them there itself?
If not, a better way to communicate between view and controller?

答:
Each MediaView creates a MediaController, and each MediaController creates another MediaView, that generates the infinite loop, the appropriate thing is to create a MediaController in MediaView and make the connections:

```<code>MediaView::MediaView(QWidget* parent) : QWidget(parent)
{
   m_controller = new MediaController(this);
   connect(m_controller, &MediaController::loadingFileFinished, this, &MediaView::enableButtons);
   [...]
}
</code>```

it is not necessary to create a new MediaView within MediaController.

If you want to access MediaView from MediaController you can do it through parent since MediaView is the parent of MediaController:

MediaController.h

```<code>MediaView *view;
</code>```

MediaController.cpp

```<code>MediaController::MediaController(QWidget* parent) : QWidget(parent)
{
    view = qobject_cast<QMediaView *>(parent);
    //or
    // connect(this, &MediaController::loadingFileFinished, view, &MediaView::enableButtons);
}
</code>```

Body:
I have a MediaView class which inherits QWidget and has GUI components. And i have another class MediaController which handles the changes made on the GUI components.

I need:
to enable buttons when i receive the signal finishedLoadingFile()

So here is a sample how my class looks:

MediaView.cpp

MediaView::MediaView(QWidget* parent) : QWidget(parent)
{
   m_controller = new MediaController(this);

   m_btnPlay = new QPushButton(m_mediaButtons);
   m_btnPlay->setIcon(QIcon(":/images/play.png"));
   m_btnPlay->setIconSize(QSize(32, 32));
   m_btnPlay->move(100, 10);
   m_btnPlay->resize(39, 38);
   m_btnPlay->setToolTip("Play");

   m_btnPause = new QPushButton(m_mediaButtons);
   m_btnPause->setIcon(QIcon(":/images/pause.png"));
   m_btnPause->setIconSize(QSize(32, 32));
   m_btnPause->move(150, 10);
   m_btnPause->resize(39, 38);
   m_btnPause->setToolTip("Pause");

   m_btnPlay->setEnabled(false);
   m_btnPause->setEnabled(false);

   connect(m_btnOpen, SIGNAL(clicked(bool)), m_controller, SLOT(loadFile()));
   connect(m_btnPlay,SIGNAL(clicked(bool)),m_controller,SLOT(buttonPlayClicked()));
   connect(m_btnPause,SIGNAL(clicked(bool)),m_controller,SLOT(buttonPauseClicked()));
}

void MediaView::enableButtons()
{
   m_btnPlay->setEnabled(true);
   m_btnPause->setEnabled(true);
}

MediaController.cpp

MediaController::MediaController(QWidget* parent) : QWidget(parent)
{
    MediaView* view = new MediaView(this); //loop here
    connect(this, SIGNAL(loadingFileFinished(), view, SLOT(enableButtons()));
}

void MediaController::loadFile()
{
    m_filePath = "";

    m_filePath = QFileDialog::getOpenFileName(this, "Choose a .txt file with paths to gtt streams", QString(),
             QString("text file(*.txt)"));

    if (m_filePath.isEmpty())
    {
        return;
    }

    m_file = "";
    m_file.append(m_filePath.toLocal8Bit().constData());

    emit finishedLoadingFile();
}

Issue:

I wish to call the enableButtons() in the MediaView class. But when i instantiate the MediaView class inside MediaController, app crashes because they keep calling each others constructors in a loop. Reason being, they both communicate using signals and slots so i need to instantiate objects of their respective classes.

Alternatives:

I would like to know whether if it is possible to access the widgets from MediaController class so that i can use them there itself?
If not, a better way to communicate between view and controller?

Body:
Each MediaView creates a MediaController, and each MediaController creates another MediaView, that generates the infinite loop, the appropriate thing is to create a MediaController in MediaView and make the connections:

MediaView::MediaView(QWidget* parent) : QWidget(parent)
{
   m_controller = new MediaController(this);
   connect(m_controller, &MediaController::loadingFileFinished, this, &MediaView::enableButtons);
   [...]
}

it is not necessary to create a new MediaView within MediaController.

If you want to access MediaView from MediaController you can do it through parent since MediaView is the parent of MediaController:

MediaController.h

MediaView *view;

MediaController.cpp

MediaController::MediaController(QWidget* parent) : QWidget(parent)
{
    view = qobject_cast<QMediaView *>(parent);
    //or
    // connect(this, &MediaController::loadingFileFinished, view, &MediaView::enableButtons);
}


问:
Android Studio: Simple BaseAdapter Setup Fail
I would like to create a simple populated GridView using BaseAdapter but I keep getting empty list - application runs but there are no Views displayed.
Below are all files are use for this task:

Main:

```<code>String[] items = {"Some", "items", "to", "display"};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    GridView grid = (GridView)findViewById(R.id.grid);
    final TextView text = (TextView)findViewById(R.id.text);

    MyAdapter adapter = new MyAdapter(getApplicationContext(), items);

    grid.setAdapter(adapter);
</code>```

MyAdapter:

LayoutInflater inflater;

```<code>Context context;
String[] myData;

public MyAdapter(Context context, String[] myData) {
    this.context = context;
    this.myData = myData;
}

@Override
public int getCount() {
    return 0;
}

@Override
public Object getItem(int position) {
    return myData[position];
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = inflater.inflate(R.layout.grid, parent, false);
    TextView text = (TextView) convertView.findViewById(R.id.textView);
    text.setText(myData[position]);
    return convertView;
}
</code>```

activity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.android.random.MainActivity">

    <GridView
        android:id="@+id/grid"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:verticalSpacing="40dip"
        android:horizontalSpacing="5dip"
        android:numColumns="auto_fit"
        android:columnWidth="100dip"
        android:stretchMode="columnWidth"
        android:gravity="center"
        />

</android.support.constraint.ConstraintLayout>
</code>```

grid.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        />
</LinearLayout>
</code>```

I have checked in various sources countles times and I did not manage to find an error in my code. It would be amazing if someone would take a look at it and find a reason for empty activity as the reason is probably obvious.

答:
You can try this my friend</p>

```<code>public class MyAdapter extends BaseAdapter {

Context context;
String[] data;

public MyAdapter(Context context, String[] myData) {
    this.context = context;
    this.data = myData;
}

@Override
public int getCount() {
    return data.length;
}

@Override
public Object getItem(int position) {
    return data[position];
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    if (convertView == null) {
            LayoutInflater mInflater = (LayoutInflater)
                    context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

            convertView = mInflater.inflate(R.layout.grid, null);
        }

    TextView text = (TextView) convertView.findViewById(R.id.textView);
    text.setText(data[position]);
    return convertView;

}
}
</code>```

Body:
I would like to create a simple populated GridView using BaseAdapter but I keep getting empty list - application runs but there are no Views displayed.
Below are all files are use for this task:

Main:

String[] items = {"Some", "items", "to", "display"};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    GridView grid = (GridView)findViewById(R.id.grid);
    final TextView text = (TextView)findViewById(R.id.text);

    MyAdapter adapter = new MyAdapter(getApplicationContext(), items);

    grid.setAdapter(adapter);

MyAdapter:

LayoutInflater inflater;

Context context;
String[] myData;

public MyAdapter(Context context, String[] myData) {
    this.context = context;
    this.myData = myData;
}

@Override
public int getCount() {
    return 0;
}

@Override
public Object getItem(int position) {
    return myData[position];
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = inflater.inflate(R.layout.grid, parent, false);
    TextView text = (TextView) convertView.findViewById(R.id.textView);
    text.setText(myData[position]);
    return convertView;
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.android.random.MainActivity">

    <GridView
        android:id="@+id/grid"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:verticalSpacing="40dip"
        android:horizontalSpacing="5dip"
        android:numColumns="auto_fit"
        android:columnWidth="100dip"
        android:stretchMode="columnWidth"
        android:gravity="center"
        />

</android.support.constraint.ConstraintLayout>

grid.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        />
</LinearLayout>

I have checked in various sources countles times and I did not manage to find an error in my code. It would be amazing if someone would take a look at it and find a reason for empty activity as the reason is probably obvious.

Body:
You can try this my friend

public class MyAdapter extends BaseAdapter {

Context context;
String[] data;

public MyAdapter(Context context, String[] myData) {
    this.context = context;
    this.data = myData;
}

@Override
public int getCount() {
    return data.length;
}

@Override
public Object getItem(int position) {
    return data[position];
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    if (convertView == null) {
            LayoutInflater mInflater = (LayoutInflater)
                    context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

            convertView = mInflater.inflate(R.layout.grid, null);
        }

    TextView text = (TextView) convertView.findViewById(R.id.textView);
    text.setText(data[position]);
    return convertView;

}
}


问:
What is wrong with my maze-solving algorithm?
I have used a DFS-algorithm for noting the moves needed to solve the maze. There's a startVertex and an endVertex. My code is as follows:

```<code>private void DFS(int vertex, boolean visited[], LinkedList<Move> output) {

    visited[vertex] = true;

    for (int neighbor: g.neighbors(vertex)) {
        if (visited[neighbor] != true) {
            if (neighbor == vertex + 1)
                output.add(Move.RIGHT);
            else if (neighbor == vertex - 1)
                output.add(Move.LEFT);
            else if (neighbor == vertex + Math.sqrt(g.size()))
                output.add(Move.DOWN);
            else
                output.add(Move.UP);
            if (neighbor == endVertex)
                break;
            DFS(neighbor, visited, output);
        }
        else {
            output.removeLast();
        }
    }
}
</code>```

I am using the removeLast() function when all the surrounding neighbors have been explored and thus that particular vertex remains of no use. But I think that the error lies there only.

The size of graph g is n*n because the original maze is a 2D square matrix with n rows and n columns.

答:
You need to clear visited when leaving DFS (and the endVertex hasn't been found)

output.removeLast should be symmetrical to output.add

break only leaves the innermost loop. Is that what you want?

You probably want to let DFS return whether the endVertex was found, so you know the search can be stopped in higher layers

Body:
I have used a DFS-algorithm for noting the moves needed to solve the maze. There's a startVertex and an endVertex. My code is as follows:

private void DFS(int vertex, boolean visited[], LinkedList<Move> output) {

    visited[vertex] = true;

    for (int neighbor: g.neighbors(vertex)) {
        if (visited[neighbor] != true) {
            if (neighbor == vertex + 1)
                output.add(Move.RIGHT);
            else if (neighbor == vertex - 1)
                output.add(Move.LEFT);
            else if (neighbor == vertex + Math.sqrt(g.size()))
                output.add(Move.DOWN);
            else
                output.add(Move.UP);
            if (neighbor == endVertex)
                break;
            DFS(neighbor, visited, output);
        }
        else {
            output.removeLast();
        }
    }
}

I am using the removeLast() function when all the surrounding neighbors have been explored and thus that particular vertex remains of no use. But I think that the error lies there only.

The size of graph g is n*n because the original maze is a 2D square matrix with n rows and n columns.


问:
How to Invoke Click to Open this Dropdown Menu
I would like to press a button to make this dropdown menu that is in a webbrowser open.

Here is the code html...

```<code><div class="nfTabSelectionWrapper" id="directDisplayStringId"><a class="nfTabSelection nfTabSelection--active mentPicker standardHeight" href="#"><div class="mopNameAndLogos"><span class="nfTabSelection--text card-type-text mentActive">Options</span><div class="logosContainer"><span class="logos logos-inline"></span></div></div><span class="ui-svg-icon ui-svg-icon--chevron pull-right pickerArrow"></span></a></div>
</code>```

Image of Dropdown Menu...

I tried with this code, but it did not work:

```<code>WebBrowser1.Document.GetElementById("directDisplayStringId").InvokeMember("click")
</code>```

答:
The click event of the dropdown is most likely bound to the  element located within the div (seeing as it is only referring to #).

Try getting the first  element of the div and click that:

```<code>Dim directDisplayStringIdDiv As HtmlElement = WebBrowser1.Document.GetElementById("directDisplayStringId")

If directDisplayStringIdDiv Is Nothing Then
    MessageBox.Show("directDisplayStringId doesn't exist.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    Return
End If

Dim anchorElements As HtmlElementCollection = directDisplayStringIdDiv.GetElementsByTagName("a")

If anchorElements.Count <= 0 Then
    MessageBox.Show("No anchor elements found.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    Return
End If

anchorElements(0).InvokeMember("click")
</code>```

Body:
I would like to press a button to make this dropdown menu that is in a webbrowser open.

Here is the code html...

Options

Image of Dropdown Menu...

I tried with this code, but it did not work:

WebBrowser1.Document.GetElementById("directDisplayStringId").InvokeMember("click")

Body:
The click event of the dropdown is most likely bound to the <a> element located within the div (seeing as it is only referring to #).

Try getting the first <a> element of the div and click that:

Dim directDisplayStringIdDiv As HtmlElement = WebBrowser1.Document.GetElementById("directDisplayStringId")

If directDisplayStringIdDiv Is Nothing Then
    MessageBox.Show("directDisplayStringId doesn't exist.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    Return
End If

Dim anchorElements As HtmlElementCollection = directDisplayStringIdDiv.GetElementsByTagName("a")

If anchorElements.Count <= 0 Then
    MessageBox.Show("No anchor elements found.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    Return
End If

anchorElements(0).InvokeMember("click")


问:
Icon in HTML is not showing up on webpage?
I'm trying to have an icon or .png show up the right of the text "username" in a login box for my website, however I can't get it to show up. I practiced making a simple html page and I can get it to appear on the screen of a simple page but cannot get it to appear next to "Username" when I try it with my login page. I tried putting code for a .png and .ico in next to the "username" and in my .css file under the associated header but can't get it to appear. the .png and .ico files are in the root folder. I've read and watched a number of tutorials, tried many different code examples, etc. Any suggestions would be appreciated!

I've tried placing this code with no luck:

```<code><img src = 'sunny.png' style='vertical-align: middle' />
</code>```

My login html code:

$(document).ready(function () {
         $('#logo').addClass('animated fadeInDown');
         $("input:text:visible:first").focus();
     });
     $('#username').focus(function() {
      $('label[for="username"]').addClass('selected');
     });
     $('#username').blur(function() {
      $('label[for="username"]').removeClass('selected');
     });
     $('#password').focus(function() {
      $('label[for="password"]').addClass('selected');
     });
     $('#password').blur(function() {
      $('label[for="password"]').removeClass('selected');
     });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
     background: url("../images/photo_bg.jpg") no-repeat center center fixed;
     background-size: cover;
     font-size: 16px;
     font-family: 'Lato', sans-serif;
     font-weight: 300;
     margin: 0;
     color: #666;
    }

    /* Typography */
    h1#title {
     font-family: 'Roboto Slab', serif;
     font-weight: 300;
     font-size: 3.2em;
     color: white;
     text-shadow: 0 0 10px rgba(0,0,0,0.8);
     margin: 0 auto;
     padding-top: 180px;
     max-width: 300px;
     text-align: center;
     position: relative;
     top: 0px;
    }

    h1#title span span {
     font-weight: 400;
    }

    h2 {
     <img style='vertical-align:middle;' src='gmail.png' width="30">
    <div style='vertical-align:middle; display:inline;'>
    Your text here
    </div>
     text-transform: uppercase;
     color: white;
     font-weight: 400;
     letter-spacing: 1px;
     font-size: 1.4em;
     line-height: 2.8em;
    }

    a {
     text-decoration: none;
     color: #666;
    }

    a:hover {
     color: #aeaeae;
    }

    p.small {
     font-size: 0.8em;
     margin: 20px 0 0;
    }

    /* Layout */
    .container {
     margin: 0;
    }

    .top {
     margin: 0;
     padding: 0;
     width: 100%;
     background: -moz-linear-gradient(top,  rgba(0,0,0,0.6) 0%, rgba(0,0,0,0) 100%); /* FF3.6-15 */
     background: -webkit-linear-gradient(top,  rgba(0,0,0,0.6) 0%,rgba(0,0,0,0) 100%); /* Chrome10-25,Safari5.1-6 */
     background: linear-gradient(to bottom,  rgba(0,0,0,0.6) 0%,rgba(0,0,0,0) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
     filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#99000000', endColorstr='#00000000',GradientType=0 ); /* IE6-9 */
    }

    .login-box {
     background-color: white;
     max-width: 340px;
     margin: 0 auto;
     position: relative;
     top: 80px;
     padding-bottom: 30px;
     border-radius: 5px;
     box-shadow: 0 5px 50px rgba(0,0,0,0.4);
     text-align: center;
    }

    .login-box .box-header {
     background-color: #665851;
     margin-top: 0;
     border-radius: 5px 5px 0 0;
    }

    .login-box label {
     font-weight: 700;
     font-size: .8em;
     color: #888;
     letter-spacing: 1px;
     text-transform: uppercase;
     line-height: 2em;
    }

    .login-box input {
     margin-bottom: 20px;
     padding: 8px;
     border: 1px solid #ccc;
     border-radius: 2px;
     font-size: .9em;
     color: #888;
    }

    .login-box input:focus {
     outline: none;
     border-color: #665851;
     transition: 0.5s;
     color: #665851;
    }

    .login-box button {
     margin-top: 0px;
     border: 0;
     border-radius: 2px;
     color: white;
     padding: 10px;
     text-transform: uppercase;
     font-weight: 400;
     font-size: 0.7em;
     letter-spacing: 1px;
     background-color: #665851;
     cursor:pointer;
     outline: none;
    }

    .login-box button:hover {
     opacity: 0.7;
     transition: 0.5s;
    }

    .login-box button:hover {
     opacity: 0.7;
     transition: 0.5s;
    }

    .selected {
     color: #665851!important;
     transition: 0.5s;
    }

    /* Animation Delay */
    #logo {
      -webkit-animation-duration: 1s;
      -webkit-animation-delay: 2s;
    }

    .login-box {
      -webkit-animation-duration: 1s;
      -webkit-animation-delay: 1s;
    }</code>```

Daily UI

Log In

       Username

       <input type="text" id="username">

       Password

       <input type="password" id="password">

       <button type="submit">Sign In</button>

Forgot your password?

    ```

答:
Try adding :

Font Awesome CSS URI

CheatSheet :  placeholder=" Username"

and input { font-family: 'FontAwesome'; }  into your css

$(document).ready(function () {
         $('#logo').addClass('animated fadeInDown');
         $("input:text:visible:first").focus();
     });
     $('#username').focus(function() {
      $('label[for="username"]').addClass('selected');
     });
     $('#username').blur(function() {
      $('label[for="username"]').removeClass('selected');
     });
     $('#password').focus(function() {
      $('label[for="password"]').addClass('selected');
     });
     $('#password').blur(function() {
      $('label[for="password"]').removeClass('selected');
     });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
     background: url("../images/photo_bg.jpg") no-repeat center center fixed;
     background-size: cover;
     font-size: 16px;
     font-family: 'Lato', sans-serif;
     font-weight: 300;
     margin: 0;
     color: #666;
    }

    /* Typography */
    h1#title {
     font-family: 'Roboto Slab', serif;
     font-weight: 300;
     font-size: 3.2em;
     color: white;
     text-shadow: 0 0 10px rgba(0,0,0,0.8);
     margin: 0 auto;
     padding-top: 180px;
     max-width: 300px;
     text-align: center;
     position: relative;
     top: 0px;
    }

    h1#title span span {
     font-weight: 400;
    }

    h2 {
     <img style='vertical-align:middle;' src='gmail.png' width="30">
    <div style='vertical-align:middle; display:inline;'>
    Your text here
    </div>
     text-transform: uppercase;
     color: white;
     font-weight: 400;
     letter-spacing: 1px;
     font-size: 1.4em;
     line-height: 2.8em;
    }

    a {
     text-decoration: none;
     color: #666;
    }

    a:hover {
     color: #aeaeae;
    }

    p.small {
     font-size: 0.8em;
     margin: 20px 0 0;
    }

    /* Layout */
    .container {
     margin: 0;
    }

    .top {
     margin: 0;
     padding: 0;
     width: 100%;
     background: -moz-linear-gradient(top,  rgba(0,0,0,0.6) 0%, rgba(0,0,0,0) 100%); /* FF3.6-15 */
     background: -webkit-linear-gradient(top,  rgba(0,0,0,0.6) 0%,rgba(0,0,0,0) 100%); /* Chrome10-25,Safari5.1-6 */
     background: linear-gradient(to bottom,  rgba(0,0,0,0.6) 0%,rgba(0,0,0,0) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
     filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#99000000', endColorstr='#00000000',GradientType=0 ); /* IE6-9 */
    }

    .login-box {
     background-color: white;
     max-width: 340px;
     margin: 0 auto;
     position: relative;
     top: 80px;
     padding-bottom: 30px;
     border-radius: 5px;
     box-shadow: 0 5px 50px rgba(0,0,0,0.4);
     text-align: center;
    }

    .login-box .box-header {
     background-color: #665851;
     margin-top: 0;
     border-radius: 5px 5px 0 0;
    }

    .login-box label {
     font-weight: 700;
     font-size: .8em;
     color: #888;
     letter-spacing: 1px;
     text-transform: uppercase;
     line-height: 2em;
    }

    input { font-family: 'FontAwesome'; /* This is for the placeholder */

    .login-box input {
     margin-bottom: 20px;
     padding: 8px;
     border: 1px solid #ccc;
     border-radius: 2px;
     font-size: .9em;
     color: #888;
    }

    .login-box input:focus {
     outline: none;
     border-color: #665851;
     transition: 0.5s;
     color: #665851;
    }

    .login-box button {
     margin-top: 0px;
     border: 0;
     border-radius: 2px;
     color: white;
     padding: 10px;
     text-transform: uppercase;
     font-weight: 400;
     font-size: 0.7em;
     letter-spacing: 1px;
     background-color: #665851;
     cursor:pointer;
     outline: none;
    }

    .login-box button:hover {
     opacity: 0.7;
     transition: 0.5s;
    }

    .login-box button:hover {
     opacity: 0.7;
     transition: 0.5s;
    }

    .selected {
     color: #665851!important;
     transition: 0.5s;
    }

    /* Animation Delay */
    #logo {
      -webkit-animation-duration: 1s;
      -webkit-animation-delay: 2s;
    }

    .login-box {
      -webkit-animation-duration: 1s;
      -webkit-animation-delay: 1s;
    }</code>```

<link href="https://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet"/>

Daily UI

Log In

       Username

       <input type="text" id="username" placeholder=" Username">

       Password

       <input type="password" id="password" placeholder=" Password">

       <button type="submit">Sign In</button>

Forgot your password?

    ```

Body:
I'm trying to have an icon or .png show up the right of the text "username" in a login box for my website, however I can't get it to show up. I practiced making a simple html page and I can get it to appear on the screen of a simple page but cannot get it to appear next to "Username" when I try it with my login page. I tried putting code for a .png and .ico in next to the "username" and in my .css file under the associated header but can't get it to appear. the .png and .ico files are in the root folder. I've read and watched a number of tutorials, tried many different code examples, etc. Any suggestions would be appreciated!

I've tried placing this code with no luck:

My login html code:

$(document).ready(function () {
         $('#logo').addClass('animated fadeInDown');
         $("input:text:visible:first").focus();
     });
     $('#username').focus(function() {
      $('label[for="username"]').addClass('selected');
     });
     $('#username').blur(function() {
      $('label[for="username"]').removeClass('selected');
     });
     $('#password').focus(function() {
      $('label[for="password"]').addClass('selected');
     });
     $('#password').blur(function() {
      $('label[for="password"]').removeClass('selected');
     });

body {
     background: url("../images/photo_bg.jpg") no-repeat center center fixed;
     background-size: cover;
     font-size: 16px;
     font-family: 'Lato', sans-serif;
     font-weight: 300;
     margin: 0;
     color: #666;
    }

    /* Typography */
    h1#title {
     font-family: 'Roboto Slab', serif;
     font-weight: 300;
     font-size: 3.2em;
     color: white;
     text-shadow: 0 0 10px rgba(0,0,0,0.8);
     margin: 0 auto;
     padding-top: 180px;
     max-width: 300px;
     text-align: center;
     position: relative;
     top: 0px;
    }

    h1#title span span {
     font-weight: 400;
    }

    h2 {

    Your text here

     text-transform: uppercase;
     color: white;
     font-weight: 400;
     letter-spacing: 1px;
     font-size: 1.4em;
     line-height: 2.8em;
    }

    a {
     text-decoration: none;
     color: #666;
    }

    a:hover {
     color: #aeaeae;
    }

    p.small {
     font-size: 0.8em;
     margin: 20px 0 0;
    }

    /* Layout */
    .container {
     margin: 0;
    }

    .top {
     margin: 0;
     padding: 0;
     width: 100%;
     background: -moz-linear-gradient(top,  rgba(0,0,0,0.6) 0%, rgba(0,0,0,0) 100%); /* FF3.6-15 */
     background: -webkit-linear-gradient(top,  rgba(0,0,0,0.6) 0%,rgba(0,0,0,0) 100%); /* Chrome10-25,Safari5.1-6 */
     background: linear-gradient(to bottom,  rgba(0,0,0,0.6) 0%,rgba(0,0,0,0) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
     filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#99000000', endColorstr='#00000000',GradientType=0 ); /* IE6-9 */
    }

    .login-box {
     background-color: white;
     max-width: 340px;
     margin: 0 auto;
     position: relative;
     top: 80px;
     padding-bottom: 30px;
     border-radius: 5px;
     box-shadow: 0 5px 50px rgba(0,0,0,0.4);
     text-align: center;
    }

    .login-box .box-header {
     background-color: #665851;
     margin-top: 0;
     border-radius: 5px 5px 0 0;
    }

    .login-box label {
     font-weight: 700;
     font-size: .8em;
     color: #888;
     letter-spacing: 1px;
     text-transform: uppercase;
     line-height: 2em;
    }

    .login-box input {
     margin-bottom: 20px;
     padding: 8px;
     border: 1px solid #ccc;
     border-radius: 2px;
     font-size: .9em;
     color: #888;
    }

    .login-box input:focus {
     outline: none;
     border-color: #665851;
     transition: 0.5s;
     color: #665851;
    }

    .login-box button {
     margin-top: 0px;
     border: 0;
     border-radius: 2px;
     color: white;
     padding: 10px;
     text-transform: uppercase;
     font-weight: 400;
     font-size: 0.7em;
     letter-spacing: 1px;
     background-color: #665851;
     cursor:pointer;
     outline: none;
    }

    .login-box button:hover {
     opacity: 0.7;
     transition: 0.5s;
    }

    .login-box button:hover {
     opacity: 0.7;
     transition: 0.5s;
    }

    .selected {
     color: #665851!important;
     transition: 0.5s;
    }

    /* Animation Delay */
    #logo {
      -webkit-animation-duration: 1s;
      -webkit-animation-delay: 2s;
    }

    .login-box {
      -webkit-animation-duration: 1s;
      -webkit-animation-delay: 1s;
    }

Daily UI

Log In

       Username

       <input type="text" id="username">

       Password

       <input type="password" id="password">

       <button type="submit">Sign In</button>

Forgot your password?

Body:
Try adding :

Font Awesome CSS URI

CheatSheet :  placeholder="&#61447; Username"

and input { font-family: 'FontAwesome'; }  into your css

$(document).ready(function () {
         $('#logo').addClass('animated fadeInDown');
         $("input:text:visible:first").focus();
     });
     $('#username').focus(function() {
      $('label[for="username"]').addClass('selected');
     });
     $('#username').blur(function() {
      $('label[for="username"]').removeClass('selected');
     });
     $('#password').focus(function() {
      $('label[for="password"]').addClass('selected');
     });
     $('#password').blur(function() {
      $('label[for="password"]').removeClass('selected');
     });

body {
     background: url("../images/photo_bg.jpg") no-repeat center center fixed;
     background-size: cover;
     font-size: 16px;
     font-family: 'Lato', sans-serif;
     font-weight: 300;
     margin: 0;
     color: #666;
    }

    /* Typography */
    h1#title {
     font-family: 'Roboto Slab', serif;
     font-weight: 300;
     font-size: 3.2em;
     color: white;
     text-shadow: 0 0 10px rgba(0,0,0,0.8);
     margin: 0 auto;
     padding-top: 180px;
     max-width: 300px;
     text-align: center;
     position: relative;
     top: 0px;
    }

    h1#title span span {
     font-weight: 400;
    }

    h2 {
     <img style='vertical-align:middle;' src='gmail.png' width="30">
    <div style='vertical-align:middle; display:inline;'>
    Your text here
    </div>
     text-transform: uppercase;
     color: white;
     font-weight: 400;
     letter-spacing: 1px;
     font-size: 1.4em;
     line-height: 2.8em;
    }

    a {
     text-decoration: none;
     color: #666;
    }

    a:hover {
     color: #aeaeae;
    }

    p.small {
     font-size: 0.8em;
     margin: 20px 0 0;
    }

    /* Layout */
    .container {
     margin: 0;
    }

    .top {
     margin: 0;
     padding: 0;
     width: 100%;
     background: -moz-linear-gradient(top,  rgba(0,0,0,0.6) 0%, rgba(0,0,0,0) 100%); /* FF3.6-15 */
     background: -webkit-linear-gradient(top,  rgba(0,0,0,0.6) 0%,rgba(0,0,0,0) 100%); /* Chrome10-25,Safari5.1-6 */
     background: linear-gradient(to bottom,  rgba(0,0,0,0.6) 0%,rgba(0,0,0,0) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
     filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#99000000', endColorstr='#00000000',GradientType=0 ); /* IE6-9 */
    }

    .login-box {
     background-color: white;
     max-width: 340px;
     margin: 0 auto;
     position: relative;
     top: 80px;
     padding-bottom: 30px;
     border-radius: 5px;
     box-shadow: 0 5px 50px rgba(0,0,0,0.4);
     text-align: center;
    }

    .login-box .box-header {
     background-color: #665851;
     margin-top: 0;
     border-radius: 5px 5px 0 0;
    }

    .login-box label {
     font-weight: 700;
     font-size: .8em;
     color: #888;
     letter-spacing: 1px;
     text-transform: uppercase;
     line-height: 2em;
    }

    input { font-family: 'FontAwesome'; /* This is for the placeholder */

    .login-box input {
     margin-bottom: 20px;
     padding: 8px;
     border: 1px solid #ccc;
     border-radius: 2px;
     font-size: .9em;
     color: #888;
    }

    .login-box input:focus {
     outline: none;
     border-color: #665851;
     transition: 0.5s;
     color: #665851;
    }

    .login-box button {
     margin-top: 0px;
     border: 0;
     border-radius: 2px;
     color: white;
     padding: 10px;
     text-transform: uppercase;
     font-weight: 400;
     font-size: 0.7em;
     letter-spacing: 1px;
     background-color: #665851;
     cursor:pointer;
     outline: none;
    }

    .login-box button:hover {
     opacity: 0.7;
     transition: 0.5s;
    }

    .login-box button:hover {
     opacity: 0.7;
     transition: 0.5s;
    }

    .selected {
     color: #665851!important;
     transition: 0.5s;
    }

    /* Animation Delay */
    #logo {
      -webkit-animation-duration: 1s;
      -webkit-animation-delay: 2s;
    }

    .login-box {
      -webkit-animation-duration: 1s;
      -webkit-animation-delay: 1s;
    }

<link href="https://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<body>
     <div class="container">
      <div class="top">
       <h1 id="title" class="hidden"><span id="logo">Daily <span>UI</span></span></h1>
      </div>
      <div class="login-box animated fadeInUp">
       <div class="box-header">
        <h2>Log In</h2>
       </div>
       <label for="username">Username</label>
       <br/>
       <input type="text" id="username" placeholder="&#61447; Username">
       <br/>
       <label for="password">Password</label>
       <br/>
       <input type="password" id="password" placeholder="&#xf084; Password">
       <br/>
       <button type="submit">Sign In</button>
       <br/>
       <a href="#"><p class="small">Forgot your password?</p></a>
      </div>
     </div>
    </body>