问:
First time deploying a django app on Heroku and I'm facing 2 issues, solution?
I've worked on my social app and been able to deploy it and I'm having 2 problems:
Link: https://network50web.herokuapp.com/
1/It directs me autmatically to https://network50web.herokuapp.com/accounts/login/?next=/ and I'm only able to see the site if I write the routes manually in the address bar like(login, register)

2/When I try to login it with my existent username it throws error "Programming Error at /login

relation "auth_user" does not exist
LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user..." and it highlights this line "            user = User.objects.create_user(username, email, password)" even when I try to register a new account
I used SQL for the database
Views:

```<code>from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect, request
from django.http.response import JsonResponse
from django.shortcuts import render, redirect, resolve_url, get_object_or_404
from django.urls import reverse, reverse_lazy
from django.core import serializers
from django.core.paginator import Paginator
from django.contrib import messages
from django.contrib.auth.models import User
from django.db.models import Q
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from itertools import chain

from .models import Relationship, Post, Profile, Like
from django.views.generic import TemplateView, View, UpdateView, DeleteView, ListView, DetailView
from .forms import ProfileModelForm, PostModelForm, CommentModelForm

def search_view(request):
    if request.method == "POST":
        searched = request.POST['searched']
        profiles = Profile.objects.filter(slug__contains=searched)
        return render(request, 'network/search.html',
        {'searched':searched,
        'profiles':profiles})
    else:
        return render(request, 'network/search.html',
        {})

class ProfileDetailView(LoginRequiredMixin, DetailView):
    model = Profile
    template_name = 'network/profile.html'
    success_url = reverse_lazy('profile-view')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        user = User.objects.get(username__iexact=self.request.user)
        profile = Profile.objects.get(user=user)
        rel_r = Relationship.objects.filter(sender=profile)
        rel_s = Relationship.objects.filter(receiver=profile)
        rel_receiver = []
        rel_sender = []
        for item in rel_r:
            rel_receiver.append(item.receiver.user)
        for item in rel_s:
            rel_sender.append(item.sender.user)

        context["rel_receiver"] = rel_receiver
        context["rel_sender"] = rel_sender
        context["posts"] = self.get_object().get_all_authors_posts()
        context["len_posts"] = True if len(self.get_object().get_all_authors_posts()) > 0 else False

        return context

@login_required
def profile_view(request):
    profile = Profile.objects.get(user=request.user)
    form = ProfileModelForm(request.POST or None, request.FILES or None, instance=profile)
    confirm = False

    if request.method == 'POST':
        if form.is_valid():
            form.save()
            confirm = True

    context = {
        'profile': profile,
        'form': form,
        'confirm': confirm,
    }

    return render(request, 'network/profile.html', context)

@login_required
def invites_received_view(request):
    profile = Profile.objects.get(user=request.user)
    qs = Relationship.objects.invitations_received(profile)
    results = list(map(lambda x: x.sender, qs))
    is_empty = False
    if len(results) == 0:
        is_empty = True

    context = {
        'qs':results,
        'is_empty': is_empty,
    }

    return render(request, 'network/invites.html', context)

@login_required
def accept_invitation(request):
    if request.method =='POST':
        pk = request.POST.get('profile_pk')
        sender = Profile.objects.get(pk=pk)
        receiver = Profile.objects.get(user=request.user)
        rel = get_object_or_404(Relationship, sender=sender, receiver=receiver)
        if rel.status == 'send':
            rel.status = 'accepted'
            rel.save()

    return redirect('invites-view')

@login_required
def reject_invitation(request):
    if request.method=="POST":
        pk = request.POST.get('profile_pk')
        receiver = Profile.objects.get(user=request.user)
        sender = Profile.objects.get(pk=pk)
        rel = get_object_or_404(Relationship, sender=sender, receiver=receiver)
        rel.delete()
    return redirect('invites-view')

@login_required
def invite_profiles_list_view(request):
    user = request.user
    qs = Profile.objects.get_all_profiles_to_invite(user)

    context = {'qs': qs}

    return render(request, 'network/to_invite_list.html', context)

@login_required
def profiles_list_view(request):
    user = request.user
    qs = Profile.objects.get_all_profiles(user)

    context = {'qs': qs}

    return render(request, 'network/profile_list.html', context)

class ProfileListView(LoginRequiredMixin, ListView):
    model = Profile
    template_name = 'network/profile_list.html'
    #context_object_name = 'qs'

    def get_queryset(self):
        qs = Profile.objects.get_all_profiles(self.request.user)
        return qs

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        user = User.objects.get(username__iexact=self.request.user)
        profile = Profile.objects.get(user=user)
        rel_r = Relationship.objects.filter(sender=profile)
        rel_s = Relationship.objects.filter(receiver=profile)
        rel_receiver = []
        rel_sender = []
        for item in rel_r:
            rel_receiver.append(item.receiver.user)
        for item in rel_s:
            rel_sender.append(item.sender.user)
        context["rel_receiver"] = rel_receiver
        context["rel_sender"] = rel_sender
        context["is_empty"] = False
        if len(self.get_queryset()) == 0:
            context["is_empty"] = True

        return context

@login_required
def send_invitation(request):
    if request.method == 'POST':
        pk = request.POST.get('profile_pk')
        user = request.user
        sender = Profile.objects.get(user=user)
        receiver = Profile.objects.get(pk=pk)

        rel = Relationship.objects.create(sender=sender, receiver=receiver, status='send')

        return redirect(request.META.get('HTTP_REFERER'))
    return redirect('profile')

@login_required
def remove_friends(request):
    if request.method == 'POST':
        pk = request.POST.get('profile_pk')
        user = request.user
        sender = Profile.objects.get(user=user)
        receiver = Profile.objects.get(pk=pk)

        rel = Relationship.objects.get(
            (Q(sender=sender) & Q(receiver=receiver)) | (Q(sender=receiver) & Q(receiver=sender))
        )
        rel.delete()
        return redirect(request.META.get('HTTP_REFERER'))
    return redirect('profile')

@login_required
def like_unlike_post(request):
    user = request.user
    if request.method == 'POST':
        post_id = request.POST.get('post_id')
        post_obj = Post.objects.get(id=post_id)
        profile = Profile.objects.get(user=user)

        if profile in post_obj.liked.all():
            post_obj.liked.remove(profile)
        else:
            post_obj.liked.add(profile)

        like, created = Like.objects.get_or_create(user=profile, post_id=post_id)

        if not created:
            if like.value=='Like':
                like.value='Unlike'
            else:
                like.value='Like'
        else:
            like.value='Unlike'

            post_obj.save()
            like.save()

        data = {
            'value': like.value,
            'likes': post_obj.liked.all().count()
        }
        return JsonResponse(data, safe=False)
    return redirect('posts')

@login_required
def post_comment_create_view(request):
    qs = Post.objects.all()
    profile = Profile.objects.get(user=request.user)

    #Setting up pagination
    p = Paginator(qs, 5)
    page = request.GET.get('page')
    post_list = p.get_page(page)

    #Post form, comment form
    p_form = PostModelForm()
    c_form = CommentModelForm()
    post_added = False

    profile = Profile.objects.get(user=request.user)

    if 'submit_pForm' in request.POST:
        print(request.POST)
        p_form = PostModelForm(request.POST, request.FILES)
        if p_form.is_valid():
            instance = p_form.save(commit=False)
            instance.author = profile
            instance.save()
            p_form = PostModelForm()
            post_added = True

    if 'submit_cForm' in request.POST:
        c_form = CommentModelForm(request.POST)
        if c_form.is_valid():
            instance = c_form.save(commit=False)
            instance.user = profile
            instance.post = Post.objects.get(id=request.POST.get('post_id'))
            instance.save()
            c_form = CommentModelForm()

    context = {
        'qs': qs,
        'profile': profile,
        'p_form': p_form,
        'c_form': c_form,
        'post_added': post_added,
        'post_list': post_list,
    }

    return render(request, 'network/posts.html', context)

@login_required
def posts_of_following_profiles(request):

    profile = Profile.objects.get(user=request.user)
    users = [user for user in profile.following.all()]
    posts = []
    qs = None

    for u in users:
        p = Profile.objects.get(user=u)
        p_posts = p.post_set.all()
        posts.append(p_posts)

    my_posts = profile.get_my_posts()
    posts.append(my_posts)
    if len(posts) > 0:
            my_posts = sorted(chain(*posts), reverse=True, key=lambda obj: obj.created)

    #Setting up pagination
    p = Paginator(my_posts, 5)
    page = request.GET.get('page')
    post_list = p.get_page(page)

    #Post form, comment form
    p_form = PostModelForm()
    c_form = CommentModelForm()
    post_added = False

    if 'submit_pForm' in request.POST:
        print(request.POST)
        p_form = PostModelForm(request.POST, request.FILES)
        if p_form.is_valid():
            instance = p_form.save(commit=False)
            instance.author = profile
            instance.save()
            p_form = PostModelForm()
            post_added = True

    if 'submit_cForm' in request.POST:
        c_form = CommentModelForm(request.POST)
        if c_form.is_valid():
            instance = c_form.save(commit=False)
            instance.user = profile
            instance.post = Post.objects.get(id=request.POST.get('post_id'))
            instance.save()
            c_form = CommentModelForm()

    context = {
        'posts': qs,
        'profile': profile,
        'p_form': p_form,
        'c_form': c_form,
        'post_added': post_added,
        'post_list': post_list,
    }

    return render(request, 'network/followers_posts.html', context)

class PostDeleteView(LoginRequiredMixin, DeleteView):
    model = Post
    template_name = 'network/confirmDelete.html'
    success_url = reverse_lazy('posts')

    def get_object(self, *args, **kwargs):
        pk = self.kwargs.get('pk')
        obj = Post.objects.get(pk=pk)
        if not obj.author.user == self.request.user:
            messages.warning(self.request, 'You need to be the owner of the post in order to delete it!')
        return obj

class PostUpdateView(LoginRequiredMixin, UpdateView):
    form_class = PostModelForm
    model = Post
    template_name = 'network/update.html'
    success_url = reverse_lazy('posts')

    def form_valid(self, form):
        profile = Profile.objects.get(user=self.request.user)
        if form.instance.author == profile:
            return super().form_valid(form)
        else:
            form.add_error(None, "You need to be the owner of the post in order to update it!")
            return super().form_invalid(form)

def login_view(request):
    if request.method == "POST":

        # Attempt to sign user in
        username = request.POST["username"]
        password = request.POST["password"]
        user = authenticate(request, username=username, password=password)

        # Check if authentication successful
        if user is not None:
            login(request, user)
            return HttpResponseRedirect(reverse("posts"))
        else:
            return render(request, "network/login.html", {
                "message": "Invalid username and/or password."
            })
    else:
        return render(request, "network/login.html")

def logout_view(request):
    logout(request)
    return HttpResponseRedirect(reverse("login"))

def register(request):
    if request.method == "POST":
        username = request.POST["username"]
        email = request.POST["email"]

        # Ensure password matches confirmation
        password = request.POST["password"]
        confirmation = request.POST["confirmation"]
        if password != confirmation:
            return render(request, "network/register.html", {
                "message": "Passwords must match."
            })

        # Attempt to create new user
        try:
            user = User.objects.create_user(username, email, password)
            user.save()
        except IntegrityError:
            return render(request, "network/register.html", {
                "message": "Username already taken."
            })
        login(request, user)
        return HttpResponseRedirect(reverse("all-profiles-view"))
    else:
        return render(request, "network/register.html")
</code>```

