问:
Public Static Void Add(Ship) is not working. Don't know how to "add ship"
I am working on my project and am having problems with a couple lines of code. I'm brand new to C# so I don't really understand it as much as I would like to yet. I was asked to create a new class called "Ships" that will allows you to add a ship {void Add(Ship)} and reset the collection {void Clear()}. This is what I've come up with but again, there are problems I don't know how to fix. Thank you for the help.

. Lines 44 through 59 don't seem to be working.
. I am trying to enter a void Add(Ship) method that will allow you to add a ship
. The add method should validate that no ships are overlapping
. If there is a collision this method should throw a suitable exception

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Module_4_Battleship
  {

    public class Ships
    {
        public string ShipName { get; set; }
        public ShipOrientation Orientation { get; set; }
        public int ShipNum { get; set; }
        public int ExtentUnits { get; set; }
        public int Position_Row { get; set; }
        public int Position_Col { get; set; }
        static bool PlayerGameOver, GameOverBool;
        public override string ToString()
        {
            return "Ship Number: " + ShipNum + "   Ship Name: " + ShipName;
        }
        public override bool Equals(object obj)
        {
            if (obj == null) return false;
            Ship objAsShip = obj as Ship;
            if (objAsShip == null) return false;
            else return Equals(objAsShip);
        }
        public override int GetHashCode()
        {
            return ShipNum;
        }
        public bool Equals(Ship other)
        {
            if (other == null) return false;
            return (this.ShipNum.Equals(other.ShipNum));
        }

        ***public static void Add(Ship)
        {
            List<Ship> ships = new List<Ship>
            {
                new Ship() { ShipName = "Battleship", ShipNum = 1 },
                new Ship() { ShipName = "Cruiser", ShipNum = 2 },
                new Ship() { ShipName = "Submarine", ShipNum = 3 },
                new Ship() { ShipName = "Attacker", ShipNum = 4 },
                new Ship() { ShipName = "The Soldier", ShipNum = 5 },
                new Ship() { ShipName = "Boat", ShipNum = 6 }***
            };
            ;

            Console.WriteLine();
            foreach (Ship aShip in ships)
            {
                Console.WriteLine(aShip);
            }

            Console.WriteLine("\nContains(\"1\"): {0}",
            ships.Contains(new Ship { ShipNum = 1, ShipName = "" }));

            Console.WriteLine("\nInsert(2, \"2\")");
            ships.Insert(2, new Ship() { ShipName = "Cruiser", ShipNum = 2
 });

            //Console.WriteLine();
            foreach (Ship aShip in ships)
            {
                Console.WriteLine(aShip);
            }

            Console.WriteLine("\nParts[3]: {0}", ships[3]);

            Console.WriteLine("\nRemove(\"1534\")");

            ships.Remove(new Ship() { ShipNum = 3, ShipName = "Submarine"
});

            Console.WriteLine();
            foreach (Ship aShip in ships)
            {
                Console.WriteLine(aShip);
            }
            Console.WriteLine("\nRemoveAt(3)");

            ships.RemoveAt(3);

            Console.WriteLine();
            foreach (Ship aShip in ships)
            {
                Console.WriteLine(aShip);
            }

        }
        public void clear()
        {

            Console.Clear();
        }

        public bool Attack(int Row, int Col)
        {
            if (this.Orientation == ShipOrientation.Horizontal)
                return (
                   Row == this.Position_Row
                   &&
                   Col >= Position_Col
                   &&
                   Col <= (Position_Col + ExtentUnits - 1)
                 );
            else
                return (
                   Col == this.Position_Col
                   &&
                   Row >= Position_Row
                   &&
                   Row <= (Position_Row + ExtentUnits - 1)
                 );
        }
        public enum ShipOrientation
        {
            Horizontal = 0,
            Vertical
        }
    }
}
</code>```

答:
Some of this has already been pointed out in the comments, but here it goes.

As indicated in the comments, this class seems to conflate the concept of a ship and the concept of a collection of ships. I strongly suggest splitting them.

Secondly, the signature of the Add method is incorrect:

```<code>public static void Add(Ship)
</code>```

Ship is the type/class name, but (as also pointed out in the comments) you also need to include a variable name if you're trying to add a specific ship.

Also, the clear method is incorrect. All this does is clear the console - it doesn't actually do anything to the underlying data:

```<code>public void clear()
{
    Console.Clear();
}
</code>```

Also, it looks like your Add method does a lot of stuff other than just adding a ship to the collection. As a professor of mine used to say, you generally shouldn't have to use the word "and" when describing what a method or class does.

On a related note, I actually strongly recommend using C#'s XML Documentation feature to describe the purpose of each of your methods, especially since you're still new to the language. Basically, this enables you to write a summary, description of your arguments, description of your return value, describe what exceptions it may throw, etc. - Visual Studio will even use it to generate Intellisense. You can put as much detail as you want, or just write some basic details (e.g. a summary of the method). Trust me, it helps, and the more thorough you are the more it helps. For example, awhile back I was having trouble writing a method, so I tried to write XML documentation for it; I quickly realized that I couldn't remember why I was adding the method in the first place (hence the reason I was having trouble writing it). It's definitely helped me get "unstuck" and/or debug quite a few times, too.

One final code issue: right now you just store the data locally to the Add method. That means that, as soon as the Add method finishes, your list of ships (along with any changes you made to it) will be lost.

Body:
I am working on my project and am having problems with a couple lines of code. I'm brand new to C# so I don't really understand it as much as I would like to yet. I was asked to create a new class called "Ships" that will allows you to add a ship {void Add(Ship)} and reset the collection {void Clear()}. This is what I've come up with but again, there are problems I don't know how to fix. Thank you for the help.

. Lines 44 through 59 don't seem to be working.
. I am trying to enter a void Add(Ship) method that will allow you to add a ship
. The add method should validate that no ships are overlapping
. If there is a collision this method should throw a suitable exception

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Module_4_Battleship
  {

    public class Ships
    {
        public string ShipName { get; set; }
        public ShipOrientation Orientation { get; set; }
        public int ShipNum { get; set; }
        public int ExtentUnits { get; set; }
        public int Position_Row { get; set; }
        public int Position_Col { get; set; }
        static bool PlayerGameOver, GameOverBool;
        public override string ToString()
        {
            return "Ship Number: " + ShipNum + "   Ship Name: " + ShipName;
        }
        public override bool Equals(object obj)
        {
            if (obj == null) return false;
            Ship objAsShip = obj as Ship;
            if (objAsShip == null) return false;
            else return Equals(objAsShip);
        }
        public override int GetHashCode()
        {
            return ShipNum;
        }
        public bool Equals(Ship other)
        {
            if (other == null) return false;
            return (this.ShipNum.Equals(other.ShipNum));
        }

        ***public static void Add(Ship)
        {
            List<Ship> ships = new List<Ship>
            {
                new Ship() { ShipName = "Battleship", ShipNum = 1 },
                new Ship() { ShipName = "Cruiser", ShipNum = 2 },
                new Ship() { ShipName = "Submarine", ShipNum = 3 },
                new Ship() { ShipName = "Attacker", ShipNum = 4 },
                new Ship() { ShipName = "The Soldier", ShipNum = 5 },
                new Ship() { ShipName = "Boat", ShipNum = 6 }***
            };
            ;

            Console.WriteLine();
            foreach (Ship aShip in ships)
            {
                Console.WriteLine(aShip);
            }

            Console.WriteLine("\nContains(\"1\"): {0}",
            ships.Contains(new Ship { ShipNum = 1, ShipName = "" }));

            Console.WriteLine("\nInsert(2, \"2\")");
            ships.Insert(2, new Ship() { ShipName = "Cruiser", ShipNum = 2
 });

            //Console.WriteLine();
            foreach (Ship aShip in ships)
            {
                Console.WriteLine(aShip);
            }

            Console.WriteLine("\nParts[3]: {0}", ships[3]);

            Console.WriteLine("\nRemove(\"1534\")");

            ships.Remove(new Ship() { ShipNum = 3, ShipName = "Submarine"
});

            Console.WriteLine();
            foreach (Ship aShip in ships)
            {
                Console.WriteLine(aShip);
            }
            Console.WriteLine("\nRemoveAt(3)");

            ships.RemoveAt(3);

            Console.WriteLine();
            foreach (Ship aShip in ships)
            {
                Console.WriteLine(aShip);
            }

        }
        public void clear()
        {

            Console.Clear();
        }

        public bool Attack(int Row, int Col)
        {
            if (this.Orientation == ShipOrientation.Horizontal)
                return (
                   Row == this.Position_Row
                   &&
                   Col >= Position_Col
                   &&
                   Col <= (Position_Col + ExtentUnits - 1)
                 );
            else
                return (
                   Col == this.Position_Col
                   &&
                   Row >= Position_Row
                   &&
                   Row <= (Position_Row + ExtentUnits - 1)
                 );
        }
        public enum ShipOrientation
        {
            Horizontal = 0,
            Vertical
        }
    }
}

Body:
Some of this has already been pointed out in the comments, but here it goes.

As indicated in the comments, this class seems to conflate the concept of a ship and the concept of a collection of ships. I strongly suggest splitting them.

Secondly, the signature of the Add method is incorrect:

public static void Add(Ship)

Ship is the type/class name, but (as also pointed out in the comments) you also need to include a variable name if you're trying to add a specific ship.

Also, the clear method is incorrect. All this does is clear the console - it doesn't actually do anything to the underlying data:

public void clear()
{
    Console.Clear();
}

Also, it looks like your Add method does a lot of stuff other than just adding a ship to the collection. As a professor of mine used to say, you generally shouldn't have to use the word "and" when describing what a method or class does.

On a related note, I actually strongly recommend using C#'s XML Documentation feature to describe the purpose of each of your methods, especially since you're still new to the language. Basically, this enables you to write a summary, description of your arguments, description of your return value, describe what exceptions it may throw, etc. - Visual Studio will even use it to generate Intellisense. You can put as much detail as you want, or just write some basic details (e.g. a summary of the method). Trust me, it helps, and the more thorough you are the more it helps. For example, awhile back I was having trouble writing a method, so I tried to write XML documentation for it; I quickly realized that I couldn't remember why I was adding the method in the first place (hence the reason I was having trouble writing it). It's definitely helped me get "unstuck" and/or debug quite a few times, too.

One final code issue: right now you just store the data locally to the Add method. That means that, as soon as the Add method finishes, your list of ships (along with any changes you made to it) will be lost.


来源: stackexchange

问:
d3.js force directed graph: How to make node size depends on the value of the links?
I have this kind of data:

var nodes = [
{
    "id": "A",
    "label": "Data A",
    "group": "0",
    "level": "0"
}, {
    "id": "B",
    "label": "Data B",
    "group": "1",
    "level": "1"
},
// etc //
]

var links = [
{
    "source": "A",
    "target": "B",
"strength": "0.5",
    "value": "276"
}, {
    "source": "A",
    "target": "C",
"strength": "0.5",
"value": "866"
},
// etc //
]
```

<p>I've been trying to set the nodes radius size according to the <code>value</code> from the links that have said node as its <code>target</code>.</p>

<p>So for example, node B should have its size according to the value of 276 (the link that have node B as its target).</p>

<p>This what I use:</p>

<pre class="lang-js prettyprint-override"><code>var nodeElements = g.append("g")
    .attr("class", "nodes")
    .selectAll("circle")
    .data(nodes)
    .enter().append("circle")
    .attr("r", function(node,link){
          var radius = 12;
          if (node.level == 0) radius = radius * 2; // Setting up the main node as bigger than others

          node.weight = link.filter(function(link) {
             if (link.target.index == node.index){
               var linkValue = link.value;
               if (linkValue > 500) ? (radius = 12) : (radius = 6);
             }
          });

          return radius;
      })
    .attr("fill", getNodeColor)
    .attr("stroke", "#fff")
    .attr('stroke-width', 2)
    .on('mouseover', selectNode)
</code>```

That doesn't seem to work though. Says it doesn't recognize the link.filter, something I've taken from here. I'm using d3.js v4.

Tried looking up for clues but still got no hints. Any ideas?

答:
There are several things that need to change, but first you should understand that you are not automatically adding links to the node's data.

So the purpose of the filter statement seems to be to find the corresponding link in that array, based on index.
There is no link variable passed into the outer function, but instead you should be searching through the links array defined above for one link that has target with the node's id.

If you only need one link, and not all of them, use Array.prototype.find. But filter and find work the same way - the anonymous function defined is called on each item in the array. find stops at the first found object, while filter returns all matches.

```<code>.attr("r", function(dat, index, n) {
    var linkItem = links.find(function(link) {
        return link.target == dat.id;
    });
    var radius = 12;
    // linkItem would be undefined if the item was not found in the links
    if (linkItem && linkItem.value > 500) {
        radius = 12;
    } else {
        radius = 6;
    }

    // you should double the radius towards the end,
    // so that radius doesn't get overwritten
    if (dat.level === 0) {
        radius = 2 * radius;
    }

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

ContentLicense: CC BY-SA 3.0

Body:
I have this kind of data:

var nodes = [
{
    "id": "A",
    "label": "Data A",
    "group": "0",
    "level": "0"
}, {
    "id": "B",
    "label": "Data B",
    "group": "1",
    "level": "1"
},
// etc //
]

var links = [
{
    "source": "A",
    "target": "B",
"strength": "0.5",
    "value": "276"
}, {
    "source": "A",
    "target": "C",
"strength": "0.5",
"value": "866"
},
// etc //
]

I've been trying to set the nodes radius size according to the value from the links that have said node as its target.

So for example, node B should have its size according to the value of 276 (the link that have node B as its target).

This what I use:

var nodeElements = g.append("g")
    .attr("class", "nodes")
    .selectAll("circle")
    .data(nodes)
    .enter().append("circle")
    .attr("r", function(node,link){
          var radius = 12;
          if (node.level == 0) radius = radius * 2; // Setting up the main node as bigger than others

          node.weight = link.filter(function(link) {
             if (link.target.index == node.index){
               var linkValue = link.value;
               if (linkValue > 500) ? (radius = 12) : (radius = 6);
             }
          });

          return radius;
      })
    .attr("fill", getNodeColor)
    .attr("stroke", "#fff")
    .attr('stroke-width', 2)
    .on('mouseover', selectNode)

That doesn't seem to work though. Says it doesn't recognize the link.filter, something I've taken from here. I'm using d3.js v4.

Tried looking up for clues but still got no hints. Any ideas?

Body:
There are several things that need to change, but first you should understand that you are not automatically adding links to the node's data.

So the purpose of the filter statement seems to be to find the corresponding link in that array, based on index.
There is no link variable passed into the outer function, but instead you should be searching through the links array defined above for one link that has target with the node's id.

If you only need one link, and not all of them, use Array.prototype.find. But filter and find work the same way - the anonymous function defined is called on each item in the array. find stops at the first found object, while filter returns all matches.

.attr("r", function(dat, index, n) {
    var linkItem = links.find(function(link) {
        return link.target == dat.id;
    });
    var radius = 12;
    // linkItem would be undefined if the item was not found in the links
    if (linkItem && linkItem.value > 500) {
        radius = 12;
    } else {
        radius = 6;
    }

    // you should double the radius towards the end,
    // so that radius doesn't get overwritten
    if (dat.level === 0) {
        radius = 2 * radius;
    }

    return radius;
})


问:
A way to reduce run-time
I have a 2048x2048 image and I want to re-set the pixels values according to certain condition. The problem is that it takes houres (if not days) for the code to end. Is there a way to shorten the run-time?
This is the function:

```<code>function ProcImage = ProcessImage(X,length,width)
 for i=1:length
    for j=1:width
        if X(j,i)<=0.025*(max(max(X(:,:))))
            X(j,i)=0;
        else
            if X(j,i)>=0.95*(max(max(X(:,:))))
                X(j,i)=(max(max(X(:,:))));
            end
        end
    end
end
ProcImage=X(1:end,1:end);
</code>```

thanks in advance.

答:
Vectorize it. You don't need to compute the maximum value of X on every iteration, since it will be the same throughout. Compute it once, store that value, then use it later. You can also do away with the loops by using element-wise logical operations and matrix indexing. Here's a simplified version that should be much faster:

```<code>maxX = max(X(:));
X(X <= 0.025.*maxX) = 0;
X(X >= 0.95.*maxX) = maxX;
</code>```

Title: A way to reduce run-time

Body:
I have a 2048x2048 image and I want to re-set the pixels values according to certain condition. The problem is that it takes houres (if not days) for the code to end. Is there a way to shorten the run-time?
This is the function:

function ProcImage = ProcessImage(X,length,width)
 for i=1:length
    for j=1:width
        if X(j,i)<=0.025*(max(max(X(:,:))))
            X(j,i)=0;
        else
            if X(j,i)>=0.95*(max(max(X(:,:))))
                X(j,i)=(max(max(X(:,:))));
            end
        end
    end
end
ProcImage=X(1:end,1:end);

thanks in advance.

Body:
Vectorize it. You don't need to compute the maximum value of X on every iteration, since it will be the same throughout. Compute it once, store that value, then use it later. You can also do away with the loops by using element-wise logical operations and matrix indexing. Here's a simplified version that should be much faster:

maxX = max(X(:));
X(X <= 0.025.*maxX) = 0;
X(X >= 0.95.*maxX) = maxX;


问:
App Registration Role Deletion?
I have a requirement to delete some roles from an app registration.

Have tried to do this on the Azure portal both directly in the manifest editor and by downloading / editing / uploading the manifest JSON.

I get the following error:

Failed to update application xxxxxx.  Error details:
  CannotDeleteEnabledEntitlement.

I also tried to set "isEnabled" property to "false" and delete the roles after that with no success.

Anyone have any pointers on how to overcome this issue?

答:
As you mentioned in your post, the deletion of any OAuth2Permission is a 2 step process:

You must first disable the permission, and push that to the directory.

Then you can delete the permission.

The error message you are showing in your post is a result of you not disabling the permission first. You will need to share details about the error you get if trying to delete the disabled permission fails as well.

Title: App Registration Role Deletion?


问:
No Reverse Match error in Django
New to Django and stuck on this error. My template was rendering correctly. The only change I made was adding a '1/0' in my views.py file to simulate a breakpoint. And now the template will not render when I remove it.

urls.py

```<code>from django.conf.urls import url
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.views import login, logout
from app.views import send_morsel, start_hunt, MorselList, MorselDetailView,\
register, create_morsel, HomePageView, FAQPageView, AboutPageView,\
newsletter_signup, edit_morsel

app_name = 'app'
urlpatterns = [
    url(r'^$', HomePageView.as_view(), name='home'),
    url(r'^morsels/$', MorselList.as_view(), name='morsel_list'),
    url(r'^morsels/send/$', send_morsel, name='morsel_send'),
    url(r'^morsels/(?P<morsel_id>[0-9])/start_hunt/$', start_hunt, name='start_hunt'),
    url(r'^register/', register, name='register'),
    url(r'^faq/$', FAQPageView.as_view(), name='faq'),
    url(r'^about/$', AboutPageView.as_view(), name='about'),
    url(r'^morsels/create/$', create_morsel, name="create_morsel"),
    url(r'^morsels/(?P<morsel_id>[0-9])/edit/$', edit_morsel, name='edit_morsel'),
    url(r'^morsels/(?P<pk>[0-9])/display/$', MorselDetailView.as_view(), name='morsel_detail'),
    url(r'^newsletter_signup/$', newsletter_signup, name='newsletter_signup')
]
</code>```

morsel_list.html

```<code>{% extends "app/base.html" %}
{% load bootstrap3 %}
{% bootstrap_css %}
{% bootstrap_javascript %}
{% bootstrap_messages %}
{% block content %}
    <h2>Morsels</h2>
    {% if user.is_authenticated %}
        <p>hello</p>
        <p>welcome {{ user.username }}</p>
        <p><a href="/logout">Logout</a></p>
    {% else %}
        <p><a href="/login">Login</a></p>
        <p><a href="/app/register">Register</a></p>
    {% endif %}
    <ul>
        {% for morsel in object_list %}
            <li>{{ morsel.name }}
                <a href="{%url 'app:morsel_detail' morsel.id%}">View</a>
                <a href="{%url 'app:edit_morsel' morsel.id %}">Edit</a>
                <a href="{%url 'app:start_hunt' morsel.id%}">Send! </a>
            </li>
        {% endfor %}
    </ul>
    {% if messages %}
        {% for msg in messages %}
            {% bootstrap_alert msg.message alert_type=msg.level_tag %}
        {% endfor %}
    {% endif %}
{% endblock %}
</code>```

Really not sure what to do here.

relevant block from views.py:

```<code>def edit_morsel(request, morsel_id=None):
    if request.method == 'POST':
        extra = int(request.session['extra'])
        form = MorselCreationForm(request.POST)
        formset = formset_factory(QuestionAnswerCreationForm, extra=extra)(request.POST)
        if form.is_valid() and formset.is_valid():
            name = form.cleaned_data["name"]
            start_time = form.cleaned_data["start_time"]
            end_time = form.cleaned_data["end_time"]
            welcome_text = form.cleaned_data["welcome_text"]
            completed_text = form.cleaned_data["completed_text"]
            public_enabled = form.cleaned_data["public_enabled"]
            m = Morsel(
                name=name,
                start_time = start_time,
                end_time = end_time,
                welcome_text = welcome_text,
                completed_text = completed_text,
                public_enabled = public_enabled
            )
            m.save()
            # this order is important to be able to access the relations
            for form in formset:
                question_text = form.cleaned_data["question_text"]
                q = Question(
                    question_text=question_text,
                    morsel = m
                )
                answer = Answer(question=q)
                q.answer.answer_text = form.cleaned_data["answer_text"]
                q.save()
    morsel = get_object_or_404(Morsel.objects.prefetch_related('questions'), pk=morsel_id)
    form = MorselCreationForm(initial={
        "start_time" : morsel.start_time,
        "end_time" : morsel.end_time,
        "name" : morsel.name,
        "welcome_text" : morsel.welcome_text,
        "completed_text" : morsel.completed_text,
        "public_enabled" : morsel.public_enabled
    })
    initial_formset_values = [{"question_text":question.question_text,"answer_text":question.answer.answer_text} \
    for question in morsel.questions.select_related("answer").all()]
    formset = formset_factory(QuestionAnswerCreationForm, extra=1, max_num=len(morsel.questions.all()))(initial=initial_formset_values)
    return render(request, 'app/edit_morsel.html', {'form':form, 'formset':formset})
</code>```

Traceback:

```<code>Environment:

Request Method: GET
Request URL: http://localhost:8000/app/morsels/

Django Version: 1.11.6
Python Version: 3.6.3
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'app.apps.AppConfig',
 'django_extensions',
 'twilio',
 'debug_toolbar',
 'bootstrap3',
 'sass_processor']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'debug_toolbar.middleware.DebugToolbarMiddleware']

Template error:
In template /Users/kiniadit/code/morsels/app/templates/app/base.html, error at line 12
   Reverse for 'morsel_detail' with arguments '(10,)' not found. 1 pattern(s) tried: ['app/morsels/(?P<pk>[0-9])/display/$']   2 : <html><head>
   3 :         <meta charset="utf-8">
   4 :         <meta name="viewport" content="width=device-width, initial-scale=1">
   5 :         <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" type="text/css">s
   6 :
   7 :         <!-- Custom links -->
   8 :          <link href="{% static 'app/css/style.css' %}" rel="stylesheet" type="text/css" />
   9 :         <body>
   10 :         <nav class="navbar navbar-expand-md navbar-dark bg-success">
   11 :           <div class="container">
   12 :             <a  class="navbar-brand" href="/"><img sr c="{% static 'app/images/logo.png' %}"></a>
   13 :             <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbar2SupportedContent" aria-controls="navbar2SupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button>
   14 :             <div class="collapse navbar-collapse text-center justify-content-end" id="navbar2SupportedContent">
   15 :               <ul class="navbar-nav">
   16 :                 <li class="nav-item">
   17 :                   <a class="nav-link text-white" href="{% url 'app:about' %}">About</a>
   18 :                 </li>
   19 :                 <li class="nav-item">
   20 :                   <a class="nav-link text-white" href="{% url 'app:faq' %}">FAQ</a>
   21 :                 </li>
   22 :               </ul>

Traceback:

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  41.             response = get_response(request)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  217.                 response = self.process_exception_by_middleware(e, request)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  215.                 response = response.render()

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/response.py" in render
  107.             self.content = self.rendered_content

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/response.py" in rendered_content
  84.         content = template.render(context, self._request)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/backends/django.py" in render
  66.             return self.template.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render
  207.                     return self._render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/test/utils.py" in instrumented_test_render
  107.     return self.nodelist.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render
  990.                 bit = node.render_annotated(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render_annotated
  957.             return self.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/loader_tags.py" in render
  177.             return compiled_parent._render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/test/utils.py" in instrumented_test_render
  107.     return self.nodelist.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render
  990.                 bit = node.render_annotated(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render_annotated
  957.             return self.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/loader_tags.py" in render
  72.                 result = block.nodelist.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render
  990.                 bit = node.render_annotated(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render_annotated
  957.             return self.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/defaulttags.py" in render
  216.                     nodelist.append(node.render_annotated(context))

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render_annotated
  957.             return self.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/defaulttags.py" in render
  458.             url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/urls/base.py" in reverse
  91.     return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/urls/resolvers.py" in _reverse_with_prefix
  497.         raise NoReverseMatch(msg)

Exception Type: NoReverseMatch at /app/morsels/
Exception Value: Reverse for 'morsel_detail' with arguments '(10,)' not found. 1 pattern(s) tried: ['app/morsels/(?P<pk>[0-9])/display/$']
</code>```

答: In your urls.py, you have:  url(r'^morsels/(?P[0-9])/display/$', MorselDetailView.as_view(), name='morsel_detail'), pk(primary key)means you have to name the parameters pk when you make the request. So as the error shows, you try to send a parameters called the morsel.id which suppose to be the pk, so it raise error,so inside you morsel_list.html file, switch View to View, hope this help you.</p>

Title: No Reverse Match error in Django

Body:
New to Django and stuck on this error. My template was rendering correctly. The only change I made was adding a '1/0' in my views.py file to simulate a breakpoint. And now the template will not render when I remove it.

urls.py

from django.conf.urls import url
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.views import login, logout
from app.views import send_morsel, start_hunt, MorselList, MorselDetailView,\
register, create_morsel, HomePageView, FAQPageView, AboutPageView,\
newsletter_signup, edit_morsel

app_name = 'app'
urlpatterns = [
    url(r'^$', HomePageView.as_view(), name='home'),
    url(r'^morsels/$', MorselList.as_view(), name='morsel_list'),
    url(r'^morsels/send/$', send_morsel, name='morsel_send'),
    url(r'^morsels/(?P<morsel_id>[0-9])/start_hunt/$', start_hunt, name='start_hunt'),
    url(r'^register/', register, name='register'),
    url(r'^faq/$', FAQPageView.as_view(), name='faq'),
    url(r'^about/$', AboutPageView.as_view(), name='about'),
    url(r'^morsels/create/$', create_morsel, name="create_morsel"),
    url(r'^morsels/(?P<morsel_id>[0-9])/edit/$', edit_morsel, name='edit_morsel'),
    url(r'^morsels/(?P<pk>[0-9])/display/$', MorselDetailView.as_view(), name='morsel_detail'),
    url(r'^newsletter_signup/$', newsletter_signup, name='newsletter_signup')
]

morsel_list.html

{% extends "app/base.html" %}
{% load bootstrap3 %}
{% bootstrap_css %}
{% bootstrap_javascript %}
{% bootstrap_messages %}
{% block content %}

Morsels

    {% if user.is_authenticated %}

hello

welcome {{ user.username }}

Logout

    {% else %}

Login

Register

    {% endif %}

        {% for morsel in object_list %}

{{ morsel.name }}
                View
                Edit
                Send!

        {% endfor %}

    {% if messages %}
        {% for msg in messages %}
            {% bootstrap_alert msg.message alert_type=msg.level_tag %}
        {% endfor %}
    {% endif %}
{% endblock %}

Really not sure what to do here.

relevant block from views.py:

def edit_morsel(request, morsel_id=None):
    if request.method == 'POST':
        extra = int(request.session['extra'])
        form = MorselCreationForm(request.POST)
        formset = formset_factory(QuestionAnswerCreationForm, extra=extra)(request.POST)
        if form.is_valid() and formset.is_valid():
            name = form.cleaned_data["name"]
            start_time = form.cleaned_data["start_time"]
            end_time = form.cleaned_data["end_time"]
            welcome_text = form.cleaned_data["welcome_text"]
            completed_text = form.cleaned_data["completed_text"]
            public_enabled = form.cleaned_data["public_enabled"]
            m = Morsel(
                name=name,
                start_time = start_time,
                end_time = end_time,
                welcome_text = welcome_text,
                completed_text = completed_text,
                public_enabled = public_enabled
            )
            m.save()
            # this order is important to be able to access the relations
            for form in formset:
                question_text = form.cleaned_data["question_text"]
                q = Question(
                    question_text=question_text,
                    morsel = m
                )
                answer = Answer(question=q)
                q.answer.answer_text = form.cleaned_data["answer_text"]
                q.save()
    morsel = get_object_or_404(Morsel.objects.prefetch_related('questions'), pk=morsel_id)
    form = MorselCreationForm(initial={
        "start_time" : morsel.start_time,
        "end_time" : morsel.end_time,
        "name" : morsel.name,
        "welcome_text" : morsel.welcome_text,
        "completed_text" : morsel.completed_text,
        "public_enabled" : morsel.public_enabled
    })
    initial_formset_values = [{"question_text":question.question_text,"answer_text":question.answer.answer_text} \
    for question in morsel.questions.select_related("answer").all()]
    formset = formset_factory(QuestionAnswerCreationForm, extra=1, max_num=len(morsel.questions.all()))(initial=initial_formset_values)
    return render(request, 'app/edit_morsel.html', {'form':form, 'formset':formset})

Traceback:

Environment:

Request Method: GET
Request URL: http://localhost:8000/app/morsels/

Django Version: 1.11.6
Python Version: 3.6.3
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'app.apps.AppConfig',
 'django_extensions',
 'twilio',
 'debug_toolbar',
 'bootstrap3',
 'sass_processor']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'debug_toolbar.middleware.DebugToolbarMiddleware']