URLs:

```<code>
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static

from . import views
from .views import (
    posts_of_following_profiles,
    like_unlike_post,
    invites_received_view,
    invite_profiles_list_view,
    send_invitation,
    remove_friends,
    accept_invitation,
    reject_invitation,
    search_view,
    post_comment_create_view,
    login_view,
    logout_view,
    register,

    ProfileDetailView,
    PostDeleteView,
    PostUpdateView,
    ProfileListView,
    #EditProfileView,
)

urlpatterns = [
    path("", ProfileListView.as_view(), name="all-profiles-view"),
    path("posts/", views.post_comment_create_view, name="posts"),
    path("posts-follow/", posts_of_following_profiles, name="posts-follow"),
    path("login", views.login_view, name="login"),
    path("logout", views.logout_view, name="logout"),
    path("register", views.register, name="register"),
    path("liked/", like_unlike_post, name="like-post-view"),
    path("<pk>/delete", PostDeleteView.as_view(), name="post-delete"),
    path("<pk>/update", PostUpdateView.as_view(), name="post-update"),
    path("invites/", invites_received_view, name="invites-view"),
    path("send-invite/", send_invitation, name="send-invite"),
    path("remove-friend/", remove_friends, name="remove-friend"),
    path("invites/accept/", accept_invitation, name="accept-invite"),
    path("invites/reject/", reject_invitation, name="reject-invite"),
    path("to-invite/", invite_profiles_list_view, name='invite-profiles-view'),
    path("search/", views.search_view, name='search-view'),
    path("<slug>", ProfileDetailView.as_view(), name="profile-view"),
]

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

Models:

```<code>from django.contrib.auth.models import User
from django.core import validators
from django.db import models
from itertools import chain
import random
from django.db.models.aggregates import Max
from django.shortcuts import reverse

from django.db.models.deletion import CASCADE
from .utils import get_random_code
from django.template.defaultfilters import slugify
from django.core.validators import FileExtensionValidator
from django.db.models import Q

class ProfileManager(models.Manager):

    def get_all_profiles_to_invite(self, sender):
        profiles = Profile.objects.all().exclude(user=sender)
        profile = Profile.objects.get(user=sender)
        qs = Relationship.objects.filter(Q(sender=profile) | Q(receiver=profile))

        accepted = set([])
        for rel in qs:
            if rel.status == 'accepted':
                accepted.add(rel.receiver)
                accepted.add(rel.sender)
        print(accepted)

        available = [profile for profile in profiles if profile not in accepted]

        return available

    def get_all_profiles(self, me):
        profiles = Profile.objects.all().exclude(user=me)
        return profiles

class Profile(models.Model):
    first_name = models.CharField(max_length=64, blank=True)
    last_name = models.CharField(max_length=64, blank=True)
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    country = models.CharField(max_length=64, blank=True)
    avatar = models.ImageField(upload_to='avatars', default='avatar.png')
    background = models.ImageField(upload_to='backgrounds', default='background.png')
    following = models.ManyToManyField(User, related_name='following', blank=True)
    bio = models.TextField(default="No Bio..")
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)
    slug = models.SlugField(unique=True, blank=True)

    objects = ProfileManager()

    def __str__(self):
        return f"{self.user.username}"

    def get_absolute_url(self):
        return reverse("profile-view", kwargs={"slug": self.slug})

    __initial_first_name = None
    __initial_last_name = None

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__initial_first_name = self.first_name
        self.__initial_last_name = self.last_name

    def save(self, *args, **kwargs):
        ex = False
        to_slug = self.slug
        if self.first_name != self.__initial_first_name or self.last_name != self.__initial_last_name or self.slug=="":
            if self.first_name and self.last_name:
                to_slug = slugify(str(self.first_name) + " " + str(self.last_name))
                ex = Profile.objects.filter(slug=to_slug).exists()
                while ex:
                    to_slug = slugify(to_slug + " " + str(get_random_code()))
                    ex = Profile.objects.filter(slug=to_slug).exists()
            else:
                to_slug = str(self.user)
        self.slug = to_slug
        super().save(*args, **kwargs)

    def get_followers(self):
        return self.following.all()

    def get_followers_num(self):
        return self.following.all().count()

    def get_my_posts(self):
        return self.post_set.all()

    def get_country(self):
        return self.post_set.all()

    def get_following_users(self):
        following_list = [p for p in self.get_following()]
        return following_list

    def get_followers_users(self):
        following_list = [p for p in self.get_followers()]
        return following_list

    def get_all_posts(self):
        users = [user for user in self.get_following()]
        posts = []
        qs = None
        for u in users:
            p = Profile.objects.get(user=u)
            p_posts = p.post_set.all()
            posts.append(p_posts)
        my_posts = self.post_set.all()
        posts.append(my_posts)
        if len(posts) > 0:
            qs = sorted(chain(*posts), reverse=True, key=lambda obj: obj.created)
        return qs

    def get_posts_num(self):
        return self.post_set.all().count()

    def get_all_authors_posts(self):
        return self.post_set.all()

    def get_likes_given_num(self):
        likes = self.like_set.all()
        total_liked = 0
        for item in likes:
            if item.value == 'Like':
                total_liked += 1
        return total_liked

    def get_likes_received_num(self):
        posts = self.post_set.all()
        total_liked = 0
        for item in posts:
            total_liked += item.all().count()
        return total_liked

    def get_proposals_for_following(self):
        profiles = Profile.objects.all().exclude(user=self.user)
        followers_list = [p for p in self.get_following()]
        available = [p.user for p in profiles if p.user not in followers_list]
        random.shuffle(available)
        return available[:3]

STATUS_CHOICES = (
    ('send', 'send'),
    ('accepted', 'accepted')
)

class RelationshipManager(models.Manager):
    def invitations_received(self, receiver):
        qs = Relationship.objects.filter(receiver=receiver, status='send')
        return qs

class Relationship(models.Model):
    sender = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='sender')
    receiver = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='receiver')
    status = models.CharField(max_length=8, choices=STATUS_CHOICES)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    objects = RelationshipManager()

    def __str__(self):
        return f"{self.sender}-{self.receiver}-{self.status}"

class Post(models.Model):
    # id is created automatically by Django
    picture = models.ImageField(upload_to='images', blank=True, validators=[FileExtensionValidator(['png', 'jpg', 'jpeg'])])
    content = models.TextField()
    liked = models.ManyToManyField(Profile, blank=True, related_name="likes")
    author = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('-created',)

    def __str__ (self):
        return str(self.content[:20])

    def num_likes(self):
        return self.liked.all().count()

    @property
    def like_count(self):
        return self.liked.all().count()

    def get_user_liked(self, user):
        pass

    # Number of comments
    def num_comments(self):
        return self.comment_set.all.count()

class Comment(models.Model):
    user = models.ForeignKey(Profile, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    body = models.TextField(max_length=250)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.pk)

LIKE_CHOICES = (
    ('Like', 'Like'),
    ('Unlike', 'Unlike'),
)

class Like(models.Model):
    user = models.ForeignKey(Profile, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    value = models.CharField(choices=LIKE_CHOICES, max_length=8)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.user}-{self.post}-{self.value}"

    def like_numb(self):
        return self.like.all().count()
</code>```

Settings:

```<code>import os
import django_heroku
import dj_database_url
from decouple import config
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = secretkey

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'crispy_forms',
    'network',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.humanize',
]

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',
    'whitenoise.middleware.WhiteNoiseMiddleware',
]

ROOT_URLCONF = 'project4.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': (BASE_DIR, 'network/templates'),
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'project4.wsgi.application'

# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3')
    }
}

# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

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

STATIC_URL = 'network/static/'
STATICFILES_DIRS = (BASE_DIR, 'network/static')

STATICFILES_STORAGE = 'whitenoise.storage.CompressManifestStaticFilesStorage'

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')

DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'