Template error:
In template /Users/kiniadit/code/morsels/app/templates/app/base.html, error at line 12
   Reverse for 'morsel_detail' with arguments '(10,)' not found. 1 pattern(s) tried: ['app/morsels/(?P<pk>[0-9])/display/$']   2 :
   3 :         <meta charset="utf-8">
   4 :         <meta name="viewport" content="width=device-width, initial-scale=1">
   5 :         <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" type="text/css">s
   6 :
   7 :
   8 :          <link href="{% static 'app/css/style.css' %}" rel="stylesheet" type="text/css" />
   9 :
   10 :
   11 :

   12 :
   13 :             <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbar2SupportedContent" aria-controls="navbar2SupportedContent" aria-expanded="false" aria-label="Toggle navigation">  </button>
   14 :

   15 :

   16 :

   17 :                   About
   18 :

   19 :

   20 :                   FAQ
   21 :

   22 :

Traceback:

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  41.             response = get_response(request)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  217.                 response = self.process_exception_by_middleware(e, request)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  215.                 response = response.render()

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/response.py" in render
  107.             self.content = self.rendered_content

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/response.py" in rendered_content
  84.         content = template.render(context, self._request)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/backends/django.py" in render
  66.             return self.template.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render
  207.                     return self._render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/test/utils.py" in instrumented_test_render
  107.     return self.nodelist.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render
  990.                 bit = node.render_annotated(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render_annotated
  957.             return self.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/loader_tags.py" in render
  177.             return compiled_parent._render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/test/utils.py" in instrumented_test_render
  107.     return self.nodelist.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render
  990.                 bit = node.render_annotated(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render_annotated
  957.             return self.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/loader_tags.py" in render
  72.                 result = block.nodelist.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render
  990.                 bit = node.render_annotated(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render_annotated
  957.             return self.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/defaulttags.py" in render
  216.                     nodelist.append(node.render_annotated(context))

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render_annotated
  957.             return self.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/defaulttags.py" in render
  458.             url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/urls/base.py" in reverse
  91.     return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/urls/resolvers.py" in _reverse_with_prefix
  497.         raise NoReverseMatch(msg)

Exception Type: NoReverseMatch at /app/morsels/
Exception Value: Reverse for 'morsel_detail' with arguments '(10,)' not found. 1 pattern(s) tried: ['app/morsels/(?P<pk>[0-9])/display/$']


问:
Reverse Ajax(Comet) with ASP.NET
I am looking for a basic example of how to implement the Reverse Ajax (Comet) with ASP.NET. I have already looked the below ones and I don't want to use them right now (because they are paid)

http://www.frozenmountain.com/websync/
http://www.lightstreamer.com/demos.htm

I have already gone on various links mentioned on SO . But most of them are pointing towards external API. I am looking for a clear cut example of how to implement that .

答: I have been looking for the same thing and I found https://github.com/nmosafi/aspComet which is opensource (you can contribute to it if you would like).  They have a working sample on the site that you can have a look at.  They have a guy who blogs about some of the design decisions etc that you may find useful (Blog Link)</p>

ContentLicense: CC BY-SA 2.5

Title: Reverse Ajax(Comet) with ASP.NET


问:
ASP.NET MVC SaveChangesAsync throwing DbUpdateException
I'm new to Entityframework in my practice app I'm trying to initialize my newly created database with some sample data and using SaveChangesAsync() but its giving internal server error. When I migrated my DbContext there was no problem and the database created successfully.

EDITED:
after debugging I found SqlException: Cannot insert explicit value for identity column in table 'Packages' when IDENTITY_INSERT is set to OFF what should I do?

DbInitializer

```<code>public class DbContextInitializer
{
    private AppDbContext _context;
    private Data data = new Data();

    public DbContextInitializer(AppDbContext context)
    {
        _context = context;
    }

    public async Task SeedData()
    {
        if (!_context.Packages.Any())
        {
            var pack1 = data.get(1);
            _context.Packages.Add(pack1);

            var pack2 = data.get(2);
            _context.Packages.Add(pack2);

            var pack3 = data.get(3);
            _context.Packages.Add(pack3);

            await _context.SaveChangesAsync();
        }
    }

}
</code>```

DbContext

```<code> public class AppDbContext : DbContext
  {
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {

    }

    public DbSet<TableModel> Packages { get; set; }
  }
</code>```

Configure in Startup.cs

```<code>public void Configure(IApplicationBuilder app,
        IHostingEnvironment env,
        DbContextInitializer seed)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=App}/{action=Index}/{id?}");
        });

        seed.SeedData().Wait();
    }
</code>```

ConfigureServices in Startup.cs

```<code>    public void ConfigureServices(IServiceCollection services)
    {

        services.AddDbContext<AppDbContext>(options => options.UseSqlServer(_configurationroot.GetConnectionString("ConString")));
        services.AddMvc();
        services.AddTransient<ITableData, MockTableData>();
        services.AddTransient<DbContextInitializer>();
    }
</code>```

Error

答:
I'm sorry I cannot see your data but I do know this.  If your primary key is an identity column then you cannot insert data into that column. SQL has control of the data that goes into that column based on your seed and increment value it will start at the seed and increment the value by what you told it to.  Identity (1,1) will get you 1,2,3,4 and so on.  Don't mean to lecture if you already knew.

So you have two options.

Go into your dummy data and remove one column from all the rows. the first column would be a preset ID that you are trying to force into your Identity column.  remove that field and it will go right in there without a hitch.

values (1, milk), (2, bread), (3, vodka) becomes values (milk), (bread), (vodka)

SQL will handle the IDs

or you can turn on Identity insert which tells SQL I want to insert stuff into your Identity column.

here is a link to a Stack exchange post on how to do that for entity framework

How can I force entity framework to insert identity columns?

Of course you could also change your database design to not use an identity column for the primary key which I guess would be option number three.

Body:
I'm new to Entityframework in my practice app I'm trying to initialize my newly created database with some sample data and using SaveChangesAsync() but its giving internal server error. When I migrated my DbContext there was no problem and the database created successfully.

EDITED:
after debugging I found SqlException: Cannot insert explicit value for identity column in table 'Packages' when IDENTITY_INSERT is set to OFF what should I do?

DbInitializer

public class DbContextInitializer
{
    private AppDbContext _context;
    private Data data = new Data();

    public DbContextInitializer(AppDbContext context)
    {
        _context = context;
    }

    public async Task SeedData()
    {
        if (!_context.Packages.Any())
        {
            var pack1 = data.get(1);
            _context.Packages.Add(pack1);

            var pack2 = data.get(2);
            _context.Packages.Add(pack2);

            var pack3 = data.get(3);
            _context.Packages.Add(pack3);

            await _context.SaveChangesAsync();
        }
    }

}

DbContext

 public class AppDbContext : DbContext
  {
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {

    }

    public DbSet<TableModel> Packages { get; set; }
  }

Configure in Startup.cs

public void Configure(IApplicationBuilder app,
        IHostingEnvironment env,
        DbContextInitializer seed)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=App}/{action=Index}/{id?}");
        });

        seed.SeedData().Wait();
    }

ConfigureServices in Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddDbContext<AppDbContext>(options => options.UseSqlServer(_configurationroot.GetConnectionString("ConString")));
        services.AddMvc();
        services.AddTransient<ITableData, MockTableData>();
        services.AddTransient<DbContextInitializer>();
    }

Error


问:
Google Sign In flow with multiple activities
I have an app with 3 activities : a login activity, a main activity and a detail activity.

The login activity uses Google Sign In to get the account of the user (the token id and the email).
Both Main activity and Detail activity need theGoogleSignInAccount.

I don't want to the app to always start on login activity and transparently re-login when the user launch back the app.

I don't want to store the token id and the user email on shared preferences, I'd prefer to manipulate directly aGoogleSignInAccount everywhere in my app.

What is the proper flow to handle this sign in scenario ? Should I try to do a silentSignIn in every screen or is there a better way to store and retrieve the GoogleSignInAccount ?

答:
You can also pass GoogleSignInAccount as extra Intent input:

```<code>GoogleSignInAccount acct = result.getSignInAccount();
Intent intent = new Intent(this, AnotherActivity.class);
intent.putExtra("singedInAccount", acct);
startActivity(intent);
</code>```

and receive it in onCreate() another's activity method as such:

```<code>getIntent().getParcelableExtra("singedInAccount");
</code>```