django_heroku.settings(locals())
</code>```

答:
First you've to set your LOGIN_URL and LOGIN_REDIRECT_URL inside your settings.py file like this

```<code>LOGIN_URL = '/login'
LOGIN_REDIRECT_URL = '/'
</code>```

Second login to your heroku cli and run this command

```<code>$ heroku run bash
</code>```

this will open a bash for you from there you can access your project files
you've to navigate to your project root dir (where manage.py lies) and then run these two commands

```<code>$ python manage.py makemigrations network
$ python manage.py migrate
$ python manage.py createsuperuser
</code>```

Body:
I've worked on my social app and been able to deploy it and I'm having 2 problems:
Link: https://network50web.herokuapp.com/
1/It directs me autmatically to https://network50web.herokuapp.com/accounts/login/?next=/ and I'm only able to see the site if I write the routes manually in the address bar like(login, register)

2/When I try to login it with my existent username it throws error "Programming Error at /login

relation "auth_user" does not exist
LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user..." and it highlights this line "            user = User.objects.create_user(username, email, password)" even when I try to register a new account
I used SQL for the database
Views:

from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect, request
from django.http.response import JsonResponse
from django.shortcuts import render, redirect, resolve_url, get_object_or_404
from django.urls import reverse, reverse_lazy
from django.core import serializers
from django.core.paginator import Paginator
from django.contrib import messages
from django.contrib.auth.models import User
from django.db.models import Q
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from itertools import chain

from .models import Relationship, Post, Profile, Like
from django.views.generic import TemplateView, View, UpdateView, DeleteView, ListView, DetailView
from .forms import ProfileModelForm, PostModelForm, CommentModelForm

def search_view(request):
    if request.method == "POST":
        searched = request.POST['searched']
        profiles = Profile.objects.filter(slug__contains=searched)
        return render(request, 'network/search.html',
        {'searched':searched,
        'profiles':profiles})
    else:
        return render(request, 'network/search.html',
        {})

class ProfileDetailView(LoginRequiredMixin, DetailView):
    model = Profile
    template_name = 'network/profile.html'
    success_url = reverse_lazy('profile-view')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        user = User.objects.get(username__iexact=self.request.user)
        profile = Profile.objects.get(user=user)
        rel_r = Relationship.objects.filter(sender=profile)
        rel_s = Relationship.objects.filter(receiver=profile)
        rel_receiver = []
        rel_sender = []
        for item in rel_r:
            rel_receiver.append(item.receiver.user)
        for item in rel_s:
            rel_sender.append(item.sender.user)

        context["rel_receiver"] = rel_receiver
        context["rel_sender"] = rel_sender
        context["posts"] = self.get_object().get_all_authors_posts()
        context["len_posts"] = True if len(self.get_object().get_all_authors_posts()) > 0 else False

        return context

@login_required
def profile_view(request):
    profile = Profile.objects.get(user=request.user)
    form = ProfileModelForm(request.POST or None, request.FILES or None, instance=profile)
    confirm = False

    if request.method == 'POST':
        if form.is_valid():
            form.save()
            confirm = True

    context = {
        'profile': profile,
        'form': form,
        'confirm': confirm,
    }

    return render(request, 'network/profile.html', context)

@login_required
def invites_received_view(request):
    profile = Profile.objects.get(user=request.user)
    qs = Relationship.objects.invitations_received(profile)
    results = list(map(lambda x: x.sender, qs))
    is_empty = False
    if len(results) == 0:
        is_empty = True

    context = {
        'qs':results,
        'is_empty': is_empty,
    }

    return render(request, 'network/invites.html', context)

@login_required
def accept_invitation(request):
    if request.method =='POST':
        pk = request.POST.get('profile_pk')
        sender = Profile.objects.get(pk=pk)
        receiver = Profile.objects.get(user=request.user)
        rel = get_object_or_404(Relationship, sender=sender, receiver=receiver)
        if rel.status == 'send':
            rel.status = 'accepted'
            rel.save()

    return redirect('invites-view')

@login_required
def reject_invitation(request):
    if request.method=="POST":
        pk = request.POST.get('profile_pk')
        receiver = Profile.objects.get(user=request.user)
        sender = Profile.objects.get(pk=pk)
        rel = get_object_or_404(Relationship, sender=sender, receiver=receiver)
        rel.delete()
    return redirect('invites-view')

@login_required
def invite_profiles_list_view(request):
    user = request.user
    qs = Profile.objects.get_all_profiles_to_invite(user)

    context = {'qs': qs}

    return render(request, 'network/to_invite_list.html', context)

@login_required
def profiles_list_view(request):
    user = request.user
    qs = Profile.objects.get_all_profiles(user)

    context = {'qs': qs}

    return render(request, 'network/profile_list.html', context)

class ProfileListView(LoginRequiredMixin, ListView):
    model = Profile
    template_name = 'network/profile_list.html'
    #context_object_name = 'qs'

    def get_queryset(self):
        qs = Profile.objects.get_all_profiles(self.request.user)
        return qs

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        user = User.objects.get(username__iexact=self.request.user)
        profile = Profile.objects.get(user=user)
        rel_r = Relationship.objects.filter(sender=profile)
        rel_s = Relationship.objects.filter(receiver=profile)
        rel_receiver = []
        rel_sender = []
        for item in rel_r:
            rel_receiver.append(item.receiver.user)
        for item in rel_s:
            rel_sender.append(item.sender.user)
        context["rel_receiver"] = rel_receiver
        context["rel_sender"] = rel_sender
        context["is_empty"] = False
        if len(self.get_queryset()) == 0:
            context["is_empty"] = True

        return context

@login_required
def send_invitation(request):
    if request.method == 'POST':
        pk = request.POST.get('profile_pk')
        user = request.user
        sender = Profile.objects.get(user=user)
        receiver = Profile.objects.get(pk=pk)

        rel = Relationship.objects.create(sender=sender, receiver=receiver, status='send')

        return redirect(request.META.get('HTTP_REFERER'))
    return redirect('profile')

@login_required
def remove_friends(request):
    if request.method == 'POST':
        pk = request.POST.get('profile_pk')
        user = request.user
        sender = Profile.objects.get(user=user)
        receiver = Profile.objects.get(pk=pk)

        rel = Relationship.objects.get(
            (Q(sender=sender) & Q(receiver=receiver)) | (Q(sender=receiver) & Q(receiver=sender))
        )
        rel.delete()
        return redirect(request.META.get('HTTP_REFERER'))
    return redirect('profile')

@login_required
def like_unlike_post(request):
    user = request.user
    if request.method == 'POST':
        post_id = request.POST.get('post_id')
        post_obj = Post.objects.get(id=post_id)
        profile = Profile.objects.get(user=user)

        if profile in post_obj.liked.all():
            post_obj.liked.remove(profile)
        else:
            post_obj.liked.add(profile)

        like, created = Like.objects.get_or_create(user=profile, post_id=post_id)

        if not created:
            if like.value=='Like':
                like.value='Unlike'
            else:
                like.value='Like'
        else:
            like.value='Unlike'

            post_obj.save()
            like.save()

        data = {
            'value': like.value,
            'likes': post_obj.liked.all().count()
        }
        return JsonResponse(data, safe=False)
    return redirect('posts')

@login_required
def post_comment_create_view(request):
    qs = Post.objects.all()
    profile = Profile.objects.get(user=request.user)

    #Setting up pagination
    p = Paginator(qs, 5)
    page = request.GET.get('page')
    post_list = p.get_page(page)

    #Post form, comment form
    p_form = PostModelForm()
    c_form = CommentModelForm()
    post_added = False

    profile = Profile.objects.get(user=request.user)

    if 'submit_pForm' in request.POST:
        print(request.POST)
        p_form = PostModelForm(request.POST, request.FILES)
        if p_form.is_valid():
            instance = p_form.save(commit=False)
            instance.author = profile
            instance.save()
            p_form = PostModelForm()
            post_added = True

    if 'submit_cForm' in request.POST:
        c_form = CommentModelForm(request.POST)
        if c_form.is_valid():
            instance = c_form.save(commit=False)
            instance.user = profile
            instance.post = Post.objects.get(id=request.POST.get('post_id'))
            instance.save()
            c_form = CommentModelForm()

    context = {
        'qs': qs,
        'profile': profile,
        'p_form': p_form,
        'c_form': c_form,
        'post_added': post_added,
        'post_list': post_list,
    }

    return render(request, 'network/posts.html', context)

@login_required
def posts_of_following_profiles(request):

    profile = Profile.objects.get(user=request.user)
    users = [user for user in profile.following.all()]
    posts = []
    qs = None

    for u in users:
        p = Profile.objects.get(user=u)
        p_posts = p.post_set.all()
        posts.append(p_posts)

    my_posts = profile.get_my_posts()
    posts.append(my_posts)
    if len(posts) > 0:
            my_posts = sorted(chain(*posts), reverse=True, key=lambda obj: obj.created)

    #Setting up pagination
    p = Paginator(my_posts, 5)
    page = request.GET.get('page')
    post_list = p.get_page(page)

    #Post form, comment form
    p_form = PostModelForm()
    c_form = CommentModelForm()
    post_added = False

    if 'submit_pForm' in request.POST:
        print(request.POST)
        p_form = PostModelForm(request.POST, request.FILES)
        if p_form.is_valid():
            instance = p_form.save(commit=False)
            instance.author = profile
            instance.save()
            p_form = PostModelForm()
            post_added = True

    if 'submit_cForm' in request.POST:
        c_form = CommentModelForm(request.POST)
        if c_form.is_valid():
            instance = c_form.save(commit=False)
            instance.user = profile
            instance.post = Post.objects.get(id=request.POST.get('post_id'))
            instance.save()
            c_form = CommentModelForm()

    context = {
        'posts': qs,
        'profile': profile,
        'p_form': p_form,
        'c_form': c_form,
        'post_added': post_added,
        'post_list': post_list,
    }

    return render(request, 'network/followers_posts.html', context)

class PostDeleteView(LoginRequiredMixin, DeleteView):
    model = Post
    template_name = 'network/confirmDelete.html'
    success_url = reverse_lazy('posts')

    def get_object(self, *args, **kwargs):
        pk = self.kwargs.get('pk')
        obj = Post.objects.get(pk=pk)
        if not obj.author.user == self.request.user:
            messages.warning(self.request, 'You need to be the owner of the post in order to delete it!')
        return obj

class PostUpdateView(LoginRequiredMixin, UpdateView):
    form_class = PostModelForm
    model = Post
    template_name = 'network/update.html'
    success_url = reverse_lazy('posts')

    def form_valid(self, form):
        profile = Profile.objects.get(user=self.request.user)
        if form.instance.author == profile:
            return super().form_valid(form)
        else:
            form.add_error(None, "You need to be the owner of the post in order to update it!")
            return super().form_invalid(form)

def login_view(request):
    if request.method == "POST":

        # Attempt to sign user in
        username = request.POST["username"]
        password = request.POST["password"]
        user = authenticate(request, username=username, password=password)

        # Check if authentication successful
        if user is not None:
            login(request, user)
            return HttpResponseRedirect(reverse("posts"))
        else:
            return render(request, "network/login.html", {
                "message": "Invalid username and/or password."
            })
    else:
        return render(request, "network/login.html")

def logout_view(request):
    logout(request)
    return HttpResponseRedirect(reverse("login"))

def register(request):
    if request.method == "POST":
        username = request.POST["username"]
        email = request.POST["email"]

        # Ensure password matches confirmation
        password = request.POST["password"]
        confirmation = request.POST["confirmation"]
        if password != confirmation:
            return render(request, "network/register.html", {
                "message": "Passwords must match."
            })

        # Attempt to create new user
        try:
            user = User.objects.create_user(username, email, password)
            user.save()
        except IntegrityError:
            return render(request, "network/register.html", {
                "message": "Username already taken."
            })
        login(request, user)
        return HttpResponseRedirect(reverse("all-profiles-view"))
    else:
        return render(request, "network/register.html")

URLs:

from django.urls import path
from django.conf import settings
from django.conf.urls.static import static

from . import views
from .views import (
    posts_of_following_profiles,
    like_unlike_post,
    invites_received_view,
    invite_profiles_list_view,
    send_invitation,
    remove_friends,
    accept_invitation,
    reject_invitation,
    search_view,
    post_comment_create_view,
    login_view,
    logout_view,
    register,

    ProfileDetailView,
    PostDeleteView,
    PostUpdateView,
    ProfileListView,
    #EditProfileView,
)

urlpatterns = [
    path("", ProfileListView.as_view(), name="all-profiles-view"),
    path("posts/", views.post_comment_create_view, name="posts"),
    path("posts-follow/", posts_of_following_profiles, name="posts-follow"),
    path("login", views.login_view, name="login"),
    path("logout", views.logout_view, name="logout"),
    path("register", views.register, name="register"),
    path("liked/", like_unlike_post, name="like-post-view"),
    path("<pk>/delete", PostDeleteView.as_view(), name="post-delete"),
    path("<pk>/update", PostUpdateView.as_view(), name="post-update"),
    path("invites/", invites_received_view, name="invites-view"),
    path("send-invite/", send_invitation, name="send-invite"),
    path("remove-friend/", remove_friends, name="remove-friend"),
    path("invites/accept/", accept_invitation, name="accept-invite"),
    path("invites/reject/", reject_invitation, name="reject-invite"),
    path("to-invite/", invite_profiles_list_view, name='invite-profiles-view'),
    path("search/", views.search_view, name='search-view'),
    path("<slug>", ProfileDetailView.as_view(), name="profile-view"),
]

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Models:

from django.contrib.auth.models import User
from django.core import validators
from django.db import models
from itertools import chain
import random
from django.db.models.aggregates import Max
from django.shortcuts import reverse

from django.db.models.deletion import CASCADE
from .utils import get_random_code
from django.template.defaultfilters import slugify
from django.core.validators import FileExtensionValidator
from django.db.models import Q

class ProfileManager(models.Manager):

    def get_all_profiles_to_invite(self, sender):
        profiles = Profile.objects.all().exclude(user=sender)
        profile = Profile.objects.get(user=sender)
        qs = Relationship.objects.filter(Q(sender=profile) | Q(receiver=profile))

        accepted = set([])
        for rel in qs:
            if rel.status == 'accepted':
                accepted.add(rel.receiver)
                accepted.add(rel.sender)
        print(accepted)

        available = [profile for profile in profiles if profile not in accepted]

        return available

    def get_all_profiles(self, me):
        profiles = Profile.objects.all().exclude(user=me)
        return profiles

class Profile(models.Model):
    first_name = models.CharField(max_length=64, blank=True)
    last_name = models.CharField(max_length=64, blank=True)
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    country = models.CharField(max_length=64, blank=True)
    avatar = models.ImageField(upload_to='avatars', default='avatar.png')
    background = models.ImageField(upload_to='backgrounds', default='background.png')
    following = models.ManyToManyField(User, related_name='following', blank=True)
    bio = models.TextField(default="No Bio..")
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)
    slug = models.SlugField(unique=True, blank=True)

    objects = ProfileManager()

    def __str__(self):
        return f"{self.user.username}"

    def get_absolute_url(self):
        return reverse("profile-view", kwargs={"slug": self.slug})

    __initial_first_name = None
    __initial_last_name = None

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__initial_first_name = self.first_name
        self.__initial_last_name = self.last_name

    def save(self, *args, **kwargs):
        ex = False
        to_slug = self.slug
        if self.first_name != self.__initial_first_name or self.last_name != self.__initial_last_name or self.slug=="":
            if self.first_name and self.last_name:
                to_slug = slugify(str(self.first_name) + " " + str(self.last_name))
                ex = Profile.objects.filter(slug=to_slug).exists()
                while ex:
                    to_slug = slugify(to_slug + " " + str(get_random_code()))
                    ex = Profile.objects.filter(slug=to_slug).exists()
            else:
                to_slug = str(self.user)
        self.slug = to_slug
        super().save(*args, **kwargs)

    def get_followers(self):
        return self.following.all()

    def get_followers_num(self):
        return self.following.all().count()

    def get_my_posts(self):
        return self.post_set.all()

    def get_country(self):
        return self.post_set.all()

    def get_following_users(self):
        following_list = [p for p in self.get_following()]
        return following_list

    def get_followers_users(self):
        following_list = [p for p in self.get_followers()]
        return following_list

    def get_all_posts(self):
        users = [user for user in self.get_following()]
        posts = []
        qs = None
        for u in users:
            p = Profile.objects.get(user=u)
            p_posts = p.post_set.all()
            posts.append(p_posts)
        my_posts = self.post_set.all()
        posts.append(my_posts)
        if len(posts) > 0:
            qs = sorted(chain(*posts), reverse=True, key=lambda obj: obj.created)
        return qs

    def get_posts_num(self):
        return self.post_set.all().count()

    def get_all_authors_posts(self):
        return self.post_set.all()

    def get_likes_given_num(self):
        likes = self.like_set.all()
        total_liked = 0
        for item in likes:
            if item.value == 'Like':
                total_liked += 1
        return total_liked

    def get_likes_received_num(self):
        posts = self.post_set.all()
        total_liked = 0
        for item in posts:
            total_liked += item.all().count()
        return total_liked

    def get_proposals_for_following(self):
        profiles = Profile.objects.all().exclude(user=self.user)
        followers_list = [p for p in self.get_following()]
        available = [p.user for p in profiles if p.user not in followers_list]
        random.shuffle(available)
        return available[:3]

STATUS_CHOICES = (
    ('send', 'send'),
    ('accepted', 'accepted')
)

class RelationshipManager(models.Manager):
    def invitations_received(self, receiver):
        qs = Relationship.objects.filter(receiver=receiver, status='send')
        return qs

class Relationship(models.Model):
    sender = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='sender')
    receiver = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='receiver')
    status = models.CharField(max_length=8, choices=STATUS_CHOICES)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    objects = RelationshipManager()

    def __str__(self):
        return f"{self.sender}-{self.receiver}-{self.status}"

class Post(models.Model):
    # id is created automatically by Django
    picture = models.ImageField(upload_to='images', blank=True, validators=[FileExtensionValidator(['png', 'jpg', 'jpeg'])])
    content = models.TextField()
    liked = models.ManyToManyField(Profile, blank=True, related_name="likes")
    author = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('-created',)

    def __str__ (self):
        return str(self.content[:20])

    def num_likes(self):
        return self.liked.all().count()

    @property
    def like_count(self):
        return self.liked.all().count()

    def get_user_liked(self, user):
        pass

    # Number of comments
    def num_comments(self):
        return self.comment_set.all.count()

class Comment(models.Model):
    user = models.ForeignKey(Profile, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    body = models.TextField(max_length=250)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.pk)

LIKE_CHOICES = (
    ('Like', 'Like'),
    ('Unlike', 'Unlike'),
)

class Like(models.Model):
    user = models.ForeignKey(Profile, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    value = models.CharField(choices=LIKE_CHOICES, max_length=8)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.user}-{self.post}-{self.value}"

    def like_numb(self):
        return self.like.all().count()

Settings:

import os
import django_heroku
import dj_database_url
from decouple import config
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = secretkey

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'crispy_forms',
    'network',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.humanize',
]

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',
    'whitenoise.middleware.WhiteNoiseMiddleware',
]

ROOT_URLCONF = 'project4.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': (BASE_DIR, 'network/templates'),
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'project4.wsgi.application'

# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3')
    }
}

# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

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

STATIC_URL = 'network/static/'
STATICFILES_DIRS = (BASE_DIR, 'network/static')

STATICFILES_STORAGE = 'whitenoise.storage.CompressManifestStaticFilesStorage'

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')

DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'

django_heroku.settings(locals())

Body:
First you've to set your LOGIN_URL and LOGIN_REDIRECT_URL inside your settings.py file like this

LOGIN_URL = '/login'
LOGIN_REDIRECT_URL = '/'

Second login to your heroku cli and run this command

$ heroku run bash

this will open a bash for you from there you can access your project files
you've to navigate to your project root dir (where manage.py lies) and then run these two commands

$ python manage.py makemigrations network
$ python manage.py migrate
$ python manage.py createsuperuser


来源: stackexchange

问:
When I union two datasets in Snowflake SQL, Should the length, Scale and precision be exactly same between two tables?
```<code>Table 1
ID value  DataType
001    A    VARCHAR(10)
002    A    VARCHAR(10)
003    B    VARCHAR(10)
004    C    VARCHAR(10)