Notice that you have to use getParcelableExtra() instead of getSerializableExtra() as far as GoogleSignInAccount implements Parcelable and not Serializable interface.

Body:
You can also pass GoogleSignInAccount as extra Intent input:

GoogleSignInAccount acct = result.getSignInAccount();
Intent intent = new Intent(this, AnotherActivity.class);
intent.putExtra("singedInAccount", acct);
startActivity(intent);

and receive it in onCreate() another's activity method as such:

getIntent().getParcelableExtra("singedInAccount");

Notice that you have to use getParcelableExtra() instead of getSerializableExtra() as far as GoogleSignInAccount implements Parcelable and not Serializable interface.


问:
UniWebView message throttling/collision?
I have the following listener setup in my Unity scene:

```<code>ui.OnMessageReceived += (view, message) => {
    var path = message.Path;
    var action = message.Args ["action"];
    if (path == "app") {
        if (action == "log") {
            Debug.Log ("[W] " + message.Args ["text"]);
        }
    }
};
</code>```

And in my web view I have this log function:

```<code>log: function(m) {
    window.location.href = 'uniwebview://app?action=log&text=' + m;
}
</code>```

When I execute the following code, the only output that shows up in logcat are tests 5 and E:

```<code>app.log("Echo Test (1)");
app.log("Echo Test (2)");
app.log("Echo Test (3)");
app.log("Echo Test (4)");
app.log("Echo Test (5)");
setTimeout(function() {
    app.log("Echo Test (A)");
    app.log("Echo Test (B)");
    app.log("Echo Test (C)");
    app.log("Echo Test (D)");
    app.log("Echo Test (E)");
}, 500);
</code>```

```<code>08-16 13:55:20.229 13860 13881 I Unity   : [W] Echo Test (5)
08-16 13:55:20.693 13860 13881 I Unity   : [W] Echo Test (E)
</code>```

What is causing this and how can it be fixed?

答:
Looks like the URL doesn't get time to post to your listener. Your instantly changing the address so it's not executing. You added the timeout which is a sensible thing to do, I suggest you creating a function that waits after each log.

Here is another post having a similar issue that required a time out.

```<code>log: function(m) {
  setTimeout(function(){
     window.location.href = 'uniwebview://app?action=log&text=' + m;
  },500
}
</code>```

I haven't tested this but if you didn't want to use a timer with 500 milliseconds you could probably check to see if the page has finished loading before you execute the next request

```<code>var readyStateCheckInterval = setInterval(function() {
    if (document.readyState === "complete") {
        clearInterval(readyStateCheckInterval);
        init();
    }
}, 10);
</code>```

Body:
I have the following listener setup in my Unity scene:

ui.OnMessageReceived += (view, message) => {
    var path = message.Path;
    var action = message.Args ["action"];
    if (path == "app") {
        if (action == "log") {
            Debug.Log ("[W] " + message.Args ["text"]);
        }
    }
};

And in my web view I have this log function:

log: function(m) {
    window.location.href = 'uniwebview://app?action=log&text=' + m;
}

When I execute the following code, the only output that shows up in logcat are tests 5 and E:

app.log("Echo Test (1)");
app.log("Echo Test (2)");
app.log("Echo Test (3)");
app.log("Echo Test (4)");
app.log("Echo Test (5)");
setTimeout(function() {
    app.log("Echo Test (A)");
    app.log("Echo Test (B)");
    app.log("Echo Test (C)");
    app.log("Echo Test (D)");
    app.log("Echo Test (E)");
}, 500);

08-16 13:55:20.229 13860 13881 I Unity   : [W] Echo Test (5)
08-16 13:55:20.693 13860 13881 I Unity   : [W] Echo Test (E)

What is causing this and how can it be fixed?

Body:
Looks like the URL doesn't get time to post to your listener. Your instantly changing the address so it's not executing. You added the timeout which is a sensible thing to do, I suggest you creating a function that waits after each log.

Here is another post having a similar issue that required a time out.