Table 1
ID value  DataType
001    A    VARCHAR(100)
002    A    VARCHAR(100)
003    B    VARCHAR(100)
004    C    VARCHAR(100)
</code>```

Will the Union in Snowflake be safe, if the datatype is same but the length, scale and precision differs between two tables?

答:
You don't have to worry about string lengths, but you do have to watch out for numeric scale and precision when doing unions. Here's an example:

```<code>create or replace table TABLE_A(MY_NUM number(38,0));
create or replace table TABLE_B(MY_NUM number(38,37));

insert into TABLE_A (MY_NUM) values (12345);
insert into TABLE_B (MY_NUM) values (1.23456789);

select * from TABLE_A
union all
select * from TABLE_B
</code>```

Running this will give you the error:

Number out of representable range: type FIXEDSB16{nullable}, value 12345

In this case, the optimizer can't win. If it casts that column to NUMBER(38,0) then the value in TABLE_B would be truncated silently. If it casts to NUMBER(38,37), then it cannot represent a number with more than one place before the decimal point as stored in TABLE_A.

If you make sure the optimizer can always find a way to reconcile the precisions and scales for the column, it will be safe. If there is a possibility that one table's column can hold a value that the other table cannot, it may not be safe. If there is a standoff situation like the example here where two or more tables have values other tables in the union cannot represent then it's unsafe.

ContentLicense: CC BY-SA 4.0

Body:
Table 1
ID value  DataType
001    A    VARCHAR(10)
002    A    VARCHAR(10)
003    B    VARCHAR(10)
004    C    VARCHAR(10)

Table 1
ID value  DataType
001    A    VARCHAR(100)
002    A    VARCHAR(100)
003    B    VARCHAR(100)
004    C    VARCHAR(100)

Will the Union in Snowflake be safe, if the datatype is same but the length, scale and precision differs between two tables?

Body:
You don't have to worry about string lengths, but you do have to watch out for numeric scale and precision when doing unions. Here's an example:

create or replace table TABLE_A(MY_NUM number(38,0));
create or replace table TABLE_B(MY_NUM number(38,37));

insert into TABLE_A (MY_NUM) values (12345);
insert into TABLE_B (MY_NUM) values (1.23456789);

select * from TABLE_A
union all
select * from TABLE_B

Running this will give you the error:

Number out of representable range: type FIXEDSB16{nullable}, value 12345

In this case, the optimizer can't win. If it casts that column to NUMBER(38,0) then the value in TABLE_B would be truncated silently. If it casts to NUMBER(38,37), then it cannot represent a number with more than one place before the decimal point as stored in TABLE_A.

If you make sure the optimizer can always find a way to reconcile the precisions and scales for the column, it will be safe. If there is a possibility that one table's column can hold a value that the other table cannot, it may not be safe. If there is a standoff situation like the example here where two or more tables have values other tables in the union cannot represent then it's unsafe.


问:
django_filters recursive filtering
so I have a django filter that looks like this:

```<code>class ModelFilter(FilterSet):
    user_name = CharFilter(method="some_method")
    boss = ModelChoiceFilter(...)