log: function(m) {
  setTimeout(function(){
     window.location.href = 'uniwebview://app?action=log&text=' + m;
  },500
}

I haven't tested this but if you didn't want to use a timer with 500 milliseconds you could probably check to see if the page has finished loading before you execute the next request

var readyStateCheckInterval = setInterval(function() {
    if (document.readyState === "complete") {
        clearInterval(readyStateCheckInterval);
        init();
    }
}, 10);


问:
Change qt scrollbar style to match default qml scrollbar
How can I have the same style for qt scrollbars than the default one on qml?

Here is a screenshot of the default scrollbar on qt:

And this is the one with qml ScollView component.

答:
There is a workaround, using stylesheet.</p>

```<code>    this->setStyleSheet(QString(
        "QScrollBar:vertical {"
        "    border: 0px solid #c6c6c6;"
        "    background: transparent;"
        "    width: 13px;    "
        "    margin: 0px 0px 0px 0px;"
        "}"
        "QScrollBar:horizontal {"
        "    border: 0px solid #c6c6c6;"
        "    background: transparent;"
        "    height: 13px;    "
        "    margin: 0px 0px 0px 0px;"
        "}"
        "QScrollBar::handle {"
        "    background: #c6c6c6;"
        "    border: 3px solid %1;"
        "    border-radius: 6px;"
        "}"
        "QScrollBar::add-line:vertical {"
        "    height: 0px;"
        "    subcontrol-position: bottom;"
        "    subcontrol-origin: margin;"
        "}"
        "QScrollBar::sub-line:vertical {"
        "    height: 0 px;"
        "    subcontrol-position: top;"
        "    subcontrol-origin: margin;"
        "}"
        "QScrollBar::add-line:horizontal {"
        "    width: 0px;"
        "    subcontrol-position: right;"
        "    subcontrol-origin: margin;"
        "}"
        "QScrollBar::sub-line:horizontal {"
        "    width: 0 px;"
        "    subcontrol-position: left;"
        "    subcontrol-origin: margin;"
        "}").arg(SUPER_LIGHT_GREY));
</code>```

Body:
There is a workaround, using stylesheet.

    this->setStyleSheet(QString(
        "QScrollBar:vertical {"
        "    border: 0px solid #c6c6c6;"
        "    background: transparent;"
        "    width: 13px;    "
        "    margin: 0px 0px 0px 0px;"
        "}"
        "QScrollBar:horizontal {"
        "    border: 0px solid #c6c6c6;"
        "    background: transparent;"
        "    height: 13px;    "
        "    margin: 0px 0px 0px 0px;"
        "}"
        "QScrollBar::handle {"
        "    background: #c6c6c6;"
        "    border: 3px solid %1;"
        "    border-radius: 6px;"
        "}"
        "QScrollBar::add-line:vertical {"
        "    height: 0px;"
        "    subcontrol-position: bottom;"
        "    subcontrol-origin: margin;"
        "}"
        "QScrollBar::sub-line:vertical {"
        "    height: 0 px;"
        "    subcontrol-position: top;"
        "    subcontrol-origin: margin;"
        "}"
        "QScrollBar::add-line:horizontal {"
        "    width: 0px;"
        "    subcontrol-position: right;"
        "    subcontrol-origin: margin;"
        "}"
        "QScrollBar::sub-line:horizontal {"
        "    width: 0 px;"
        "    subcontrol-position: left;"
        "    subcontrol-origin: margin;"
        "}").arg(SUPER_LIGHT_GREY));


问:
Static Library and Swift
So I'm working on an iOS project in Swift, and I wanted to create a Static library with some useful stuff in it.

My problem is when I try to build my lib in Xcode (version 6.3) I have a "Build Failed" followed by : /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool: unknown option character 'X' in: -Xlinker

I've never saw this and it's not my first static lib. So I was thinking I may be linked to the fact that I'm using exclusively Swift class.

What do you guys think ?
Thank you in advance.

答:
As mentioned, Apple does allow Swift in static libraries as of Xcode 9 Beta 4.

We attempted to do this on an existing project with an Objective-C-based target and "child" static library projects and kept running into a linking error

```<code>ld: library not found for -lswiftSwiftOnoneSupport for architecture x86_64
</code>```

also

```<code>ld: library not found for -lswiftDispatch for architecture x86_64
</code>```

This is because the main target (app) is trying to build solely against Objective-C and isn't told by the static library that it needs to include Swift libraries. This was because there weren't any Swift files in the Compile Sources section of our Build Phases for the app target.

So basically all you have to do is add at least one .swift file to that compile list and it will include the Swift libraries for you. It doesn't even need to have any code or values in it, it can be an empty file.

Then you can start adding Swift files to your "child" static library project. I would let it generate the bridging header for you at first then you can move it around and change what gets imported (make sure the project points to the right file in the build settings if you move it).

You should still keep in mind that using Swift and Objective-C within the same static library may have issues of its own. I suggest reading the Apple developer doc "Swift and Objective-C in the Same Project" on how to address importing Objective-C into Swift (using a bridging header) and how to use the Swift files in your Objective-C code (importing the generated -Swift.h for your library).

Title: Static Library and Swift

Body:
As mentioned, Apple does allow Swift in static libraries as of Xcode 9 Beta 4.

We attempted to do this on an existing project with an Objective-C-based target and "child" static library projects and kept running into a linking error

ld: library not found for -lswiftSwiftOnoneSupport for architecture x86_64

also

ld: library not found for -lswiftDispatch for architecture x86_64

This is because the main target (app) is trying to build solely against Objective-C and isn't told by the static library that it needs to include Swift libraries. This was because there weren't any Swift files in the Compile Sources section of our Build Phases for the app target.

So basically all you have to do is add at least one .swift file to that compile list and it will include the Swift libraries for you. It doesn't even need to have any code or values in it, it can be an empty file.

Then you can start adding Swift files to your "child" static library project. I would let it generate the bridging header for you at first then you can move it around and change what gets imported (make sure the project points to the right file in the build settings if you move it).

You should still keep in mind that using Swift and Objective-C within the same static library may have issues of its own. I suggest reading the Apple developer doc "Swift and Objective-C in the Same Project" on how to address importing Objective-C into Swift (using a bridging header) and how to use the Swift files in your Objective-C code (importing the generated -Swift.h for your library).

ContentLicense: CC BY-SA 4.0


问:
How to create One-to-Many and Many-to-One Relationship from one class to another class in Java/IntelliJ
I've done research on how to resolve this issue and none of it worked for me. I know I don't fully understand how it works--which is exactly the point, but sometimes I have to stop and ask for help/clarification.

I am working on a side project (and working on my programming skills). Please note, I am on a junior level.

I am trying to create two classes where one class has several fields that is one to one relationship. There are only two fields that will have 1 to M relationship and M to M relationship. The "Dog" class has a field called picture which will be 1 to M relationship with a "Picture" class. For the life of me, every time I execute the code--it runs into problems. I've tried several ways to make it work-- such as making the class serializable, having one field mapped by another and vice versa, used the CascadeType and many more. I've come to realize perhaps I don't quite understand how it works in Java (I am using IntelliJ), even though I understood the concept of it.

The articles I've read and tried using to name a few:

Entity Framework one-to-many and many-to-many relationship

Multiple 1:many relationship in Hibernate

Java JPA one to many

http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#entity-mapping-association

Hibernate One to Many and Many to One Relation

I have a feeling that I was really close to what I was trying to do...but I seem to overlook something, badly.

The intention of my database:

I'm making each row in the Dog table that has their own name, weight, etc.
Each row (dog) will have many pictures assigned to them. They will be in the form of URL address in the database which I plan to call on it using spring framework. I found Cloudinary and figured I can try to implement their code with mine. This side project of mine is to improve a current, working lab rescue organization that has the most basic website I've ever seen.

Here are my codes:

Dog Table/Class

```<code>package com.claudiazeledon.LuckyLabsRescue.models;

import org.hibernate.annotations.Target;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Collection;
import java.util.Set;

@Entity
public class Dog{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column
    private String name;

    @Column
    private Integer weight;

    @Column
    private Integer age;

    @Column
    private Gender gender;

    @Column
    private String color;

    @OneToOne
    private Temperament temperament;

    @OneToOne
    private Availability availability;

    @OneToOne
    private Health health;

    @OneToMany
    @JoinColumn(name = "picture_dp")
    private Set<Picture> getPictures;

    public Dog() {
    }

    public Dog(int id, String name, Integer weight, Integer age, Gender gender, String color, Temperament temperament, Availability availability, Health health, Set<Picture> getPictures) {
        this.id = id;
        this.name = name;
        this.weight = weight;
        this.age = age;
        this.gender = gender;
        this.color = color;
        this.temperament = temperament;
        this.availability = availability;
        this.health = health;
        this.getPictures = getPictures;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getWeight() {
        return weight;
    }

    public void setWeight(Integer weight) {
        this.weight = weight;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Gender getGender() {
        return gender;
    }

    public void setGender(Gender gender) {
        this.gender = gender;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public Temperament getTemperament() {
        return temperament;
    }

    public void setTemperament(Temperament temperament) {
        this.temperament = temperament;
    }

    public Availability getAvailability() {
        return availability;
    }

    public void setAvailability(Availability availability) {
        this.availability = availability;
    }

    public Health getHealth() {
        return health;
    }

    public void setHealth(Health health) {
        this.health = health;
    }

    public Set<Picture> getGetPictures() {
        return getPictures;
    }

    public void setGetPictures(Set<Picture> getPictures) {
        this.getPictures = getPictures;
    }
}
</code>```

Picture Table/Class

```<code>package com.claudiazeledon.LuckyLabsRescue.models;

import javax.persistence.*;
import java.net.URL;

@Entity
@Table(name = "picture")
public class Picture{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @ManyToOne
    @JoinColumn(name = "picture_dp", insertable = false, updatable = false)
    private URL pictureURL;

//    @ManyToOne
//    @JoinColumn(name = "pictureId")
//    @MapsId("pictureId")
//    private Dog dogImage;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public URL getPictureURL() {
        return pictureURL;
    }

    public void setPictureURL(URL pictureURL) {
        this.pictureURL = pictureURL;
    }

}
</code>```

Error Message from IntelliJ

```<code>2017-11-16 15:20:35.300  INFO 24180 --- [  restartedMain] org.hibernate.Version                    : HHH000412: Hibernate Core {5.0.12.Final}
2017-11-16 15:20:35.301  INFO 24180 --- [  restartedMain] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2017-11-16 15:20:35.302  INFO 24180 --- [  restartedMain] org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
2017-11-16 15:20:35.418  INFO 24180 --- [  restartedMain] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2017-11-16 15:20:35.518  INFO 24180 --- [  restartedMain] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
2017-11-16 15:20:35.623  INFO 24180 --- [  restartedMain] o.h.e.j.e.i.LobCreatorBuilderImpl        : HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
2017-11-16 15:20:35.625  INFO 24180 --- [  restartedMain] org.hibernate.type.BasicTypeRegistry     : HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType@673c77b3
2017-11-16 15:20:35.766  WARN 24180 --- [  restartedMain] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: @OneToOne or @ManyToOne on com.claudiazeledon.LuckyLabsRescue.models.Picture.pictureURL references an unknown entity: java.net.URL
2017-11-16 15:20:35.771  INFO 24180 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2017-11-16 15:20:35.782  INFO 24180 --- [  restartedMain] utoConfigurationReportLoggingInitializer :

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-11-16 15:20:35.792 ERROR 24180 --- [  restartedMain] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: @OneToOne or @ManyToOne on com.claudiazeledon.LuckyLabsRescue.models.Picture.pictureURL references an unknown entity: java.net.URL
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1078) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:857) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at com.claudiazeledon.LuckyLabsRescue.LuckyLabsRescueApplication.main(LuckyLabsRescueApplication.java:10) [classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_144]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_144]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_144]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_144]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-1.5.8.RELEASE.jar:1.5.8.RELEASE]
Caused by: org.hibernate.AnnotationException: @OneToOne or @ManyToOne on com.claudiazeledon.LuckyLabsRescue.models.Picture.pictureURL references an unknown entity: java.net.URL
    at org.hibernate.cfg.ToOneFkSecondPass.doSecondPass(ToOneFkSecondPass.java:97) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processEndOfQueue(InFlightMetadataCollectorImpl.java:1786) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processFkSecondPassesInOrder(InFlightMetadataCollectorImpl.java:1730) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1617) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:278) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:847) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:874) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    ... 21 common frames omitted
</code>```

答:
You put a @ManyToOne relationship on the pictureUrl:

```<code>@ManyToOne
@JoinColumn(name = "picture_dp", insertable = false, updatable = false)
private URL pictureURL;
</code>```

Relationships are established between entities, but URL is not an entity.

The easiest solution is to remove the @ManyToOne and @JoinColumn annotations on that field an replace them with a regular @Column annotation.

```<code>@Column
private URL pictureURL;
</code>```

Body:
I've done research on how to resolve this issue and none of it worked for me. I know I don't fully understand how it works--which is exactly the point, but sometimes I have to stop and ask for help/clarification.

I am working on a side project (and working on my programming skills). Please note, I am on a junior level.

I am trying to create two classes where one class has several fields that is one to one relationship. There are only two fields that will have 1 to M relationship and M to M relationship. The "Dog" class has a field called picture which will be 1 to M relationship with a "Picture" class. For the life of me, every time I execute the code--it runs into problems. I've tried several ways to make it work-- such as making the class serializable, having one field mapped by another and vice versa, used the CascadeType and many more. I've come to realize perhaps I don't quite understand how it works in Java (I am using IntelliJ), even though I understood the concept of it.

The articles I've read and tried using to name a few:

Entity Framework one-to-many and many-to-many relationship

Multiple 1:many relationship in Hibernate

Java JPA one to many

http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#entity-mapping-association

Hibernate One to Many and Many to One Relation

I have a feeling that I was really close to what I was trying to do...but I seem to overlook something, badly.

The intention of my database:

I'm making each row in the Dog table that has their own name, weight, etc.
Each row (dog) will have many pictures assigned to them. They will be in the form of URL address in the database which I plan to call on it using spring framework. I found Cloudinary and figured I can try to implement their code with mine. This side project of mine is to improve a current, working lab rescue organization that has the most basic website I've ever seen.

Here are my codes:

Dog Table/Class

package com.claudiazeledon.LuckyLabsRescue.models;

import org.hibernate.annotations.Target;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Collection;
import java.util.Set;

@Entity
public class Dog{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column
    private String name;

    @Column
    private Integer weight;

    @Column
    private Integer age;

    @Column
    private Gender gender;

    @Column
    private String color;

    @OneToOne
    private Temperament temperament;

    @OneToOne
    private Availability availability;

    @OneToOne
    private Health health;

    @OneToMany
    @JoinColumn(name = "picture_dp")
    private Set<Picture> getPictures;

    public Dog() {
    }

    public Dog(int id, String name, Integer weight, Integer age, Gender gender, String color, Temperament temperament, Availability availability, Health health, Set<Picture> getPictures) {
        this.id = id;
        this.name = name;
        this.weight = weight;
        this.age = age;
        this.gender = gender;
        this.color = color;
        this.temperament = temperament;
        this.availability = availability;
        this.health = health;
        this.getPictures = getPictures;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getWeight() {
        return weight;
    }

    public void setWeight(Integer weight) {
        this.weight = weight;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Gender getGender() {
        return gender;
    }

    public void setGender(Gender gender) {
        this.gender = gender;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public Temperament getTemperament() {
        return temperament;
    }

    public void setTemperament(Temperament temperament) {
        this.temperament = temperament;
    }

    public Availability getAvailability() {
        return availability;
    }

    public void setAvailability(Availability availability) {
        this.availability = availability;
    }

    public Health getHealth() {
        return health;
    }

    public void setHealth(Health health) {
        this.health = health;
    }

    public Set<Picture> getGetPictures() {
        return getPictures;
    }

    public void setGetPictures(Set<Picture> getPictures) {
        this.getPictures = getPictures;
    }
}

Picture Table/Class

package com.claudiazeledon.LuckyLabsRescue.models;

import javax.persistence.*;
import java.net.URL;

@Entity
@Table(name = "picture")
public class Picture{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @ManyToOne
    @JoinColumn(name = "picture_dp", insertable = false, updatable = false)
    private URL pictureURL;

//    @ManyToOne
//    @JoinColumn(name = "pictureId")
//    @MapsId("pictureId")
//    private Dog dogImage;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public URL getPictureURL() {
        return pictureURL;
    }

    public void setPictureURL(URL pictureURL) {
        this.pictureURL = pictureURL;
    }

}

Error Message from IntelliJ

2017-11-16 15:20:35.300  INFO 24180 --- [  restartedMain] org.hibernate.Version                    : HHH000412: Hibernate Core {5.0.12.Final}
2017-11-16 15:20:35.301  INFO 24180 --- [  restartedMain] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2017-11-16 15:20:35.302  INFO 24180 --- [  restartedMain] org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
2017-11-16 15:20:35.418  INFO 24180 --- [  restartedMain] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2017-11-16 15:20:35.518  INFO 24180 --- [  restartedMain] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
2017-11-16 15:20:35.623  INFO 24180 --- [  restartedMain] o.h.e.j.e.i.LobCreatorBuilderImpl        : HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
2017-11-16 15:20:35.625  INFO 24180 --- [  restartedMain] org.hibernate.type.BasicTypeRegistry     : HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType@673c77b3
2017-11-16 15:20:35.766  WARN 24180 --- [  restartedMain] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: @OneToOne or @ManyToOne on com.claudiazeledon.LuckyLabsRescue.models.Picture.pictureURL references an unknown entity: java.net.URL
2017-11-16 15:20:35.771  INFO 24180 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2017-11-16 15:20:35.782  INFO 24180 --- [  restartedMain] utoConfigurationReportLoggingInitializer :

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-11-16 15:20:35.792 ERROR 24180 --- [  restartedMain] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: @OneToOne or @ManyToOne on com.claudiazeledon.LuckyLabsRescue.models.Picture.pictureURL references an unknown entity: java.net.URL
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1078) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:857) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at com.claudiazeledon.LuckyLabsRescue.LuckyLabsRescueApplication.main(LuckyLabsRescueApplication.java:10) [classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_144]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_144]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_144]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_144]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-1.5.8.RELEASE.jar:1.5.8.RELEASE]
Caused by: org.hibernate.AnnotationException: @OneToOne or @ManyToOne on com.claudiazeledon.LuckyLabsRescue.models.Picture.pictureURL references an unknown entity: java.net.URL
    at org.hibernate.cfg.ToOneFkSecondPass.doSecondPass(ToOneFkSecondPass.java:97) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processEndOfQueue(InFlightMetadataCollectorImpl.java:1786) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processFkSecondPassesInOrder(InFlightMetadataCollectorImpl.java:1730) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1617) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:278) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:847) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:874) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    ... 21 common frames omitted

Body:
You put a @ManyToOne relationship on the pictureUrl:

@ManyToOne
@JoinColumn(name = "picture_dp", insertable = false, updatable = false)
private URL pictureURL;

Relationships are established between entities, but URL is not an entity.

The easiest solution is to remove the @ManyToOne and @JoinColumn annotations on that field an replace them with a regular @Column annotation.

@Column
private URL pictureURL;


问:
Does it matter where I initialize my integer?
I'm trying to understand something. I'm still a beginner to c++ and I just created this little program where you input a value and it tells you whether it's even or odd. To do this, I made an integer called "result" which takes value, and then does % 2 operation.

However, my first mistake was that I put int result above "cin >> value" so for some reason that messed up the program and the number would always be even no matter what. Then when I put int result below "cin >> value" the program worked like it should. Why is it doing this?

Any help would be appreciated thank you. I apologize if this is a duplicate but I don't know what to search for.

```<code>#include <iostream>
#include <string>
#include "Human.h"
#include <ctime>
using namespace std;

int main() {

    int value = 0; // where I input
    cin >> value;
    // if you put int result above cin program changes.
    int result = value % 2;

    if (result == 0) {
        cout << "Even number." << endl;
    }
    else {
        cout << "Odd number." << endl;
    }

    return 0;
}
</code>```

答:
Any code whichever programming language you use runs from top to bottom.
You need to first declare the variable, give it a value and then check for being even or odd.

When you used cin after setting the value of result = value%2; the compiler used the originally initialized value for value which is 0 to compute the value of result which will be 0%2.

That's why you need to use cin>>value; before setting result = value%2;.

Body:
I'm trying to understand something. I'm still a beginner to c++ and I just created this little program where you input a value and it tells you whether it's even or odd. To do this, I made an integer called "result" which takes value, and then does % 2 operation.

However, my first mistake was that I put int result above "cin >> value" so for some reason that messed up the program and the number would always be even no matter what. Then when I put int result below "cin >> value" the program worked like it should. Why is it doing this?

Any help would be appreciated thank you. I apologize if this is a duplicate but I don't know what to search for.

#include <iostream>
#include <string>
#include "Human.h"
#include <ctime>
using namespace std;

int main() {

    int value = 0; // where I input
    cin >> value;
    // if you put int result above cin program changes.
    int result = value % 2;

    if (result == 0) {
        cout << "Even number." << endl;
    }
    else {
        cout << "Odd number." << endl;
    }

    return 0;
}