</code>```

My model looks simillar to this:

```<code>class Employee(Model):
username = Charfield(...)
boss = ForeignKey("self", ''')
</code>```

So an employee can be the boss of another employee. Now, this filter will return the correct queryset based on what values the user is searching for. Let's say we have three objects:

```<code>O1= Employee(usename="u1", boss=None)
O2= Employee(usename="u2", boss=O1)
O3= Employee(usename="u3", boss=O2)
</code>```

If I apply the above mentioned filter on this data, and search for boss=O1 I will get the Object O2 as a result. I want to add a new boolean field in the filter, let's say "with_subordinates", that will return the whole "tree" relationship if it is true. So for instance if I would search for: boss=O1, with_subordinates=True, the resulte should be O2 and O3. Basically, with this new option, the filter should recursively show the employees, of previous employees and so forth.

Is there a way to achieve something like this?

答:
Apart from core concepts, we will do it the pythonic way. For this, we need to get the all objects and their boss_id from the database.

```<code>boss_object_ids = [1,] # this is the input boss id
have_to_wait = True

while have_to_wait:
    prev_ids = boss_object_ids
    if Employee.objects.filter(boss__in=boss_object_ids).count() > 0:

        boss_ids_list = Employee.objects.filter(boss__in=boss_object_ids).values_list('id', flat=True)
        boss_object_ids.extend(boss_ids_list)
        boss_object_ids = list(set(boss_object_ids))
        if set(boss_object_ids) == set(prev_ids):
            have_to_wait = False
all_subordinates = Employee.objects.filter(boss__in=boss_object_ids)

</code>```

Explanation:

At first time we pass input boss_id = [1,] or some integer.

The second time it will loop and find 2,3,4,5 are the ids, hence the list will be [1,2,3,4,5].

The third time it will get 2,3,4,1,6 ids, hence the list will be [1,2,3,4,5,6].

Like wise it will filter until it gets the same list again.

That means, in this example, it will check if there is no extra number other than [1,2,3,4,5,6].

At last, we can filter using the boss_object_ids list. This is the desired all subordinates id's list.

Title: django_filters recursive filtering

Body:
so I have a django filter that looks like this:

class ModelFilter(FilterSet):
    user_name = CharFilter(method="some_method")
    boss = ModelChoiceFilter(...)

My model looks simillar to this:

class Employee(Model):
username = Charfield(...)
boss = ForeignKey("self", ''')

So an employee can be the boss of another employee. Now, this filter will return the correct queryset based on what values the user is searching for. Let's say we have three objects:

O1= Employee(usename="u1", boss=None)
O2= Employee(usename="u2", boss=O1)
O3= Employee(usename="u3", boss=O2)

If I apply the above mentioned filter on this data, and search for boss=O1 I will get the Object O2 as a result. I want to add a new boolean field in the filter, let's say "with_subordinates", that will return the whole "tree" relationship if it is true. So for instance if I would search for: boss=O1, with_subordinates=True, the resulte should be O2 and O3. Basically, with this new option, the filter should recursively show the employees, of previous employees and so forth.

Is there a way to achieve something like this?

Body:
Apart from core concepts, we will do it the pythonic way. For this, we need to get the all objects and their boss_id from the database.

boss_object_ids = [1,] # this is the input boss id
have_to_wait = True

while have_to_wait:
    prev_ids = boss_object_ids
    if Employee.objects.filter(boss__in=boss_object_ids).count() > 0:

        boss_ids_list = Employee.objects.filter(boss__in=boss_object_ids).values_list('id', flat=True)
        boss_object_ids.extend(boss_ids_list)
        boss_object_ids = list(set(boss_object_ids))
        if set(boss_object_ids) == set(prev_ids):
            have_to_wait = False
all_subordinates = Employee.objects.filter(boss__in=boss_object_ids)

Explanation:

At first time we pass input boss_id = [1,] or some integer.

The second time it will loop and find 2,3,4,5 are the ids, hence the list will be [1,2,3,4,5].

The third time it will get 2,3,4,1,6 ids, hence the list will be [1,2,3,4,5,6].

Like wise it will filter until it gets the same list again.

That means, in this example, it will check if there is no extra number other than [1,2,3,4,5,6].

At last, we can filter using the boss_object_ids list. This is the desired all subordinates id's list.


问:
Why does Bash allocate extra array spots if I have dashes in entries?
I tell Bash (v4.4) to give me an array, and I ask how long it is:

$ list=(one two three four)
$ echo ${#list}
3
```
<p>Why are there so many more entries if I have <code>-</code> in some words?</p>
<pre class="lang-sh prettyprint-override"><code>$ list=(one-two three-four)
$ echo ${#list}
7
</code>```

If I ask for the items, most of them are empty. All the ones with values are first, despite the (apparently) odd behavior with - in words.

$ for ix in $(seq 0 ${#list}); do
>     echo "- ${list[$ix]}"
> done
- one-two
- three-four
-
-
-
-
-
```

What is going on?

答:
"One-two" has seven characters. You find the length of the list array with echo ${#list[@]}.

echo ${#list} gives you the string length of the first list element. For Bash, i recommend the following cheatsheet: https://devhints.io/bash

Body:
I tell Bash (v4.4) to give me an array, and I ask how long it is:

$ list=(one two three four)
$ echo ${#list}
3

Why are there so many more entries if I have - in some words?

$ list=(one-two three-four)
$ echo ${#list}
7

If I ask for the items, most of them are empty. All the ones with values are first, despite the (apparently) odd behavior with - in words.

$ for ix in $(seq 0 ${#list}); do
>     echo "- ${list[$ix]}"
> done
- one-two
- three-four
-
-
-
-
-

What is going on?


问:
could not execute support code to read Objective-C class data in the process. at real iPhone device
when this objective-c based method call in Simulator, it doesn't matter.
But in real iPhone device, it occurs Thread 1: signal SIGABRT

warning: could not execute support code to read Objective-C class data in the process. This may reduce the quality of type information available.

here is code

```<code>+ (NSData *)aesDecrypt:(NSURL *)url :(NSString *)key {

NSData *data = [NSData dataWithContentsOfURL: url];
if (data == nil) {
    NSLog(@"file not found");
    return nil;
}

char keyPtr[kCCKeySizeAES128];
bzero(keyPtr, sizeof(keyPtr));

[key getCString:keyPtr maxLength:sizeof(keyPtr)];

size_t bufferSize = [data length] + kCCBlockSizeAES128;
size_t decryptedBytesSize = 0;

void *buffer = malloc(bufferSize);

CCCryptorStatus result = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding, keyPtr, kCCKeySizeAES128, keyPtr, [data bytes],
        [data length], buffer, bufferSize, &decryptedBytesSize);

NSData *decrypted = [NSData dataWithBytes:buffer length:bufferSize];

NSError *error;

if (kCCSuccess != result) {
    NSLog(@"aes decrypt error");
    return nil;
}

return decrypted;
}
</code>```

I tried to fix that code several types.

return other types.

save NSData to files, and return nothing. read it in swift.

All of my tries can't fix the problems: No problem in Simulator, death in real device - iPhone 6 with iOS 11.3.1

EDIT) attach screenshot: Other Linker Flags

答:
the error of my code was that I set the class not to the whole file, but to the main view

correct place

wrong place

Body:
when this objective-c based method call in Simulator, it doesn't matter.
But in real iPhone device, it occurs Thread 1: signal SIGABRT

warning: could not execute support code to read Objective-C class data in the process. This may reduce the quality of type information available.

here is code

+ (NSData *)aesDecrypt:(NSURL *)url :(NSString *)key {

NSData *data = [NSData dataWithContentsOfURL: url];
if (data == nil) {
    NSLog(@"file not found");
    return nil;
}

char keyPtr[kCCKeySizeAES128];
bzero(keyPtr, sizeof(keyPtr));

[key getCString:keyPtr maxLength:sizeof(keyPtr)];

size_t bufferSize = [data length] + kCCBlockSizeAES128;
size_t decryptedBytesSize = 0;

void *buffer = malloc(bufferSize);

CCCryptorStatus result = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding, keyPtr, kCCKeySizeAES128, keyPtr, [data bytes],
        [data length], buffer, bufferSize, &decryptedBytesSize);

NSData *decrypted = [NSData dataWithBytes:buffer length:bufferSize];

NSError *error;

if (kCCSuccess != result) {
    NSLog(@"aes decrypt error");
    return nil;
}

return decrypted;
}

I tried to fix that code several types.

return other types.

save NSData to files, and return nothing. read it in swift.

All of my tries can't fix the problems: No problem in Simulator, death in real device - iPhone 6 with iOS 11.3.1

EDIT) attach screenshot: Other Linker Flags


问:
Find element that's on the middle of the visible screen (viewport) to target another element
What I am aiming to achieve is something that looks like this. you can see it in action on this URL, if you scroll a bit.

I was thinking at first to try using inViewport, and every time a heading or a paragraph is in viewport to show one image and hide the previous. but my problem is that the elements are in viewport in conjunction

This is the initial code I was using:

```<code>      $.fn.isInViewport = function () {
      let elementTop = $(this).offset().top;
      let elementBottom = elementTop + $(this).outerHeight();
      let viewportTop = $(window).scrollTop();
      let viewportBottom = viewportTop + window.innerHeight; // <-- here
      return elementBottom > viewportTop && elementTop < viewportBottom;
      };
     $(window).scroll(function () {
     if ($('.heading1 ').isInViewport()) {
     //  Use .blogcard instead of this
     $('.img1').addClass('show');
     } else {
     //  Remove class
     $('.img1').removeClass('show');
     }
    if ($('.heading2 ').isInViewport()) {
    //  Use .blogcard instead of this
    $('.img2').addClass('show');
    } else {
    //  Remove class
    $('.img2').removeClass('show');
    }
    });
</code>```

I have found this answer but have no idea on how can I use is to my benefits.

I have also stumbled upon this solution, which looks even smarter, but the code adds the classes to the selector in viewport and not to a different element.

This is the code applied there:

```<code>ar getElementsInArea = (function(docElm){
var viewportHeight = docElm.clientHeight;
return function(e, opts){
    var found = [], i;
    if( e && e.type == 'resize' )
        viewportHeight = docElm.clientHeight;
    for( i = opts.elements.length; i--; ){
        var elm        = opts.elements[i],
            pos        = elm.getBoundingClientRect(),
            topPerc    = pos.top    / viewportHeight * 100,
            bottomPerc = pos.bottom / viewportHeight * 100,
            middle     = (topPerc + bottomPerc)/2,
            inViewport = middle > opts.zone[1] &&
                         middle < (100-opts.zone[1]);
        elm.classList.toggle(opts.markedClass, inViewport);
        if( inViewport )
            found.push(elm);
    }
};
})(document.documentElement);
////////////////////////////////////
// How to use:
window.addEventListener('scroll', f)
window.addEventListener('resize', f)
function f(e){
getElementsInArea(e, {
    elements    : document.querySelectorAll('div'),
    markedClass : 'highlight--1',
    zone        : [20, 20] // percentage distance from top & bottom
});
getElementsInArea(e, {
    elements    : document.querySelectorAll('div'),
    markedClass : 'highlight--2',
    zone        : [40, 40] // percentage distance from top & bottom
});
}
</code>```

Would love all the help I could get. Cheers

答:
Using the IntersectionObserver API

It should be quite simple by using the IntersectionObserver API to watch for your elements intersecting the viewport, or any other (Options root) ancestor.

To detect an element reaches the viewport vertical center can be done by passing the Option rootMargin where the bottom and top values are set at -50%, with an Option threshold set to 0 (as soon as one pixel enters that intersecting area)

// Utility functions:

const EL = (sel, par) => (par || document).querySelector(sel);
const ELS = (sel, par) => (par || document).querySelectorAll(sel);

// App:

const ELS_pictures = ELS(".picture");

const switchPicture = (EL_entry) => {
  const EL_picTarg = EL(EL_entry.dataset.reveal);
  ELS_pictures.forEach(EL_pic => EL_pic.classList.toggle("is-active", EL_pic === EL_picTarg));
};

// In Viewport
const inViewport = (entries, observer) => entries.forEach(entry => entry.isIntersecting && switchPicture(entry.target));

// Assign observer to all Elements with data-reveal attribute (Articles)
ELS("[data-reveal]").forEach(el => {
  const observer = new IntersectionObserver(inViewport, {
    // root: (by default is Document),
    rootMargin: "-50% 0px -50% 0px", // set the root intersecting area as a tiny line in the vertical center
    threshold: 0, // 0 = as soon as 1px intersects
  });
  observer.observe(el);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* QuickReset */

* {
  margin: 0;
  box-sizing: border-box;
}

body {
  font: 18px/1.5 sans-serif;
}

.stickers {
  display: grid;
  grid-template-columns: 2fr 3fr;
  max-width: 1000px;
  margin: 0 auto;
}

/* Article Component */

.articles {
  display: flex;
  flex-direction: column;
}

.article {
  margin: 100px 0;
  padding: 30px;
}

.pictures {
  position: sticky;
  display: flex;
  top: 0px;
  right: 0;
  height: 100vh;
  background: #444;
}

.picture {
  position: absolute;
  height: 100%;
  width: 100%;
  object-fit: cover;
  margin: auto;
  transition: 0.3s opacity, 0.5s transform;
  opacity: 0;
  transform: scale(0.8);
}

.picture.is-active {
  opacity: 1;
  transform: scale(1);
}</code>```

Scroll down...

Many cats

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Optio laudantium perferendis eius iusto vitae eaque, eligendi ullam, rerum maiores, totam velit! Debitis repudiandae aliquam placeat, minus. Facere nihil aspernatur nam!

Little cat

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur perferendis possimus asperiores deleniti voluptatum amet nostrum ratione odio, a perspiciatis suscipit ab nulla repellat laudantium praesentium adipisci! Nihil ex, quos!

Snowcat

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur perferendis possimus asperiores deleniti voluptatum amet nostrum ratione odio, a perspiciatis suscipit ab nulla repellat laudantium praesentium adipisci! Nihil ex, quos!

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur perferendis possimus asperiores deleniti voluptatum amet nostrum ratione odio, a perspiciatis suscipit ab nulla repellat laudantium praesentium adipisci! Nihil ex, quos!

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur perferendis possimus asperiores deleniti voluptatum amet nostrum ratione odio, a perspiciatis suscipit ab nulla repellat laudantium praesentium adipisci! Nihil ex, quos!

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur perferendis possimus asperiores deleniti voluptatum amet nostrum ratione odio, a perspiciatis suscipit ab nulla repellat laudantium praesentium adipisci! Nihil ex, quos!

Cat

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aut recusandae doloribus laboriosam, quasi aspernatur modi illum voluptate dicta alias optio, omnis qui deserunt. Quisquam, beatae dolores cum nostrum sint minima!

Etc...
```

Use data-* Attribute on your articles Elements where the value should match the selector of the related picture.

Toggle a class i.e: .is-active using classList that will determine the active styles for the matching picture Element

To make the fixed effect use position: sticky on your pictures  parent element.

Body:
What I am aiming to achieve is something that looks like this. you can see it in action on this URL, if you scroll a bit.

I was thinking at first to try using inViewport, and every time a heading or a paragraph is in viewport to show one image and hide the previous. but my problem is that the elements are in viewport in conjunction

This is the initial code I was using:

      $.fn.isInViewport = function () {
      let elementTop = $(this).offset().top;
      let elementBottom = elementTop + $(this).outerHeight();
      let viewportTop = $(window).scrollTop();
      let viewportBottom = viewportTop + window.innerHeight; // <-- here
      return elementBottom > viewportTop && elementTop < viewportBottom;
      };
     $(window).scroll(function () {
     if ($('.heading1 ').isInViewport()) {
     //  Use .blogcard instead of this
     $('.img1').addClass('show');
     } else {
     //  Remove class
     $('.img1').removeClass('show');
     }
    if ($('.heading2 ').isInViewport()) {
    //  Use .blogcard instead of this
    $('.img2').addClass('show');
    } else {
    //  Remove class
    $('.img2').removeClass('show');
    }
    });

I have found this answer but have no idea on how can I use is to my benefits.

I have also stumbled upon this solution, which looks even smarter, but the code adds the classes to the selector in viewport and not to a different element.

This is the code applied there:

ar getElementsInArea = (function(docElm){
var viewportHeight = docElm.clientHeight;
return function(e, opts){
    var found = [], i;
    if( e && e.type == 'resize' )
        viewportHeight = docElm.clientHeight;
    for( i = opts.elements.length; i--; ){
        var elm        = opts.elements[i],
            pos        = elm.getBoundingClientRect(),
            topPerc    = pos.top    / viewportHeight * 100,
            bottomPerc = pos.bottom / viewportHeight * 100,
            middle     = (topPerc + bottomPerc)/2,
            inViewport = middle > opts.zone[1] &&
                         middle < (100-opts.zone[1]);
        elm.classList.toggle(opts.markedClass, inViewport);
        if( inViewport )
            found.push(elm);
    }
};
})(document.documentElement);
////////////////////////////////////
// How to use:
window.addEventListener('scroll', f)
window.addEventListener('resize', f)
function f(e){
getElementsInArea(e, {
    elements    : document.querySelectorAll('div'),
    markedClass : 'highlight--1',
    zone        : [20, 20] // percentage distance from top & bottom
});
getElementsInArea(e, {
    elements    : document.querySelectorAll('div'),
    markedClass : 'highlight--2',
    zone        : [40, 40] // percentage distance from top & bottom
});
}

Would love all the help I could get. Cheers

Body:
Using the IntersectionObserver API

It should be quite simple by using the IntersectionObserver API to watch for your elements intersecting the viewport, or any other (Options root) ancestor.

To detect an element reaches the viewport vertical center can be done by passing the Option rootMargin where the bottom and top values are set at -50%, with an Option threshold set to 0 (as soon as one pixel enters that intersecting area)

// Utility functions:

const EL = (sel, par) => (par || document).querySelector(sel);
const ELS = (sel, par) => (par || document).querySelectorAll(sel);

// App:

const ELS_pictures = ELS(".picture");

const switchPicture = (EL_entry) => {
  const EL_picTarg = EL(EL_entry.dataset.reveal);
  ELS_pictures.forEach(EL_pic => EL_pic.classList.toggle("is-active", EL_pic === EL_picTarg));
};

// In Viewport
const inViewport = (entries, observer) => entries.forEach(entry => entry.isIntersecting && switchPicture(entry.target));

// Assign observer to all Elements with data-reveal attribute (Articles)
ELS("[data-reveal]").forEach(el => {
  const observer = new IntersectionObserver(inViewport, {
    // root: (by default is Document),
    rootMargin: "-50% 0px -50% 0px", // set the root intersecting area as a tiny line in the vertical center
    threshold: 0, // 0 = as soon as 1px intersects
  });
  observer.observe(el);
});

/* QuickReset */

* {
  margin: 0;
  box-sizing: border-box;
}

body {
  font: 18px/1.5 sans-serif;
}

.stickers {
  display: grid;
  grid-template-columns: 2fr 3fr;
  max-width: 1000px;
  margin: 0 auto;
}

/* Article Component */

.articles {
  display: flex;
  flex-direction: column;
}

.article {
  margin: 100px 0;
  padding: 30px;
}

.pictures {
  position: sticky;
  display: flex;
  top: 0px;
  right: 0;
  height: 100vh;
  background: #444;
}

.picture {
  position: absolute;
  height: 100%;
  width: 100%;
  object-fit: cover;
  margin: auto;
  transition: 0.3s opacity, 0.5s transform;
  opacity: 0;
  transform: scale(0.8);
}

.picture.is-active {
  opacity: 1;
  transform: scale(1);
}

<p style="height: 80vh;">Scroll down...</p>

<div class="stickers">
  <div class="articles">
    <div class="article" data-reveal="#picture_1">
      <h1>Many cats</h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Optio laudantium perferendis eius iusto vitae eaque, eligendi ullam, rerum maiores, totam velit! Debitis repudiandae aliquam placeat, minus. Facere nihil aspernatur nam!</p>
    </div>
    <div class="article" data-reveal="#picture_2">
      <h1>Little cat</h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur perferendis possimus asperiores deleniti voluptatum amet nostrum ratione odio, a perspiciatis suscipit ab nulla repellat laudantium praesentium adipisci! Nihil ex, quos!</p>
    </div>
    <div class="article" data-reveal="#picture_3">
      <h1>Snowcat</h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur perferendis possimus asperiores deleniti voluptatum amet nostrum ratione odio, a perspiciatis suscipit ab nulla repellat laudantium praesentium adipisci! Nihil ex, quos!</p>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur perferendis possimus asperiores deleniti voluptatum amet nostrum ratione odio, a perspiciatis suscipit ab nulla repellat laudantium praesentium adipisci! Nihil ex, quos!</p>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur perferendis possimus asperiores deleniti voluptatum amet nostrum ratione odio, a perspiciatis suscipit ab nulla repellat laudantium praesentium adipisci! Nihil ex, quos!</p>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur perferendis possimus asperiores deleniti voluptatum amet nostrum ratione odio, a perspiciatis suscipit ab nulla repellat laudantium praesentium adipisci! Nihil ex, quos!</p>
    </div>
    <div class="article" data-reveal="#picture_4">
      <h1>Cat</h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aut recusandae doloribus laboriosam, quasi aspernatur modi illum voluptate dicta alias optio, omnis qui deserunt. Quisquam, beatae dolores cum nostrum sint minima!</p>
    </div>
  </div>
  <div class="pictures">
    <img class="picture is-active" id="picture_1" src="https://placekitten.com/380/300" alt="Catz!">
    <img class="picture" id="picture_2" src="https://placekitten.com/460/400" alt="Catz!">
    <img class="picture" id="picture_3" src="https://placekitten.com/400/450" alt="Catz!">
    <img class="picture" id="picture_4" src="https://placekitten.com/500/450" alt="Catz!">
  </div>
</div>

<p style="height: 180vh;">Etc...</p>

Use data-* Attribute on your articles Elements where the value should match the selector of the related picture.

Toggle a class i.e: .is-active using classList that will determine the active styles for the matching picture Element

To make the fixed effect use position: sticky on your pictures  parent element.


问:
Improper identifier with SQL compilation error in Snowflake
I am trying join two table in SQL using the following code:

```<code>SELECT
  lo.PATIENT_ID AS pid,
  lo.SERVICE_CODE,
  de.PATIENT_ID as pid,
  de.STATE,
  de.GENDER,
  de.ETHNICITY
FROM
  "DB"."SCHEMA"."TABLE" AS lo
INNER JOIN
  "DB"."SCHEMA"."TABLE" AS de
ON
  lo.pid = de.pid
WHERE
  lo.SERVICE_CODE = `2345.7';
</code>```

I am getting an error stating "SQL compilation error: invalid identifier 'LO.PID'. Line 13 is referring to the ON statement "lo.pid = de.pid" The data types are the same. Is there a glaring issue in the code. I've tried changing the alias on both the tables and variables but that didn't seem to work.

答:
For the avoidance of doubt, the commenters are suggesting the following changes:

```<code>SELECT
  lo.PATIENT_ID AS lo_pid,
  lo.SERVICE_CODE,
  de.PATIENT_ID as de_pid,
  de.STATE,
  de.GENDER,
  de.ETHNICITY
FROM
  "DB"."SCHEMA"."TABLE" lo
  INNER JOIN "DB"."SCHEMA"."TABLE" de ON lo.PATIENT_ID = de.PATIENT_ID
WHERE
  lo.SERVICE_CODE = '2345.7';
</code>```

JOIN runs first, then WHERE, then SELECT. You cannot use your alias pid in a JOIN because it hasn't been created yet. Naming two different columns the same would potentially work until you came to the point where you wanted to use this query in something else, then it would cause a problem. Ensure aliases created in the SELECT block are unique

If "DB"."SCHEMA"."TABLE" is repeated because you truly do want to join the table to itself, I'd point out that this might be an error, and at the very least unnecessary if PATIENT_ID is the PK. It might have some use if the table has multiple rows with the same patient_id, and you want to cross them together, but it;s more likely that your lo and de should represent different tables; Check if one of the "DB"."SCHEMA"."TABLE" is a typo

Body:
I am trying join two table in SQL using the following code:

SELECT
  lo.PATIENT_ID AS pid,
  lo.SERVICE_CODE,
  de.PATIENT_ID as pid,
  de.STATE,
  de.GENDER,
  de.ETHNICITY
FROM
  "DB"."SCHEMA"."TABLE" AS lo
INNER JOIN
  "DB"."SCHEMA"."TABLE" AS de
ON
  lo.pid = de.pid
WHERE
  lo.SERVICE_CODE = `2345.7';

I am getting an error stating "SQL compilation error: invalid identifier 'LO.PID'. Line 13 is referring to the ON statement "lo.pid = de.pid" The data types are the same. Is there a glaring issue in the code. I've tried changing the alias on both the tables and variables but that didn't seem to work.

Body:
For the avoidance of doubt, the commenters are suggesting the following changes:

SELECT
  lo.PATIENT_ID AS lo_pid,
  lo.SERVICE_CODE,
  de.PATIENT_ID as de_pid,
  de.STATE,
  de.GENDER,
  de.ETHNICITY
FROM
  "DB"."SCHEMA"."TABLE" lo
  INNER JOIN "DB"."SCHEMA"."TABLE" de ON lo.PATIENT_ID = de.PATIENT_ID
WHERE
  lo.SERVICE_CODE = '2345.7';

JOIN runs first, then WHERE, then SELECT. You cannot use your alias pid in a JOIN because it hasn't been created yet. Naming two different columns the same would potentially work until you came to the point where you wanted to use this query in something else, then it would cause a problem. Ensure aliases created in the SELECT block are unique

If "DB"."SCHEMA"."TABLE" is repeated because you truly do want to join the table to itself, I'd point out that this might be an error, and at the very least unnecessary if PATIENT_ID is the PK. It might have some use if the table has multiple rows with the same patient_id, and you want to cross them together, but it;s more likely that your lo and de should represent different tables; Check if one of the "DB"."SCHEMA"."TABLE" is a typo


问:
Rendering an html fragment with a jQuery script
I'm writting my first jQuery script which should render a list of anchors in a div (whose id is #content) when I click on another anchor (#dwLink).
I get are the links displayed as I want, but just for milliseconds! then they dissapear.

This is the script I wrote:

```<code>$(document).ready(function() {
  $('#dwLink').bind('click', function() {
    $('#content').html(
      "<ul>" +
        "<li><a href=\"#\">Link 1</a></li>" +
        "<li><a href=\"#\">Link 2</a></li>" +
        "<li><a href=\"#\">Link 3</a></li>" +
      "</ul>"
    );
  });
});
</code>```

Does it have something wrong?
I can't find where the problem is. I know I could do it by writting plain javascript since it is a basic dom manipulation problem, but I want to do it in a jQueryesque way.
I hope you can help me.
Thanks!

答:
```<code>$(document).ready(function() {
  $('#dwLink').bind('click', function(e) {
    e.preventDefault(); // prevent the default behavior of the link
    $('#content').html(
      "<ul>" +
        "<li><a href=\"#\">Link 1</a></li>" +
        "<li><a href=\"#\">Link 2</a></li>" +
        "<li><a href=\"#\">Link 3</a></li>" +
      "</ul>"
    );
  });
});
</code>```

here is the fiddle http://jsfiddle.net/45ShY/

ContentLicense: CC BY-SA 3.0

Body:
I'm writting my first jQuery script which should render a list of anchors in a div (whose id is #content) when I click on another anchor (#dwLink).
I get are the links displayed as I want, but just for milliseconds! then they dissapear.

This is the script I wrote:

$(document).ready(function() {
  $('#dwLink').bind('click', function() {
    $('#content').html(
      "
" +
        "
Link 1
" +
        "
Link 2
" +
        "
Link 3
" +
      "
"
    );
  });
});

Does it have something wrong?
I can't find where the problem is. I know I could do it by writting plain javascript since it is a basic dom manipulation problem, but I want to do it in a jQueryesque way.
I hope you can help me.
Thanks!

Body:
$(document).ready(function() {
  $('#dwLink').bind('click', function(e) {
    e.preventDefault(); // prevent the default behavior of the link
    $('#content').html(
      "<ul>" +
        "<li><a href=\"#\">Link 1</a></li>" +
        "<li><a href=\"#\">Link 2</a></li>" +
        "<li><a href=\"#\">Link 3</a></li>" +
      "</ul>"
    );
  });
});

here is the fiddle http://jsfiddle.net/45ShY/


问:
How to visit pre-defined URLs from file
If I have 30 pages to check, for example, EN has a disclaimer, but other 29 language don't, what would be the best way to do this? For example, right now I have it like this:

const urls = ['http://google.com/en',
  'http://google.com/bg'
]

describe('Disclaimer check', () => {
  urls.forEach((url) => {
    it(`Checks disclaimer text ${url}`, () => {
      cy.visit(url)
      cy.get('.Disclaimer').should('be.visible')
        .and('contain', 'This is disclaimer.')
    })
  })
})```

For 2 sites it's fine to define them in the same code but other file that checks that Disclaimer isn't there would be 29 different URL-s. What would be the best practice here? One idea is to separate all the test but that would mean 30 tests for each feature which doesn't sound too great.

As url I'm working with uses many different values in it, making it short with baseurl doesn't seem to fit also.

Thank you in advance!

答:
You were on the right path. This will be a good case for using cypress-each. Cypress-each will run all tests regardless if one or more fail. Depending on how long it takes, you may want to break down the it.each test into another file.

```<code>import 'cypress-each' // can included in /support/index.js

describe('Disclaimer check', () => {

  // baseUrl: http://google.com
  const noDisclaimerUrl = [
    '/bg',
    // all other languages
  ]

  it('/en does have disclaimer text', () => {
    cy.visit('/en')
    // test code
  })

  it.each((noDisclaimerUrl)
     `%s does not have disclaimer text`
     (url) => {
       cy.visit(url)
       // test code
  })
})
</code>```

Title: How to visit pre-defined URLs from file

Body:
If I have 30 pages to check, for example, EN has a disclaimer, but other 29 language don't, what would be the best way to do this? For example, right now I have it like this:

const urls = ['http://google.com/en',
  'http://google.com/bg'
]

describe('Disclaimer check', () => {
  urls.forEach((url) => {
    it(`Checks disclaimer text ${url}`, () => {
      cy.visit(url)
      cy.get('.Disclaimer').should('be.visible')
        .and('contain', 'This is disclaimer.')
    })
  })
})

For 2 sites it's fine to define them in the same code but other file that checks that Disclaimer isn't there would be 29 different URL-s. What would be the best practice here? One idea is to separate all the test but that would mean 30 tests for each feature which doesn't sound too great.

As url I'm working with uses many different values in it, making it short with baseurl doesn't seem to fit also.

Thank you in advance!

Body:
You were on the right path. This will be a good case for using cypress-each. Cypress-each will run all tests regardless if one or more fail. Depending on how long it takes, you may want to break down the it.each test into another file.

import 'cypress-each' // can included in /support/index.js

describe('Disclaimer check', () => {

  // baseUrl: http://google.com
  const noDisclaimerUrl = [
    '/bg',
    // all other languages
  ]

  it('/en does have disclaimer text', () => {
    cy.visit('/en')
    // test code
  })

  it.each((noDisclaimerUrl)
     `%s does not have disclaimer text`
     (url) => {
       cy.visit(url)
       // test code
  })
})


问:
LSTM, multi-variate, multi-feature in pytorch
I'm having trouble understanding the format of data for an LSTM in pytorch.    Lets say i have a CSV file with 4 features, laid out in timestamps one after the other ( a classic time series)

```<code>time1 feature1 feature2 feature3 feature4
time2 feature1 feature2 feature3 feature4
time3 feature1 feature2 feature3 feature4
time4 feature1 feature2 feature3 feature4,  label
</code>```

However, this entire set of 4 sequences only has a single label.  The thing we're trying to classify started at time1, but we don't know how to label it until time 4.

My question is, can a typical pytorch LSTM support this? All of the tutorials i've read, watched, walked through, involve looking at a time sequence of a single feature, or a word model, which is still a dataset with a single dimension.

If it can support it, does the data need to be flattened in some way?

Pytorch's LSTM reference states:

input: tensor of shape (L,N,Hin)(L, N, H_{in})(L,N,Hin) when batch_first=False or (N,L,Hin)(N, L, H_{in})(N,L,Hin) when batch_first=True containing the features of the input sequence. The input can also be a packed variable length sequence.

Does this mean that it cannot support any input that contains multiple sequences?  Or is there another name for this?

I'm really lost here, and could use any advice, pointers, help, so on.   Maybe some disambiguation too.

I've posted a couple times here but gotten no responses at all. If this post is misplaced, could someone kindly direct me towards the correct place to post it?

Edit: Following Daniel's advice, do i understand correctly that the four features should be put together like this:

```<code>[(feature1, feature2, feature3, feature4, feature1, feature2, feature3, feature4, feature1, feature2, feature3, feature4, feature1, feature2, feature3, feature4), label]  when given to the LSTM?
</code>```

If that's correct, is the input size (16) in this case?

Finally, I was under the impression that the output of the LSTM Would be the predicted label.  Do I have that wrong?

答:
As you show, the LSTM layer's input size is (batch_size, Sequence_length, feature_size). This means that the feature is assumed to be a 1D vector.

So to use it in your case you need to stack your four features into one vector (if they are more then 1D themselves then flatten them first) and use that vector as the layer's input.

Regarding the label. It is defiantly supported to have a label only after a few iterations. The LSTM will output a sequence with the same length as the input sequence, but when training the LSTM you can choose to use any part of that sequence in the loss function. In your case you will want to use the last element only.

Body:
I'm having trouble understanding the format of data for an LSTM in pytorch.    Lets say i have a CSV file with 4 features, laid out in timestamps one after the other ( a classic time series)

time1 feature1 feature2 feature3 feature4
time2 feature1 feature2 feature3 feature4
time3 feature1 feature2 feature3 feature4
time4 feature1 feature2 feature3 feature4,  label

However, this entire set of 4 sequences only has a single label.  The thing we're trying to classify started at time1, but we don't know how to label it until time 4.

My question is, can a typical pytorch LSTM support this? All of the tutorials i've read, watched, walked through, involve looking at a time sequence of a single feature, or a word model, which is still a dataset with a single dimension.

If it can support it, does the data need to be flattened in some way?

Pytorch's LSTM reference states:

input: tensor of shape (L,N,Hin)(L, N, H_{in})(L,N,Hin) when batch_first=False or (N,L,Hin)(N, L, H_{in})(N,L,Hin) when batch_first=True containing the features of the input sequence. The input can also be a packed variable length sequence.

Does this mean that it cannot support any input that contains multiple sequences?  Or is there another name for this?

I'm really lost here, and could use any advice, pointers, help, so on.   Maybe some disambiguation too.

I've posted a couple times here but gotten no responses at all. If this post is misplaced, could someone kindly direct me towards the correct place to post it?

Edit: Following Daniel's advice, do i understand correctly that the four features should be put together like this:

[(feature1, feature2, feature3, feature4, feature1, feature2, feature3, feature4, feature1, feature2, feature3, feature4, feature1, feature2, feature3, feature4), label]  when given to the LSTM?

If that's correct, is the input size (16) in this case?

Finally, I was under the impression that the output of the LSTM Would be the predicted label.  Do I have that wrong?


问:
Help with MVC 3 Routes
I have a simple route structure in my MVC 3 app that is breaking in an unexpected way.

My URL structure is fairly simple, but contains a handful of variables.

http://site.com/{location}/{stage}/{controller}/{action}/{id}

examples:

http://site.com/ny/prod/server/list - list all prod servers in ny

http://site.com/ny/test/server/123456 - list the details for the server in ny, in the test stage, with id 123456

http://site.com/ny/prod/server/reboot/565656 - reboot the server in ny, in the prod stage, with id 565656

I created the following route in my Global.asax file.

```<code>routes.MapRoute("Default", "{location}/{stage}/{controller}/{action}/{id}", new {controller="server", action="list", id = UrlParameter.Optional});
</code>```

This works fine for displaying a list of servers and the details of a server at /server/details/id, but when I try to execute a reboot, I get an error.

URL:  http://site.com/ny/prod/server/reboot/565656

The view 'ny' or its master was not found or no view engine supports
  the searched locations. The following locations were searched: ...

Why would it try to look for a view name ny.cshtml?

答:
i think your problem is that you are either not using a constraint to define what location and stage should look like and it is giving you false positives and reading things in where they are not supposed to or you have your route definitions in the wrong order

make sure you have the default mvc defined last and if you have multiple custom routes constrain the either using a regex or custom constraint class to define what locations are valid and they should look like

eg http://site.com/ny/test/server/123456

is ny a valid location - make a custom constraint that defines what a
valid location is validate it against a database or a list of valid
locations

is test a valid stage - regex could be sufficient but i always try to avoid regex whenever possible as it is evil and hard to maintain. again i would write a custom constraint to define what stages are valid likely validating against a list is sufficient is the case as you shouldnt  have very many stages
also to be noted with using stages the way you are in your url you can also add authentication rules in a constraint so that for exaple only people that are ..say.. admin or stakeholder roles be mached to the route and regular or non authenticated users would simply fall through to the next route or can simply give a 404

writing routes can be tricky so it is advised to contrain your input data as much as you can especially if you are accepting string data

stephen walther has a good post on writing route constraint at his blog

Title: Help with MVC 3 Routes

Body:
I have a simple route structure in my MVC 3 app that is breaking in an unexpected way.

My URL structure is fairly simple, but contains a handful of variables.

http://site.com/{location}/{stage}/{controller}/{action}/{id}

examples:

http://site.com/ny/prod/server/list - list all prod servers in ny

http://site.com/ny/test/server/123456 - list the details for the server in ny, in the test stage, with id 123456

http://site.com/ny/prod/server/reboot/565656 - reboot the server in ny, in the prod stage, with id 565656

I created the following route in my Global.asax file.

routes.MapRoute("Default", "{location}/{stage}/{controller}/{action}/{id}", new {controller="server", action="list", id = UrlParameter.Optional});

This works fine for displaying a list of servers and the details of a server at /server/details/id, but when I try to execute a reboot, I get an error.

URL:  http://site.com/ny/prod/server/reboot/565656

The view 'ny' or its master was not found or no view engine supports
  the searched locations. The following locations were searched: ...

Why would it try to look for a view name ny.cshtml?