问:
Django Rest - "<ClientProfile: mike@tyson.com>" needs to have a value for field "clientprofile" before this many-to-many relationship can be used
I'm trying to implement an API where I can:

Return all ClientProfile objects, with a nested ManytoMany field containing a list of Location objects (I don't really care if it's PK or actual object, actual object would be nice.)

Be able to POST a ClientProfile object, and specify which Location objects should be associated with it using the PK of the Location object, like so:

```<code>        {
        "user": {
            "email": "mike@tyson.com"
        },
        "first_name": "Mike",
        "last_name": "Tyson",
        "locations": [
            1,5,21

        ]
    }
</code>```

I have seen people saying "You need to implement a save method" for normal Django. I'm new to Django and Django REST, so not sure where or how to implement a solution for this..

Please save me from this nightmare!

Pip Freeze Output:

```<code>appdirs==1.4.0
chardet==2.3.0
Django==1.10.5
django-csvimport==2.5
djangorestframework==3.5.4
packaging==16.8
pyparsing==2.1.10
six==1.10.0
</code>```

Error:

```<code>    Traceback (most recent call last):
  File "/venv/project/userauth/tests/User.py", line 28, in setUp
    self.response = self.client.post(path="/client-profile/", format="json", data=self.data)
  File "/venv/lib/python3.5/site-packages/rest_framework/test.py", line 290, in post
    path, data=data, format=format, content_type=content_type, **extra)
  File "/venv/lib/python3.5/site-packages/rest_framework/test.py", line 212, in post
    return self.generic('POST', path, data, content_type, **extra)
  File "/venv/lib/python3.5/site-packages/django/test/client.py", line 409, in generic
    return self.request(**r)
  File "/venv/lib/python3.5/site-packages/rest_framework/test.py", line 279, in request
    return super(APIClient, self).request(**kwargs)
  File "/venv/lib/python3.5/site-packages/rest_framework/test.py", line 231, in request
    request = super(APIRequestFactory, self).request(**kwargs)
  File "/venv/lib/python3.5/site-packages/django/test/client.py", line 494, in request
    six.reraise(*exc_info)
  File "/venv/lib/python3.5/site-packages/django/utils/six.py", line 686, in reraise
    raise value
  File "/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner
    response = get_response(request)
  File "/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/venv/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "/venv/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/venv/lib/python3.5/site-packages/rest_framework/views.py", line 483, in dispatch
    response = self.handle_exception(exc)
  File "/venv/lib/python3.5/site-packages/rest_framework/views.py", line 443, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/venv/lib/python3.5/site-packages/rest_framework/views.py", line 480, in dispatch
    response = handler(request, *args, **kwargs)
  File "/venv/project/userauth/views/ClientProfile.py", line 25, in post
    serializer.save()
  File "/venv/lib/python3.5/site-packages/rest_framework/serializers.py", line 214, in save
    self.instance = self.create(validated_data)
  File "/venv/project/userauth/serializers/ClientProfile.py", line 20, in create
    client_profile = ClientProfile.objects.create(user=user, **validated_data)
  File "/venv/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/venv/lib/python3.5/site-packages/django/db/models/query.py", line 397, in create
    obj = self.model(**kwargs)
  File "/venv/lib/python3.5/site-packages/django/db/models/base.py", line 550, in __init__
    setattr(self, prop, kwargs[prop])
  File "/venv/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 499, in __set__
    manager = self.__get__(instance)
  File "/venv/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 476, in __get__
    return self.related_manager_cls(instance)
  File "/venv/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 783, in __init__
    (instance, self.source_field_name))
ValueError: "<ClientProfile: mike@tyson.com>" needs to have a value for field "clientprofile" before this many-to-many relationship can be used.
</code>```

Models:

```<code>class ClientProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='client_profile')
    enabled = models.BooleanField(_('Enabled?'), default=False)
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    locations = models.ManyToManyField(Location, related_name='client_profile')

    def __str__(self):
        return self.user.email

class Location(models.Model):
    company = models.ForeignKey(Company)
    display_name = models.CharField(max_length=50, null=True)
    address1 = models.CharField(max_length=50, null=True)
    address2 = models.CharField(max_length=50, null=True)
    city = models.CharField(max_length=50, null=True)
    county = models.CharField(max_length=50, null=True)
    postcode = models.CharField(max_length=50, null=True)
    country = models.CharField(max_length=50, null=True)
    tel = models.CharField(max_length=50, null=True)
    email = models.CharField(max_length=50, null=True)
</code>```

Serializers:

```<code>class ClientProfileSerializer(serializers.ModelSerializer):
    user = UserSerializer(required=True)
    locations = LocationSerializer(required=False, many=True)

    class Meta:
        model = ClientProfile
        fields = ('id', 'user', 'first_name', 'last_name', 'locations')

    def create(self, validated_data):
        user_data = validated_data.pop('user')
        user = User.objects.create(email=user_data['email'], is_client=True)
        client_profile = ClientProfile.objects.create(user=user, **validated_data)

        return client_profile

class LocationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Location
        fields = ('id', 'company', 'display_name', 'address1', 'address2',
                  'city', 'county', 'postcode', 'country', 'tel', 'email')
</code>```

Views:

```<code>class ClientProfileList(APIView):
    """
    List all ClientProfiles, or create a new ClientProfile.
    """
    def get(self, request, format=None):
        if self.request.user.is_client:
            client_profiles = ClientProfile.objects.all()
            serializer = ClientProfileSerializer(client_profiles, many=True)
            return Response(serializer.data)
        else:
            return Response(status=status.HTTP_401_UNAUTHORIZED)

    def post(self, request, format=None):
        serializer = ClientProfileSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class ClientProfileDetail(APIView):
    """
    Retrieve, update or delete a ClientProfile instance.
    """
    def get_object(self, pk):
        try:
            return ClientProfile.objects.get(pk=pk)
        except ClientProfile.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        client_profile = self.get_object(pk)
        serializer = ClientProfileSerializer(client_profile)
        return Response(serializer.data)

    def put(self, request, pk, format=None):
        client_profile = self.get_object(pk)
        serializer = ClientProfileSerializer(client_profile, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        client_profile = self.get_object(pk)
        client_profile.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
class LocationList(APIView):
    """
    List all Locations, or create a new Location.
    """
    def get(self, request, format=None):
        if self.request.user.is_authenticated:
            if self.request.user.is_client:
                locations = Location.objects.all()
                serializer = LocationSerializer(locations, many=True)
                return Response(serializer.data)
            else:
                return Response(status=status.HTTP_403_FORBIDDEN)
        else:
            return Response(status=status.HTTP_401_UNAUTHORIZED)

    def post(self, request, format=None):
        serializer = LocationSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class LocationDetail(APIView):
    """
    Retrieve, update or delete a Location instance.
    """
    def get_object(self, pk):
        try:
            return Location.objects.get(pk=pk)
        except Location.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        location = self.get_object(pk)
        serializer = LocationSerializer(location)
        return Response(serializer.data)

    def put(self, request, pk, format=None):
        location = self.get_object(pk)
        serializer = LocationSerializer(location, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        location = self.get_object(pk)
        location.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
</code>```

答:
Django Models with ManyToMany fields must be saved before you can add related instances. (To add an entry in the ManyToMany relation, Django needs the parent model instance pk which is set only after the model is created.)

So your ClientProfile must be saved before you can add any related Location instance.

To fix this error, just update your ClientProfileSerializer.create method:

```<code>class ClientProfileSerializer(serializers.ModelSerializer):

    def create(self, validated_data):
        user_data = validated_data.pop('user')
        user = User.objects.create(email=user_data['email'], is_client=True)
        locations = validated_data.pop('locations')
        client_profile = ClientProfile.objects.create(user=user, **validated_data)
        client_profile.locations.add(*locations)
        return client_profile
</code>```

Body:
I'm trying to implement an API where I can:

Return all ClientProfile objects, with a nested ManytoMany field containing a list of Location objects (I don't really care if it's PK or actual object, actual object would be nice.)

Be able to POST a ClientProfile object, and specify which Location objects should be associated with it using the PK of the Location object, like so:

        {
        "user": {
            "email": "mike@tyson.com"
        },
        "first_name": "Mike",
        "last_name": "Tyson",
        "locations": [
            1,5,21

        ]
    }

I have seen people saying "You need to implement a save method" for normal Django. I'm new to Django and Django REST, so not sure where or how to implement a solution for this..

Please save me from this nightmare!

Pip Freeze Output:

appdirs==1.4.0
chardet==2.3.0
Django==1.10.5
django-csvimport==2.5
djangorestframework==3.5.4
packaging==16.8
pyparsing==2.1.10
six==1.10.0

Error:

    Traceback (most recent call last):
  File "/venv/project/userauth/tests/User.py", line 28, in setUp
    self.response = self.client.post(path="/client-profile/", format="json", data=self.data)
  File "/venv/lib/python3.5/site-packages/rest_framework/test.py", line 290, in post
    path, data=data, format=format, content_type=content_type, **extra)
  File "/venv/lib/python3.5/site-packages/rest_framework/test.py", line 212, in post
    return self.generic('POST', path, data, content_type, **extra)
  File "/venv/lib/python3.5/site-packages/django/test/client.py", line 409, in generic
    return self.request(**r)
  File "/venv/lib/python3.5/site-packages/rest_framework/test.py", line 279, in request
    return super(APIClient, self).request(**kwargs)
  File "/venv/lib/python3.5/site-packages/rest_framework/test.py", line 231, in request
    request = super(APIRequestFactory, self).request(**kwargs)
  File "/venv/lib/python3.5/site-packages/django/test/client.py", line 494, in request
    six.reraise(*exc_info)
  File "/venv/lib/python3.5/site-packages/django/utils/six.py", line 686, in reraise
    raise value
  File "/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner
    response = get_response(request)
  File "/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/venv/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "/venv/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/venv/lib/python3.5/site-packages/rest_framework/views.py", line 483, in dispatch
    response = self.handle_exception(exc)
  File "/venv/lib/python3.5/site-packages/rest_framework/views.py", line 443, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/venv/lib/python3.5/site-packages/rest_framework/views.py", line 480, in dispatch
    response = handler(request, *args, **kwargs)
  File "/venv/project/userauth/views/ClientProfile.py", line 25, in post
    serializer.save()
  File "/venv/lib/python3.5/site-packages/rest_framework/serializers.py", line 214, in save
    self.instance = self.create(validated_data)
  File "/venv/project/userauth/serializers/ClientProfile.py", line 20, in create
    client_profile = ClientProfile.objects.create(user=user, **validated_data)
  File "/venv/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/venv/lib/python3.5/site-packages/django/db/models/query.py", line 397, in create
    obj = self.model(**kwargs)
  File "/venv/lib/python3.5/site-packages/django/db/models/base.py", line 550, in __init__
    setattr(self, prop, kwargs[prop])
  File "/venv/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 499, in __set__
    manager = self.__get__(instance)
  File "/venv/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 476, in __get__
    return self.related_manager_cls(instance)
  File "/venv/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 783, in __init__
    (instance, self.source_field_name))
ValueError: "<ClientProfile: mike@tyson.com>" needs to have a value for field "clientprofile" before this many-to-many relationship can be used.

Models:

class ClientProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='client_profile')
    enabled = models.BooleanField(_('Enabled?'), default=False)
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    locations = models.ManyToManyField(Location, related_name='client_profile')

    def __str__(self):
        return self.user.email

class Location(models.Model):
    company = models.ForeignKey(Company)
    display_name = models.CharField(max_length=50, null=True)
    address1 = models.CharField(max_length=50, null=True)
    address2 = models.CharField(max_length=50, null=True)
    city = models.CharField(max_length=50, null=True)
    county = models.CharField(max_length=50, null=True)
    postcode = models.CharField(max_length=50, null=True)
    country = models.CharField(max_length=50, null=True)
    tel = models.CharField(max_length=50, null=True)
    email = models.CharField(max_length=50, null=True)

Serializers:

class ClientProfileSerializer(serializers.ModelSerializer):
    user = UserSerializer(required=True)
    locations = LocationSerializer(required=False, many=True)

    class Meta:
        model = ClientProfile
        fields = ('id', 'user', 'first_name', 'last_name', 'locations')

    def create(self, validated_data):
        user_data = validated_data.pop('user')
        user = User.objects.create(email=user_data['email'], is_client=True)
        client_profile = ClientProfile.objects.create(user=user, **validated_data)

        return client_profile

class LocationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Location
        fields = ('id', 'company', 'display_name', 'address1', 'address2',
                  'city', 'county', 'postcode', 'country', 'tel', 'email')

Views:

class ClientProfileList(APIView):
    """
    List all ClientProfiles, or create a new ClientProfile.
    """
    def get(self, request, format=None):
        if self.request.user.is_client:
            client_profiles = ClientProfile.objects.all()
            serializer = ClientProfileSerializer(client_profiles, many=True)
            return Response(serializer.data)
        else:
            return Response(status=status.HTTP_401_UNAUTHORIZED)

    def post(self, request, format=None):
        serializer = ClientProfileSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class ClientProfileDetail(APIView):
    """
    Retrieve, update or delete a ClientProfile instance.
    """
    def get_object(self, pk):
        try:
            return ClientProfile.objects.get(pk=pk)
        except ClientProfile.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        client_profile = self.get_object(pk)
        serializer = ClientProfileSerializer(client_profile)
        return Response(serializer.data)

    def put(self, request, pk, format=None):
        client_profile = self.get_object(pk)
        serializer = ClientProfileSerializer(client_profile, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        client_profile = self.get_object(pk)
        client_profile.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
class LocationList(APIView):
    """
    List all Locations, or create a new Location.
    """
    def get(self, request, format=None):
        if self.request.user.is_authenticated:
            if self.request.user.is_client:
                locations = Location.objects.all()
                serializer = LocationSerializer(locations, many=True)
                return Response(serializer.data)
            else:
                return Response(status=status.HTTP_403_FORBIDDEN)
        else:
            return Response(status=status.HTTP_401_UNAUTHORIZED)

    def post(self, request, format=None):
        serializer = LocationSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class LocationDetail(APIView):
    """
    Retrieve, update or delete a Location instance.
    """
    def get_object(self, pk):
        try:
            return Location.objects.get(pk=pk)
        except Location.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        location = self.get_object(pk)
        serializer = LocationSerializer(location)
        return Response(serializer.data)

    def put(self, request, pk, format=None):
        location = self.get_object(pk)
        serializer = LocationSerializer(location, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        location = self.get_object(pk)
        location.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

Body:
Django Models with ManyToMany fields must be saved before you can add related instances. (To add an entry in the ManyToMany relation, Django needs the parent model instance pk which is set only after the model is created.)

So your ClientProfile must be saved before you can add any related Location instance.

To fix this error, just update your ClientProfileSerializer.create method:

class ClientProfileSerializer(serializers.ModelSerializer):

    def create(self, validated_data):
        user_data = validated_data.pop('user')
        user = User.objects.create(email=user_data['email'], is_client=True)
        locations = validated_data.pop('locations')
        client_profile = ClientProfile.objects.create(user=user, **validated_data)
        client_profile.locations.add(*locations)
        return client_profile


来源: stackexchange

问:
os.popen() variables
So i have this application thats rather complicated...
To keep it short this is the main things you should know:

```<code>file_name = raw_input("Name your file:").lower()

os.popen(sudo tcpdump -c5 -vvv -w "file_name" host wiki or host wiki2)
</code>```

but this doesn't seem to work. Can i get a fix?
Thanks,
Pastelinux

edit1:
Alright this is what i have now, but its not working, any pointers on how to fix?

import subprocess, os, sys

filename = raw_input('File name:').lower

pipe = os.popen("sudo tcpdump -c5 -w", 'filename')

pipe = popen("sudo tcpdump -c5 -w", shell=True, stdout=PIPE).stdout

答:
Don't use `os.popen', you should use the subprocess module.

I am assuming this (a string):

```<code>sudo tcpdump -c5 -vvv -w "file_name" host wiki or host wiki2
</code>```

is your command.

Since we just need to call tcpdump and not get any output from it, we use subprocess.call

```<code>>>> subprocess.call(your_command.split())
</code>```

Of course why it is not working depends on what the error is, but this is how you should go about it. If you can update the answer with your error, then it can be clear.

ContentLicense: CC BY-SA 2.5

Title: os.popen() variables

Body:
So i have this application thats rather complicated...
To keep it short this is the main things you should know:

file_name = raw_input("Name your file:").lower()

os.popen(sudo tcpdump -c5 -vvv -w "file_name" host wiki or host wiki2)

but this doesn't seem to work. Can i get a fix?
Thanks,
Pastelinux

edit1:
Alright this is what i have now, but its not working, any pointers on how to fix?

import subprocess, os, sys

filename = raw_input('File name:').lower

pipe = os.popen("sudo tcpdump -c5 -w", 'filename')

pipe = popen("sudo tcpdump -c5 -w", shell=True, stdout=PIPE).stdout

Body:
Don't use `os.popen', you should use the subprocess module.

I am assuming this (a string):

sudo tcpdump -c5 -vvv -w "file_name" host wiki or host wiki2

is your command.

Since we just need to call tcpdump and not get any output from it, we use subprocess.call

>>> subprocess.call(your_command.split())

Of course why it is not working depends on what the error is, but this is how you should go about it. If you can update the answer with your error, then it can be clear.


问:
Script not showing properly inside a div tabbertab
I have added an Instagram Widget inside a div tabbertab. The widget is not shown properly, it is like cutted in the middle. If I put the widget code outside the div tab it works fine, but I need it inside.

Here is a link to my page code:
http://thebestwineriesoftheworld.com/chateausmithhautlafitte/chateausmithhautlafitte.htm

Please let me know what can I do. You can see the widget inside the "Social Networks" title of the tab.

答:
As mentioned,The height of the iframe that hold your instagram widget is set to 435px; Setting a height to 100% relative the the parent container will works a s expected

Example

```<code><iframe id="79e8ff18932e6ecaa0a98250d72af257fd095aacd53bb71d709c79dfee180135" style="border: 0px none; width: 450px; margin: 0px; padding: 0px; height: 100%;" scrolling="no" src="https://instawidget.net/embed?u=79e8ff18932e6ecaa0a98250d72af257fd095aacd53bb71d709c79dfee180135" frameborder="no"></iframe>
</code>```

Add the css rule to your stylsheet

```<code>#79e8ff18932e6ecaa0a98250d72af257fd095aacd53bb71d709c79dfee180135{
height:100%
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
As mentioned,The height of the iframe that hold your instagram widget is set to 435px; Setting a height to 100% relative the the parent container will works a s expected

Example

<iframe id="79e8ff18932e6ecaa0a98250d72af257fd095aacd53bb71d709c79dfee180135" style="border: 0px none; width: 450px; margin: 0px; padding: 0px; height: 100%;" scrolling="no" src="https://instawidget.net/embed?u=79e8ff18932e6ecaa0a98250d72af257fd095aacd53bb71d709c79dfee180135" frameborder="no"></iframe>

Add the css rule to your stylsheet

#79e8ff18932e6ecaa0a98250d72af257fd095aacd53bb71d709c79dfee180135{
height:100%
}


问:
Using JavaScript Variables in HTML code
I'm pretty new to JavaScript.

I'm trying to make a YouTube 2.0 html thing, (interesting learning experience). I want it to be so that you click on the "load video" link and it asks you the link to the actual youtube video. Then, when you paste it in, it displays the video on the page.

My code is

Youtube 2.0

Load video

```

If you have any ideas on how I can insert the JavaScript variable into my iframe src tag, please tell me. Thanks!

答:
This code navigates the  to URL that typed in prompt dialog.

```<code><h1 style="background-color: red; color: white; font-family: helvetica; padding: 20px 20px 20px 20px;">Youtube 2.0</h1>
<a href="#" onclick="openVideo()">Load video</a>
<script>

var openVideo = function() {
    var videoLink = prompt("Video link on YouTube.com");
    window.open(videoLink, "myLink");
}
</code>```

```<code><iframe width="1120" height="630" name="myLink" frameborder="0" allowfullscreen></iframe>
</code>```

Update: This code only navigates  to given URL. You should probably use Youtube embed options instead of this.

Title: Using JavaScript Variables in HTML code

Body:
I'm pretty new to JavaScript.

I'm trying to make a YouTube 2.0 html thing, (interesting learning experience). I want it to be so that you click on the "load video" link and it asks you the link to the actual youtube video. Then, when you paste it in, it displays the video on the page.

My code is

Youtube 2.0

Load video

If you have any ideas on how I can insert the JavaScript variable into my iframe src tag, please tell me. Thanks!

Body:
This code navigates the <iframe> to URL that typed in prompt dialog.

<h1 style="background-color: red; color: white; font-family: helvetica; padding: 20px 20px 20px 20px;">Youtube 2.0</h1>
<a href="#" onclick="openVideo()">Load video</a>
<script>

var openVideo = function() {
    var videoLink = prompt("Video link on YouTube.com");
    window.open(videoLink, "myLink");
}

<iframe width="1120" height="630" name="myLink" frameborder="0" allowfullscreen></iframe>

Update: This code only navigates <iframe> to given URL. You should probably use Youtube embed options instead of this.

ContentLicense: CC BY-SA 4.0


问:
karma-typescript cannot find module
I have a very small project that I am trying to set up unit tests for. The project compiles fine when using tsc directly, however, I am getting the following Typescript compilation errors when attempting to execute tests which use the karma-typescript framework:

ERRORS:

ERROR [compiler.karma-typescript]: src/drawing/canvas.model.ts(1,23):
  error TS2307: Cannot find module 'utils'.

ERROR [compiler.karma-typescript]: src/models/grid.model.ts(1,23): error TS2307: Cannot find module 'utils'.

ERROR [compiler.karma-typescript]: src/utils/specs/obj.utils.spec.ts(1,23): error TS2307: Cannot find
  module 'utils'.

PROJECT STRUCTURE:
I've got a project set up that is structured as such:

```<code>|-dist/
|-node_modules/
|-src/
| |
| |-drawing/
| | |
| | |-canvas.model.ts
| |    ________________________________
| |   | import { Utils } from 'utils'; |  Karma Fails (tsc is fine)
| |    --------------------------------
| |
| |-models/
| | |
| | |-grid.model.ts
| |    ________________________________
| |   | import { Utils } from 'utils'; |  Karma Fails (tsc is fine)
| |    --------------------------------
| |
| |-utils/
| | |
| | |-index.ts
| | |  _________________________
| | | | export module Utils {}  |
| | |  -------------------------
| | |
| | |-specs/
| | | |
| | | |-obj.utils.spec.ts
| | |    ________________________________
| | |   | import { Utils } from 'utils'; |  Karma Fails (tsc is fine)
| | |    --------------------------------
| | |
|-karma.config.js
|-tsconfig.json
|-package.json
</code>```

It's clear to me that there is a discrepancy between my tsconfig.json file and the compiler settings used internally for karma-typescript. Here is how I have both of those files structured. According to the documentation for karma-typescript, there should be a couple of options that I can configure in my karma.conf file that would tell karma-typescript to respect my settings in my Typescript config file, namely the "paths" property, which is where I have specified to Typescript where to look for my utils module.

KARMA.CONF.JS

// Karma configuration
// Generated on Fri Mar 31 2017 16:42:11 GMT-0700 (PDT)
module.exports = function(config) {
  config.set({
    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',
    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine', 'karma-typescript'],
    // Plugins
    plugins: [
      'karma-spec-reporter',
      'karma-jasmine',
      'karma-chrome-launcher',
      'karma-jasmine-html-reporter',
      'karma-typescript'
    ],
    // list of files / patterns to load in the browser
    files: [{
      pattern: "./src/**/*.ts"
    }],
    // list of files to exclude
    exclude: ['**/*.spec.js'],

    // Karma Typescript compiler options
    karmaTypescriptConfig: {
      bundlerOptions: {
        resolve: {
          directories: ["src", "node_modules", "src/utils"]
        }
      }
    },
    compilerOptions: {
      module: 'commonjs',
      moduleResolution: 'node',
      paths: {
        'utils': ['./src/utils'], 'utils/*': ['./src/utils/*']
      }
    },
    tsconfig: './tsconfig.json',

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      "**/*.ts": ["karma-typescript"]
    },
    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress', 'kjhtml', 'spec', "karma-typescript"],
    // web server port
    port: 9876,
    // enable / disable colors in the output (reporters and logs)
    colors: true,
    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,
    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,
    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],
    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,
    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  })
}```
</div>
</div>
</p>

<hr>

<p>Here is my Typescript config file. Note that I am registering the <code>"utils"</code> in the <code>"paths"</code> portion of the tsconfig file, which assists in the Typescript compiler's module resolution process. This works fine with normal Typescript compilation, but that is probably because my Typescript compiler is actually respecting the settings in my tsconfig file. I am using <strong>Typescript 2.0.10</strong>. But it appears that karma-typescript is using <strong>Typescript 2.2.2</strong>, which could be the potential source of the error. I'll have to run my compiler against that version to see if I can generate the same error.</p>

<p><strong>TSCONFIG.JSON</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{
  "compileOnSave": true,
  "compilerOptions": {
    "baseUrl": ".",
    "outDir": "./dist",
    "paths": {
      "utils/*": ["./src/utils/*"],
      "utils": ["./src/utils"]
    },
    "declaration": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": ["es5", "dom"],
    "mapRoot": "./",
    "module": "es6",
    "moduleResolution": "node",
    "sourceMap": true,
    "target": "es5",
    "rootDirs": ["./dist", "."]
  },
  "exclude": ["./node_modules", "./dist", "**/*.d.ts"],
  "include": ["./src/**/*.ts"]
}</code>```

Can anyone help me out with this? I'm decent with Typescript but pretty new to Karma. I've been scouring documentation for about 2 days now trying to get these simple unit tests running, but to no avail. Not with the way I've got my paths structured at least. Any help would be appreciated!

UPDATE:
I tried updating my local installation of Typescript to 2.2.2, to match the Karma-Typescript's version which is also 2.2.2. Same error, same scenario - my local version compiles fine, but the Karma-Typescript version balks.

答:
There's a tiny error in the Karma config, the compilerOptions and tsconfig properties should be inside the karmaTypescriptConfig property.

Given your project structure example, here's a minimal working configuration example for both tsc and karma-typescript:

Karma.conf.js

```<code>module.exports = function(config) {
    config.set({

        frameworks: ["jasmine", "karma-typescript"],

        files: [
            { pattern: "src/**/*.ts" }
        ],

        karmaTypescriptConfig: {
            compilerOptions: {
                module: "commonjs"
            },
            tsconfig: "./tsconfig.json",
        },

        preprocessors: {
            "**/*.ts": ["karma-typescript"]
        },

        reporters: ["progress", "kjhtml", "spec", "karma-typescript"],

        browsers: ["Chrome"]
    });
};
</code>```

tsconfig.json

```<code>{
    "compileOnSave": true,
    "compilerOptions": {
        "baseUrl": ".",
        "outDir": "./dist",
        "paths": {
            "utils/*": ["./src/utils/*"],
            "utils": ["./src/utils"]
        },
        "module": "es6",
        "moduleResolution": "node",
        "sourceMap": true,
        "target": "es5"
    }
}
</code>```

I tested this using typescript@2.2.2 and karma-typescript@3.0.0.

Also, please note that karma-typescript only has Typescript as a dev dependency, letting you use any Typescript version from 1.6.2 and up :)

Title: karma-typescript cannot find module

Body:
I have a very small project that I am trying to set up unit tests for. The project compiles fine when using tsc directly, however, I am getting the following Typescript compilation errors when attempting to execute tests which use the karma-typescript framework:

ERRORS:

ERROR [compiler.karma-typescript]: src/drawing/canvas.model.ts(1,23):
  error TS2307: Cannot find module 'utils'.

ERROR [compiler.karma-typescript]: src/models/grid.model.ts(1,23): error TS2307: Cannot find module 'utils'.

ERROR [compiler.karma-typescript]: src/utils/specs/obj.utils.spec.ts(1,23): error TS2307: Cannot find
  module 'utils'.

PROJECT STRUCTURE:
I've got a project set up that is structured as such:

|-dist/
|-node_modules/
|-src/
| |
| |-drawing/
| | |
| | |-canvas.model.ts
| |    ________________________________
| |   | import { Utils } from 'utils'; |  Karma Fails (tsc is fine)
| |    --------------------------------
| |
| |-models/
| | |
| | |-grid.model.ts
| |    ________________________________
| |   | import { Utils } from 'utils'; |  Karma Fails (tsc is fine)
| |    --------------------------------
| |
| |-utils/
| | |
| | |-index.ts
| | |  _________________________
| | | | export module Utils {}  |
| | |  -------------------------
| | |
| | |-specs/
| | | |
| | | |-obj.utils.spec.ts
| | |    ________________________________
| | |   | import { Utils } from 'utils'; |  Karma Fails (tsc is fine)
| | |    --------------------------------
| | |
|-karma.config.js
|-tsconfig.json
|-package.json

It's clear to me that there is a discrepancy between my tsconfig.json file and the compiler settings used internally for karma-typescript. Here is how I have both of those files structured. According to the documentation for karma-typescript, there should be a couple of options that I can configure in my karma.conf file that would tell karma-typescript to respect my settings in my Typescript config file, namely the "paths" property, which is where I have specified to Typescript where to look for my utils module.

KARMA.CONF.JS

// Karma configuration
// Generated on Fri Mar 31 2017 16:42:11 GMT-0700 (PDT)
module.exports = function(config) {
  config.set({
    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',
    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine', 'karma-typescript'],
    // Plugins
    plugins: [
      'karma-spec-reporter',
      'karma-jasmine',
      'karma-chrome-launcher',
      'karma-jasmine-html-reporter',
      'karma-typescript'
    ],
    // list of files / patterns to load in the browser
    files: [{
      pattern: "./src/**/*.ts"
    }],
    // list of files to exclude
    exclude: ['**/*.spec.js'],

    // Karma Typescript compiler options
    karmaTypescriptConfig: {
      bundlerOptions: {
        resolve: {
          directories: ["src", "node_modules", "src/utils"]
        }
      }
    },
    compilerOptions: {
      module: 'commonjs',
      moduleResolution: 'node',
      paths: {
        'utils': ['./src/utils'], 'utils/*': ['./src/utils/*']
      }
    },
    tsconfig: './tsconfig.json',

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      "**/*.ts": ["karma-typescript"]
    },
    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress', 'kjhtml', 'spec', "karma-typescript"],
    // web server port
    port: 9876,
    // enable / disable colors in the output (reporters and logs)
    colors: true,
    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,
    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,
    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],
    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,
    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  })
}

Here is my Typescript config file. Note that I am registering the "utils" in the "paths" portion of the tsconfig file, which assists in the Typescript compiler's module resolution process. This works fine with normal Typescript compilation, but that is probably because my Typescript compiler is actually respecting the settings in my tsconfig file. I am using Typescript 2.0.10. But it appears that karma-typescript is using Typescript 2.2.2, which could be the potential source of the error. I'll have to run my compiler against that version to see if I can generate the same error.

TSCONFIG.JSON

{
  "compileOnSave": true,
  "compilerOptions": {
    "baseUrl": ".",
    "outDir": "./dist",
    "paths": {
      "utils/*": ["./src/utils/*"],
      "utils": ["./src/utils"]
    },
    "declaration": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": ["es5", "dom"],
    "mapRoot": "./",
    "module": "es6",
    "moduleResolution": "node",
    "sourceMap": true,
    "target": "es5",
    "rootDirs": ["./dist", "."]
  },
  "exclude": ["./node_modules", "./dist", "**/*.d.ts"],
  "include": ["./src/**/*.ts"]
}

Can anyone help me out with this? I'm decent with Typescript but pretty new to Karma. I've been scouring documentation for about 2 days now trying to get these simple unit tests running, but to no avail. Not with the way I've got my paths structured at least. Any help would be appreciated!

UPDATE:
I tried updating my local installation of Typescript to 2.2.2, to match the Karma-Typescript's version which is also 2.2.2. Same error, same scenario - my local version compiles fine, but the Karma-Typescript version balks.

Body:
There's a tiny error in the Karma config, the compilerOptions and tsconfig properties should be inside the karmaTypescriptConfig property.

Given your project structure example, here's a minimal working configuration example for both tsc and karma-typescript:

Karma.conf.js

module.exports = function(config) {
    config.set({

        frameworks: ["jasmine", "karma-typescript"],

        files: [
            { pattern: "src/**/*.ts" }
        ],

        karmaTypescriptConfig: {
            compilerOptions: {
                module: "commonjs"
            },
            tsconfig: "./tsconfig.json",
        },

        preprocessors: {
            "**/*.ts": ["karma-typescript"]
        },

        reporters: ["progress", "kjhtml", "spec", "karma-typescript"],

        browsers: ["Chrome"]
    });
};

tsconfig.json

{
    "compileOnSave": true,
    "compilerOptions": {
        "baseUrl": ".",
        "outDir": "./dist",
        "paths": {
            "utils/*": ["./src/utils/*"],
            "utils": ["./src/utils"]
        },
        "module": "es6",
        "moduleResolution": "node",
        "sourceMap": true,
        "target": "es5"
    }
}

I tested this using typescript@2.2.2 and karma-typescript@3.0.0.

Also, please note that karma-typescript only has Typescript as a dev dependency, letting you use any Typescript version from 1.6.2 and up :)


问:
Is there a way to add video elements in React Native (for Android)?
I 'm searching the docs, but haven't succeeded yet to find a sample code.
I need to play videos from my stream server.  Is there any way? or may be react-js does not support videos on android yet.</p>

答:
Yep. Took me a while to figure out, but the solution is easy.

Use react-native-video component which is cross-platform iOS and Android.

Implementation:
Couldn't be simpler...

```<code><Video source={{ uri: 'http://STREAM_URL/playlist.m3u8' }} />
</code>```

Tips for playing live HLS .m3u8 streams on iOS and Android:

On iOS:
Be sure to allow the stream's source domain as an exception domain on App Transport Security Settings on info.plist. While testing, I set "Allow Arbitrary Loads" to YES. Before I did this, the stream didn't come through at all.

On Android:
Use the new exoplayer variant introduced in react-native-video 1.0. Here's how to enable that: #426 (comment)

Body:
Yep. Took me a while to figure out, but the solution is easy.

Use react-native-video component which is cross-platform iOS and Android.

Implementation:
Couldn't be simpler...

<Video source={{ uri: 'http://STREAM_URL/playlist.m3u8' }} />

Tips for playing live HLS .m3u8 streams on iOS and Android:

On iOS:
Be sure to allow the stream's source domain as an exception domain on App Transport Security Settings on info.plist. While testing, I set "Allow Arbitrary Loads" to YES. Before I did this, the stream didn't come through at all.

On Android:
Use the new exoplayer variant introduced in react-native-video 1.0. Here's how to enable that: #426 (comment)


问:
Make an item display only for certain period of time on the webpage
Hi guys I am constructing a task distribution management system for my team in which I want to add a functionality that:

When I create a task, I will have an option to choose "how long is this task valid for being taken". For example, when creating the task I put "2 hours" in the

```<code><input id="valid-for">
</code>```

, then this task will only be displayed on the dashboard for 2 hours from the time it was created and then after 2 hours -> "display: none".

I've searched the web for the mechanism of achieving this feature but I didn't get a satisfied answer probably because I don't know the right terminology to google. I tried to use AJAX and use TIME_STAMP type attribute in MySQL but didn't know how to proceed. Could anybody tell me how to achieve this feature by the use of MySQL, jQuery or any other technics that could fulfill this feature? No code necessary I just need some explanation.

Thanks guys!

答:
Without knowing any more details, here is how I would consider writing the code:

In the database, have a start time and a use-by time.

In your browser page, you can run a script periodically, say every minute (this is called polling). In this case, you can use Ajax to call back to the server for updates.

At the server end, check for new tasks as well as expired tasks. Then send the results back to the Ajax caller.

Back at the browser, update the dashboard accordingly.

I would be inclined to remove the task on the browser rather than simply hide it.

Body:
Hi guys I am constructing a task distribution management system for my team in which I want to add a functionality that:

When I create a task, I will have an option to choose "how long is this task valid for being taken". For example, when creating the task I put "2 hours" in the

<input id="valid-for">

, then this task will only be displayed on the dashboard for 2 hours from the time it was created and then after 2 hours -> "display: none".

I've searched the web for the mechanism of achieving this feature but I didn't get a satisfied answer probably because I don't know the right terminology to google. I tried to use AJAX and use TIME_STAMP type attribute in MySQL but didn't know how to proceed. Could anybody tell me how to achieve this feature by the use of MySQL, jQuery or any other technics that could fulfill this feature? No code necessary I just need some explanation.

Thanks guys!


问:
Unity double mouse click input event receive
I'm making a 2D topdown shooter in Unity (version 5.6.0b3 64-bit) and I have a problem with receive mouse input properly, especially mousewheel.

I'm using mousewheel for switching weapons.

I have a problem with registering mouse input.

Code for my mouse:

```<code>if(Input.GetAxis("Mouse ScrollWheel")>0)
{
Debug.Log("Mousewheel Up");
}

if(Input.GetAxis("Mouse ScrollWheel")<0)
{
Debug.Log("Mousewheel Down");
}
</code>```

After first launching game in main menu in console I can see it detecting corretly

But after starting game and loading scene its starting to act weird and double registering mouse wheel moving:

And by this bug switching weapon not working corretly (it double switching it, missing one in the middle)
for example i have 3 weapons, from 1 it switches to 3.

Also it spawn 2 explosions on 1 right click (should be 1)

I don't know what is going on, I appreciate every help.

答:
The question is a bit vague but I have a feeling this might depend on GameObject duplication.

Maybe your GameObject (polling for input) has "DontDestroyOnLoad" called on it and you have a second one in your Game Scene and forgot to remove the one from the MainMenu.

Body:
I'm making a 2D topdown shooter in Unity (version 5.6.0b3 64-bit) and I have a problem with receive mouse input properly, especially mousewheel.

I'm using mousewheel for switching weapons.

I have a problem with registering mouse input.

Code for my mouse:

if(Input.GetAxis("Mouse ScrollWheel")>0)
{
Debug.Log("Mousewheel Up");
}

if(Input.GetAxis("Mouse ScrollWheel")<0)
{
Debug.Log("Mousewheel Down");
}

After first launching game in main menu in console I can see it detecting corretly

But after starting game and loading scene its starting to act weird and double registering mouse wheel moving:

And by this bug switching weapon not working corretly (it double switching it, missing one in the middle)
for example i have 3 weapons, from 1 it switches to 3.

Also it spawn 2 explosions on 1 right click (should be 1)

I don't know what is going on, I appreciate every help.


问:
Ionic Android Build Error

I am getting the following errors when building Android with the Ionic CLI.

The first error says "Could not find any version that matches com.android.support:support-v4:+."

I have tried updating all the Android API's but still have the same errors.
I think there is a simple solution but I am just not familiar with Android and the SDK Manager, so attached is also a screenshot of what I have download using the SDK Manager. Am I missing anything?

答:
Alright so after going into the pits of hell, I managed to fix this. Disclaimer: I am very new to building/compiling for Android (remember, I'm an Ionic user and we want nothing to do with the hurdles of working with native Android/iOS) and so this solution may seem pretty obvious.

SOLUTION (WINDOWS 7):

I had a very old version of Android Studio - I upgraded. Even though the old SDK Manager said all API's were downloaded and fine, I guess it was so outdated (from 2014 I think) that it was misleading me with false flags.

System Paths are a mess. Some people tell you to point to the 'appData' location of the Android SDK, and others tell you to point to the 'AndroidSDK' folder on your C drive. The 'appData' location ended up working for me.

SYSTEM PATH INSTRUCTIONS:

Go to Control Panel > Advanced System Settings > 'Advanced' tab in the System Properties popup > Environment Variables.

Now set a new 'SYSTEM' variable and call it ANDROID_HOME and give it the following value: C:\Users\<YOUR_USERNAME>\AppData\Local\Android\android-studio\sdk

Finally, in the SYSTEM VARIABLES section, update 'Path' (DO NOT COMPLETELY REPLACE, just add the following text to it) with %ANDROID_HOME%\platform-tools;%ANDROID_HOME%\tools;

Now save system variables, hit okay (exit all those popups), then close and reopen your terminal (I am using GIT Bash). Run your Cordova/Ionic Android build command again and it should work cordova build --release android

Title: Ionic Android Build Error


问:
bash vs csh vs others - which is better for application maintenance?

Possible Duplicate:

  What Linux shell should I use?

I am starting to get proficient in a Linux environment and i'm trying to pick a weapon of choice in terms of command shell scripting (as i'm still a big n00b at this) that will help me (and others) manage, test and administer a set of server side applications running on a *NIX environment.

My question is: What is(are) the preferred command shell(s)  out there when the following criteria are considered:

How easy is it to learn/understand for a junior dev who has never had an exposure to shell scripting?

Is there a big pool of developers out there that know this shell script?

Is it safe and easy to use - will script errors be silent or give intelligent error output, will it let the uninitiated shoot them selves in the foot?

How portable is it? - Can i expect the same script to run in OpenSolaris as well as Redhat, FreeBSD? (granted command syntax and options for specific OS will change accordingly)

How standard is it? Is it expected to be included on most distro's of *NIX or does it have to be installed additionally?

I understand that there are camps out there who hold strong feelings for/against specific command shells, i am just looking for an informed opinion.

答:
Z shell (zsh)

It's said zsh is the most powerful for now so I would recommend trying it.

No matter which shell you learn - their syntax is very similar. Only built-in commands may slightly differ. But don't choose those old and unmaintained.

Bash is the most popular. But almost every command in bash works in zsh the same way. There are some exceptions of course.

AFAIK, every shell handles it the same way. But be warned - shells are stupid, they are not as smart as programming languages.

I saw zsh working on all Linuxes, FreeBSD and OpenSolaris.

See 4. Distros have zsh in their repos.

Why I prefer zsh (Z shell) to bash:

files matching like this: for file in ./**/*.java; do ... (I mean ./**/*.ext)

wants me to confirm when I do rm * :)

tab-autocompletion is a lot better, I can write dmdomi[tab] and it suggests dnddomainname. java wants class name as the first parameter, zsh will suggest all classes available in the package and all subpackages.

But you are not limited to zsh only. If something does not work for you, you just write it in bash or sh. This is what is "#!/bin/bash" on top of the script for. :-)

To start quickly, use my .zshrc config: http://www.rozne.geozone.pl/.zshrc The only thing you should change there is export LANG="pl_PL.UTF-8". You probably don't want Polish locale.


问:
Asymptotic running time of algorithm
Given the following algorithm of multiplying matrices which are all n x n

```<code>for(int i=1;i<=n;i++){
    for(int j=1;j<=n;j++){
       s=0;
       for(int k=1;k<=n;k++){
          s+=A[i][k]*B[k][j];
          C[i][j]=s;
       }
    }
}
return s;
</code>```

The asymptotic running time is Theta(n^3) ,however what does this mean :

If we consider the running time  as a function of the length of the input the order growth is Theta( m ^(3/2) ) where m is the length of the input i.e m is the order of the number elements in the matrices  and m = Theta(n^2)

Why the growth of the input is Theta( m ^(3/2) ) and Is the whole asymptotic running time Theta(n^2)?

答:
If we have asymptotic time T is :
T = Theta(n^3)
this mean, that our time is in proportion to this t :
t = k*(n^3)
we also have m is order of magnitud of number of elements :
m = Theta(n^2).
This mean, that m' , a specific number of elements is something like :
m' = g*(n^2)
(g and k are constants)
If we put n in function of m' :
n = (m'/g)^(1/2)
We substitute this :
t = k*(n^3) = k*(m'/g)^(3/2) /////
t = (k/(g^(3/2)) * (m'^(3/2))
left part is constant
so
T = Theta(m^(3/2))
greatings, Daniel</p>

Title: Asymptotic running time of algorithm

Body:
Given the following algorithm of multiplying matrices which are all n x n

for(int i=1;i<=n;i++){
    for(int j=1;j<=n;j++){
       s=0;
       for(int k=1;k<=n;k++){
          s+=A[i][k]*B[k][j];
          C[i][j]=s;
       }
    }
}
return s;

The asymptotic running time is Theta(n^3) ,however what does this mean :

If we consider the running time  as a function of the length of the input the order growth is Theta( m ^(3/2) ) where m is the length of the input i.e m is the order of the number elements in the matrices  and m = Theta(n^2)

Why the growth of the input is Theta( m ^(3/2) ) and Is the whole asymptotic running time Theta(n^2)?


答:
In your code, the iframe is wrong. You need to specify "myLink" as id not as src.

Then you need to transform the youtube link (which is like "https://www.youtube.com/watch?v={videoId}") into the iframe link (which is like "https://www.youtube.com/embed/{videoId}"). To achieve this you need to learn about regexp. The following will work:

var ytLink = prompt('Give me a youtube link please !');
var iframe = document.getElementById('youtube');
var ytId   = ytLink.match(/v=([-A-Za-z]+)/)[1];

iframe.src = 'https://www.youtube.com/embed/' + ytId;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><iframe width="560" height="315" src="" id="youtube" frameborder="0" allowfullscreen></iframe></code>```

I recommend you to learn more about regex on the MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

Title: Using JavaScript Variables in HTML code

Body:
In your code, the iframe is wrong. You need to specify "myLink" as id not as src.

Then you need to transform the youtube link (which is like "https://www.youtube.com/watch?v={videoId}") into the iframe link (which is like "https://www.youtube.com/embed/{videoId}"). To achieve this you need to learn about regexp. The following will work:

var ytLink = prompt('Give me a youtube link please !');
var iframe = document.getElementById('youtube');
var ytId   = ytLink.match(/v=([-A-Za-z]+)/)[1];

iframe.src = 'https://www.youtube.com/embed/' + ytId;

<iframe width="560" height="315" src="" id="youtube" frameborder="0" allowfullscreen></iframe>

I recommend you to learn more about regex on the MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions


问:
Collection View, Auto layout UICollectionViewFlowLayout and itemSize
I am really struggling to achieve something fairly simple:
I would like to create a horizontal collection view where the UICollectionViewCells are the size of the UICollectionView itself.

So far so good, I have set up a view controller in the storyboard which looks something like this (notice: collection view is not equal to view controller's size):

```<code>+--------------------------+
|                          |
|         Some View        |
+--------------------------+ <----- constraint
|                          |
|                          |
|      Collection View     | <----- left and right constraint
|                          |
|                          |
+--------------------------+ <----- constraint
|                          |
|      Some other view     |
+--------------------------+
</code>```

Issue:

The collection view's cells do not seem to be the size of the collection view, despite explicitly setting the itemSize property of the collection view's flow layout property to the collection view's frame's size in the viewDidLoad() method of the controller.

In viewDidLoad() I do something like this:

```<code>let layout = self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = self.collectionView.frame.size
layout.headerReferenceSize = CGSizeZero
layout.footerReferenceSize = CGSizeZero
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
</code>```

The strange thing:

When I put this code into awakeFromNib(), it seems as if the collectionView is not hooked up -> crash.
However, when I put the code into viewDidAppear(), the collection view shortly appears with wrongly sized cells (whatever is set in the storyboard) and shortly after, the cells update to the correct size.

Can anybody help me with this issue ?

 EDIT:

Also seems to work in viewDidLayoutSubviews(). Not sure why, but I guess it is because the constraints have not been applied in viewDidLoad() yet.

答:
You might wanna try the following:
In the ViewController, implement the didLayoutSubviews() function as follows:</p>

```<code>override func didLayoutSubviews() {
    super.didLayoutSubviews()
    let collectionViewSize = self.collectionView.bounds.size
    if let flowLayout = self.collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
        flowLayout.itemSize = collectionViewSize
    }
}
</code>```

Body:
I am really struggling to achieve something fairly simple:
I would like to create a horizontal collection view where the UICollectionViewCells are the size of the UICollectionView itself.

So far so good, I have set up a view controller in the storyboard which looks something like this (notice: collection view is not equal to view controller's size):

+--------------------------+
|                          |
|         Some View        |
+--------------------------+ <----- constraint
|                          |
|                          |
|      Collection View     | <----- left and right constraint
|                          |
|                          |
+--------------------------+ <----- constraint
|                          |
|      Some other view     |
+--------------------------+

Issue:

The collection view's cells do not seem to be the size of the collection view, despite explicitly setting the itemSize property of the collection view's flow layout property to the collection view's frame's size in the viewDidLoad() method of the controller.

In viewDidLoad() I do something like this:

let layout = self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = self.collectionView.frame.size
layout.headerReferenceSize = CGSizeZero
layout.footerReferenceSize = CGSizeZero
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0

The strange thing:

When I put this code into awakeFromNib(), it seems as if the collectionView is not hooked up -> crash.
However, when I put the code into viewDidAppear(), the collection view shortly appears with wrongly sized cells (whatever is set in the storyboard) and shortly after, the cells update to the correct size.

Can anybody help me with this issue ?

 EDIT:

Also seems to work in viewDidLayoutSubviews(). Not sure why, but I guess it is because the constraints have not been applied in viewDidLoad() yet.

Body:
You might wanna try the following:
In the ViewController, implement the didLayoutSubviews() function as follows:

override func didLayoutSubviews() {
    super.didLayoutSubviews()
    let collectionViewSize = self.collectionView.bounds.size
    if let flowLayout = self.collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
        flowLayout.itemSize = collectionViewSize
    }
}


问:
Make a hash table using smart pointers?
I'm trying to make a hashtable by using smart pointers, but I'm not sure if I am doing it right. I've been trying to play with two combinations of them, but I am afraid I don't know how to initialize the table to be empty? Maybe that is the wrong verbage, but I am stuck and I need to be pointed in the right direction.

My hashNode:

```<code>struct{
    hashNode(int k, std::string i) : key(k), item(i){};

    int key;
    std::string item;
}
</code>```

My hashtable:

```<code>class Hashtable
{
public:

    Hashtable(); //not sure how to build the constructor build an empty table.

    int hashFunction(int key);
    int find(int key);
    void insert(int key, std::string item);
    void remove(int key);

private:

    int tableSize = 10;
    std::shared_ptr<std::shared_ptr<hashNode>> hashTable;
    //std::vector<std::shared_ptr<hashNode>> hashTable;
};
</code>```

I am stuck here, as I don't know if I am implementing my hashTable correctly or not. Or, if this is just a bad idea to go with. Any advice would do.

答:
Change your hashNode attribute member to be a single pointer using std::unique_ptr. Then, in HashTable's constructor you can initialise it with std::make_unique.

In you HashTable.h

```<code>class Hashtable {
public:
   Hashtable();

   int hashFunction(int key);
   int find(int key);
   void insert(int key, std::string item);
   void remove(int key);

private:
   int tableSize = 10;
   std::unique_ptr<hashNode[]> hashTable;  // As stated in the comments.
};
</code>```

In your HashTable.cpp

```<code>Hashtable::Hashtable() {
   hashTable = std::make_unique<hashNode[10]>();
}
</code>```

Title: Make a hash table using smart pointers?

Body:
I'm trying to make a hashtable by using smart pointers, but I'm not sure if I am doing it right. I've been trying to play with two combinations of them, but I am afraid I don't know how to initialize the table to be empty? Maybe that is the wrong verbage, but I am stuck and I need to be pointed in the right direction.

My hashNode:

struct{
    hashNode(int k, std::string i) : key(k), item(i){};

    int key;
    std::string item;
}

My hashtable:

class Hashtable
{
public:

    Hashtable(); //not sure how to build the constructor build an empty table.

    int hashFunction(int key);
    int find(int key);
    void insert(int key, std::string item);
    void remove(int key);

private:

    int tableSize = 10;
    std::shared_ptr<std::shared_ptr<hashNode>> hashTable;
    //std::vector<std::shared_ptr<hashNode>> hashTable;
};

I am stuck here, as I don't know if I am implementing my hashTable correctly or not. Or, if this is just a bad idea to go with. Any advice would do.

Body:
Change your hashNode attribute member to be a single pointer using std::unique_ptr. Then, in HashTable's constructor you can initialise it with std::make_unique.

In you HashTable.h

class Hashtable {
public:
   Hashtable();

   int hashFunction(int key);
   int find(int key);
   void insert(int key, std::string item);
   void remove(int key);

private:
   int tableSize = 10;
   std::unique_ptr<hashNode[]> hashTable;  // As stated in the comments.
};

In your HashTable.cpp

Hashtable::Hashtable() {
   hashTable = std::make_unique<hashNode[10]>();
}


问:
Can't find C++ 6.0 IDE in MSDN download area
I think this has something to do with a lawsuit with Sun over Java - but I can't verify this.  I'm trying to get a legacy code base to compile 1st so I can begin upgrading it.

Also: I suppose I need to know where/how I CAN get the C++ 6.0 IDE install.

Digging through the "Pile of DVD's in the old developer's drawer" right now.

答:
Yes, this was a result of the 2001 settlement between Microsoft and Sun over the Microsoft Java Virtual Machine.  Several products were axed because of this, including Windows 98, Windows Me, Office 2000, Office XP, IE 5.5

Best place to find a license is at an auction site.  It was always available at Ebay for example, prices have been steadily climbing.


问:
Swift3 JSON using Alamofire
I'm new to Alamofire and Swift.

Now, I'm trying to convert JSON from the API, but I don't know how to convert it.

API like this :

```<code>[
{
  "myid": "10303210302003",
  "mySubid": "10303210302003",
  "area_pkid": "3"
},

{
  "myid": "10303210302004",
  "mySubid": "10303210302004",
  "area_pkid": "4"
},
....]
</code>```

I'm so confused about "[" and "]" , I don't know how to convert it and get myid.

Here is my code

```<code>    Alamofire.request(MyURL, method: .get).responseJSON { (response) in

       guard let totalJSON = response.result.value as? [String : Any] else { return } // My code is just return !! WHY??

    }
</code>```

答:
Yep, [] is an array and {} represents as Dictionary. So to get myid just do:

```<code>   guard let totalJSON = response.result.value as? [Any] else { return }
   if let i = a["myID"] as? String, let a = totalJSON[0] as? [String: Any]
   {
      print(i)
   }
</code>```

Title: Swift3 JSON using Alamofire

Body:
I'm new to Alamofire and Swift.

Now, I'm trying to convert JSON from the API, but I don't know how to convert it.

API like this :

[
{
  "myid": "10303210302003",
  "mySubid": "10303210302003",
  "area_pkid": "3"
},

{
  "myid": "10303210302004",
  "mySubid": "10303210302004",
  "area_pkid": "4"
},
....]

I'm so confused about "[" and "]" , I don't know how to convert it and get myid.

Here is my code

    Alamofire.request(MyURL, method: .get).responseJSON { (response) in

       guard let totalJSON = response.result.value as? [String : Any] else { return } // My code is just return !! WHY??

    }

Body:
Yep, [] is an array and {} represents as Dictionary. So to get myid just do:

   guard let totalJSON = response.result.value as? [Any] else { return }
   if let i = a["myID"] as? String, let a = totalJSON[0] as? [String: Any]
   {
      print(i)
   }


问:
How should I handle "No internet connection" with Retrofit on Android
I'd like to handle situations when there is no internet connection. Usually I'd run:

```<code>ConnectivityManager cm =
    (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
                  activeNetwork.isConnectedOrConnecting();
</code>```

(from here) before sending the requests to the network and notify user if there were no internet connection.

From what I saw Retrofit does not handle this situation specifically. If there is no internet connection I'll just get RetrofitError with timeout as a reason.

If I'd like to incorporate this kind of check into every HTTP request with Retrofit, how should I do it? Or should I do it at all.

Thanks

Alex

答:
you can use this code

Response.java

```<code>import com.google.gson.annotations.SerializedName;

/**
 * Created by hackro on 19/01/17.
 */

public class Response {
    @SerializedName("status")
    public String status;

    public void setStatus(String status) {
        this.status = status;
    }

    public String getStatus() {
        return status;
    }

    @SuppressWarnings({"unused", "used by Retrofit"})
    public Response() {
    }

    public Response(String status) {
        this.status = status;
    }
}
</code>```

NetworkError.java

```<code>import android.text.TextUtils;

import com.google.gson.Gson;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import retrofit2.adapter.rxjava.HttpException;

import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;

/**
 * Created by hackro on 19/01/17.
 */

public class NetworkError extends Throwable {
    public static final String DEFAULT_ERROR_MESSAGE = "Please try again.";
    public static final String NETWORK_ERROR_MESSAGE = "No Internet Connection!";
    private static final String ERROR_MESSAGE_HEADER = "Error Message";
    private final Throwable error;

    public NetworkError(Throwable e) {
        super(e);
        this.error = e;
    }

    public String getMessage() {
        return error.getMessage();
    }

    public boolean isAuthFailure() {
        return error instanceof HttpException &&
                ((HttpException) error).code() == HTTP_UNAUTHORIZED;
    }

    public boolean isResponseNull() {
        return error instanceof HttpException && ((HttpException) error).response() == null;
    }

    public String getAppErrorMessage() {
        if (this.error instanceof IOException) return NETWORK_ERROR_MESSAGE;
        if (!(this.error instanceof HttpException)) return DEFAULT_ERROR_MESSAGE;
        retrofit2.Response<?> response = ((HttpException) this.error).response();
        if (response != null) {
            String status = getJsonStringFromResponse(response);
            if (!TextUtils.isEmpty(status)) return status;

            Map<String, List<String>> headers = response.headers().toMultimap();
            if (headers.containsKey(ERROR_MESSAGE_HEADER))
                return headers.get(ERROR_MESSAGE_HEADER).get(0);
        }

        return DEFAULT_ERROR_MESSAGE;
    }

    protected String getJsonStringFromResponse(final retrofit2.Response<?> response) {
        try {
            String jsonString = response.errorBody().string();
            Response errorResponse = new Gson().fromJson(jsonString, Response.class);
            return errorResponse.status;
        } catch (Exception e) {
            return null;
        }
    }

    public Throwable getError() {
        return error;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        NetworkError that = (NetworkError) o;

        return error != null ? error.equals(that.error) : that.error == null;

    }

    @Override
    public int hashCode() {
        return error != null ? error.hashCode() : 0;
    }
}
</code>```

Implementation in your methods

```<code>        @Override
        public void onCompleted() {
            super.onCompleted();
        }

        @Override
        public void onError(Throwable e) {
            super.onError(e);
            networkError.setError(e);
            Log.e("Error:",networkError.getAppErrorMessage());
        }

        @Override
        public void onNext(Object obj) {   super.onNext(obj);
    }
</code>```

Body:
I'd like to handle situations when there is no internet connection. Usually I'd run:

ConnectivityManager cm =
    (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
                  activeNetwork.isConnectedOrConnecting();

(from here) before sending the requests to the network and notify user if there were no internet connection.

From what I saw Retrofit does not handle this situation specifically. If there is no internet connection I'll just get RetrofitError with timeout as a reason.

If I'd like to incorporate this kind of check into every HTTP request with Retrofit, how should I do it? Or should I do it at all.

Thanks

Alex

Body:
you can use this code

Response.java

import com.google.gson.annotations.SerializedName;

/**
 * Created by hackro on 19/01/17.
 */

public class Response {
    @SerializedName("status")
    public String status;

    public void setStatus(String status) {
        this.status = status;
    }

    public String getStatus() {
        return status;
    }

    @SuppressWarnings({"unused", "used by Retrofit"})
    public Response() {
    }

    public Response(String status) {
        this.status = status;
    }
}

NetworkError.java

import android.text.TextUtils;

import com.google.gson.Gson;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import retrofit2.adapter.rxjava.HttpException;

import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;

/**
 * Created by hackro on 19/01/17.
 */

public class NetworkError extends Throwable {
    public static final String DEFAULT_ERROR_MESSAGE = "Please try again.";
    public static final String NETWORK_ERROR_MESSAGE = "No Internet Connection!";
    private static final String ERROR_MESSAGE_HEADER = "Error Message";
    private final Throwable error;

    public NetworkError(Throwable e) {
        super(e);
        this.error = e;
    }

    public String getMessage() {
        return error.getMessage();
    }

    public boolean isAuthFailure() {
        return error instanceof HttpException &&
                ((HttpException) error).code() == HTTP_UNAUTHORIZED;
    }

    public boolean isResponseNull() {
        return error instanceof HttpException && ((HttpException) error).response() == null;
    }

    public String getAppErrorMessage() {
        if (this.error instanceof IOException) return NETWORK_ERROR_MESSAGE;
        if (!(this.error instanceof HttpException)) return DEFAULT_ERROR_MESSAGE;
        retrofit2.Response<?> response = ((HttpException) this.error).response();
        if (response != null) {
            String status = getJsonStringFromResponse(response);
            if (!TextUtils.isEmpty(status)) return status;

            Map<String, List<String>> headers = response.headers().toMultimap();
            if (headers.containsKey(ERROR_MESSAGE_HEADER))
                return headers.get(ERROR_MESSAGE_HEADER).get(0);
        }

        return DEFAULT_ERROR_MESSAGE;
    }

    protected String getJsonStringFromResponse(final retrofit2.Response<?> response) {
        try {
            String jsonString = response.errorBody().string();
            Response errorResponse = new Gson().fromJson(jsonString, Response.class);
            return errorResponse.status;
        } catch (Exception e) {
            return null;
        }
    }

    public Throwable getError() {
        return error;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        NetworkError that = (NetworkError) o;

        return error != null ? error.equals(that.error) : that.error == null;

    }

    @Override
    public int hashCode() {
        return error != null ? error.hashCode() : 0;
    }
}

Implementation in your methods

        @Override
        public void onCompleted() {
            super.onCompleted();
        }

        @Override
        public void onError(Throwable e) {
            super.onError(e);
            networkError.setError(e);
            Log.e("Error:",networkError.getAppErrorMessage());
        }

        @Override
        public void onNext(Object obj) {   super.onNext(obj);
    }


问:
Python parser that makes parentheses according arithmetic priority
How to make a parser that will make parentheses according arithmetical priority in expressions using the pyparsing library?
for example * has higher priority than +.

It should do like this:

```<code>»> print(wholeexp.parseString('3+5-2'))
[[['3', '+', '5'], '-', '2']]
»> print(wholeexp.parseString('3+(5-2)'))
[['3', '+', ['5', '-', '2']]]
»> print(wholeexp.parseString('3+5-2*4'))
[[['3', '+', '5'], '-', ['2', '*', '4']]]
</code>```

I tried the following, but it doesn't work very well. How should we change expr here:

```<code>from pyparsing import *

numb = Word(nums)
leftpar = Suppress('(')
rightpar = Suppress(')')

expr = Forward()
expr << Or( [numb,
    Group(leftpar + expr + "+" + expr + rightpar),
    Group(leftpar + expr + "-" + expr + rightpar),
    Group(leftpar + expr + "*" + expr + rightpar)] )

wholeexp = expr + StringEnd()
</code>```

答:
Your approach is similar to that used in this pyparsing example: http://pyparsing.wikispaces.com/file/view/fourFn.py . But more recent versions of pyparsing introduced operatorPrecedence, more recently renamed infixNotation, and your 4-function arithmetic expression parser looks like this:

```<code>import pyparsing as pp

integer = pp.pyparsing_common.integer()

four_fn_arith_expr = pp.infixNotation(integer,
                                    [
                                        # leading sign
                                        (pp.oneOf("+ -"), 1, pp.opAssoc.RIGHT,),
                                        # multiplication and division
                                        (pp.oneOf("* /"), 2, pp.opAssoc.LEFT,),
                                        # addition and subtraction
                                        (pp.oneOf("+ -"), 2, pp.opAssoc.LEFT,),
                                    ])
</code>```

Here are your test cases run with this parser:

```<code>tests = """
    3+5-2
    3+(5-2)
    3+5--2
    3+5-2*4
    """
four_fn_arith_expr.runTests(tests, fullDump=False)
</code>```

Gives:

```<code>3+5-2
[[3, '+', 5, '-', 2]]

3+(5-2)
[[3, '+', [5, '-', 2]]]

3+5--2
[[3, '+', 5, '-', ['-', 2]]]

3+5-2*4
[[3, '+', 5, '-', [2, '*', 4]]]
</code>```

Body:
How to make a parser that will make parentheses according arithmetical priority in expressions using the pyparsing library?
for example * has higher priority than +.

It should do like this:

»> print(wholeexp.parseString('3+5-2'))
[[['3', '+', '5'], '-', '2']]
»> print(wholeexp.parseString('3+(5-2)'))
[['3', '+', ['5', '-', '2']]]
»> print(wholeexp.parseString('3+5-2*4'))
[[['3', '+', '5'], '-', ['2', '*', '4']]]

I tried the following, but it doesn't work very well. How should we change expr here:

from pyparsing import *

numb = Word(nums)
leftpar = Suppress('(')
rightpar = Suppress(')')

expr = Forward()
expr << Or( [numb,
    Group(leftpar + expr + "+" + expr + rightpar),
    Group(leftpar + expr + "-" + expr + rightpar),
    Group(leftpar + expr + "*" + expr + rightpar)] )

wholeexp = expr + StringEnd()

Body:
Your approach is similar to that used in this pyparsing example: http://pyparsing.wikispaces.com/file/view/fourFn.py . But more recent versions of pyparsing introduced operatorPrecedence, more recently renamed infixNotation, and your 4-function arithmetic expression parser looks like this:

import pyparsing as pp

integer = pp.pyparsing_common.integer()

four_fn_arith_expr = pp.infixNotation(integer,
                                    [
                                        # leading sign
                                        (pp.oneOf("+ -"), 1, pp.opAssoc.RIGHT,),
                                        # multiplication and division
                                        (pp.oneOf("* /"), 2, pp.opAssoc.LEFT,),
                                        # addition and subtraction
                                        (pp.oneOf("+ -"), 2, pp.opAssoc.LEFT,),
                                    ])

Here are your test cases run with this parser:

tests = """
    3+5-2
    3+(5-2)
    3+5--2
    3+5-2*4
    """
four_fn_arith_expr.runTests(tests, fullDump=False)

Gives:

3+5-2
[[3, '+', 5, '-', 2]]

3+(5-2)
[[3, '+', [5, '-', 2]]]

3+5--2
[[3, '+', 5, '-', ['-', 2]]]

3+5-2*4
[[3, '+', 5, '-', [2, '*', 4]]]


问:
React: Unexpected token import when running npm start
I have a React project that works locally when I open its path in chrome. However, when trying to deploy to Heroku (or running npm start), I get this error:

```<code>import React from 'react';
^^^^^^
SyntaxError: Unexpected token import
</code>```

I've scoured StackOverflow and Heroku's support page to no avail.

Here's my package.json:

```<code>{
  "name": "my-app-name",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "webpack": "webpack",
    "start": "node ./my-app-name.jsx",
    "postinstall": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "babel-cli": "^6.24.0",
    "babel-core": "^6.24.0",
    "babel-loader": "^6.4.1",
    "babel-preset-es2015": "^6.24.0",
    "babel-preset-react": "^6.23.0",
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "react-redux": "^5.0.3",
    "react-router": "^4.0.0",
    "react-router-dom": "^4.0.0",
    "redux": "^3.6.0",
    "webpack": "^2.3.2"
  },
  "engines": {
    "node": "6.2.1",
    "npm": "4.4.4"
  }
}
</code>```

And my webpack.config.js:

```<code>module.exports = {
  entry: "./my-app-name.jsx",
  output: {
    filename: "./bundle.js"
  },
  module: {
    loaders: [
      {
        test: [/\.jsx?$/, /\.js?$/],
        exclude: /(node_modules)/,
        loader: 'babel-loader',
        query: {
          presets: ['es2015', 'react']
        }
      }
    ]
  },
  devtool: 'source-map',
  resolve: {
    extensions: ["*",".js", ".jsx" ]
  }
};
</code>```

My node and npm versions are the same as listed in package.json. I've triple checked to make sure everything is installed correctly and none of the other StackOverflow answers have helped. Surely it has to be some sort of issue with Babel (due to it not recognizing import) but I just can't figure out what it is.

答: my-app-name.jsx is not the transpiled build. Instead of node ./my-app-name.jsx, you need to point Node to start the transpiled build like this node ./bundle.js

Body:
I have a React project that works locally when I open its path in chrome. However, when trying to deploy to Heroku (or running npm start), I get this error:

import React from 'react';
^^^^^^
SyntaxError: Unexpected token import

I've scoured StackOverflow and Heroku's support page to no avail.

Here's my package.json:

{
  "name": "my-app-name",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "webpack": "webpack",
    "start": "node ./my-app-name.jsx",
    "postinstall": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "babel-cli": "^6.24.0",
    "babel-core": "^6.24.0",
    "babel-loader": "^6.4.1",
    "babel-preset-es2015": "^6.24.0",
    "babel-preset-react": "^6.23.0",
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "react-redux": "^5.0.3",
    "react-router": "^4.0.0",
    "react-router-dom": "^4.0.0",
    "redux": "^3.6.0",
    "webpack": "^2.3.2"
  },
  "engines": {
    "node": "6.2.1",
    "npm": "4.4.4"
  }
}

And my webpack.config.js:

module.exports = {
  entry: "./my-app-name.jsx",
  output: {
    filename: "./bundle.js"
  },
  module: {
    loaders: [
      {
        test: [/\.jsx?$/, /\.js?$/],
        exclude: /(node_modules)/,
        loader: 'babel-loader',
        query: {
          presets: ['es2015', 'react']
        }
      }
    ]
  },
  devtool: 'source-map',
  resolve: {
    extensions: ["*",".js", ".jsx" ]
  }
};

My node and npm versions are the same as listed in package.json. I've triple checked to make sure everything is installed correctly and none of the other StackOverflow answers have helped. Surely it has to be some sort of issue with Babel (due to it not recognizing import) but I just can't figure out what it is.


问:
.Net core and Sqlite deployment to azure failing
I'm having difficulty deploying a .net core app using sqlite to azure. The error message I'm getting in my logs is:

```<code>fail: Microsoft.EntityFrameworkCore.Query.RelationalQueryCompilationContextFactory[1]
      An exception occurred in the database while iterating the results of a query.
      Microsoft.Data.Sqlite.SqliteException: SQLite Error 1: 'no such table: AspNetUserLogins'.
         at Microsoft.Data.Sqlite.Interop.MarshalEx.ThrowExceptionForRC(Int32 rc, Sqlite3Handle db)
         at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader(CommandBehavior behavior)
         at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
         at Microsoft.Data.Sqlite.SqliteCommand.<ExecuteDbDataReaderAsync>d__53.MoveNext()
      --- End of stack trace from previous location where exception was thrown ---
</code>```

This leads me to believe that my migrations aren't being applied correctly.

In my startup class I have the following:

```<code>    services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlite(Configuration.GetConnectionString("ConnectionName")));
</code>```

and a connection string of :

```<code>"ConnectionName": "Filename=./MyApp.sqlite"
</code>```

This works perfectly locally, but when I deploy to azure I get the given error. Any ideas what's gone wrong and what steps I can take to fix it?

答:
I've got a workaround.

I haven't worked out a way to apply migrations to sqlite as part of my deployment, everything I've tried on that front has caused errors. For the time being I found that finding the location of the .sqlite file in kudu, and then replacing it with my local .sqlite file is an acceptable workaround.

Body:
I'm having difficulty deploying a .net core app using sqlite to azure. The error message I'm getting in my logs is:

fail: Microsoft.EntityFrameworkCore.Query.RelationalQueryCompilationContextFactory[1]
      An exception occurred in the database while iterating the results of a query.
      Microsoft.Data.Sqlite.SqliteException: SQLite Error 1: 'no such table: AspNetUserLogins'.
         at Microsoft.Data.Sqlite.Interop.MarshalEx.ThrowExceptionForRC(Int32 rc, Sqlite3Handle db)
         at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader(CommandBehavior behavior)
         at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
         at Microsoft.Data.Sqlite.SqliteCommand.<ExecuteDbDataReaderAsync>d__53.MoveNext()
      --- End of stack trace from previous location where exception was thrown ---

This leads me to believe that my migrations aren't being applied correctly.

In my startup class I have the following:

    services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlite(Configuration.GetConnectionString("ConnectionName")));

and a connection string of :

"ConnectionName": "Filename=./MyApp.sqlite"

This works perfectly locally, but when I deploy to azure I get the given error. Any ideas what's gone wrong and what steps I can take to fix it?


问:
Recommended structure for high traffic website
I'm rewriting a big website, that needs very solid architecture, here are my few questions, and pardon me for mixing apples and oranges and probably kiwi too:) I did a lot of research and ended up totally confused.

Main question: Which approach would you take in building a big website expected to grow in every way?

Single entry point, pages data in the database, pulled by associating GET variable with database entry (?pageid=whatever)

Single entry point, pages data in separate files, included based on GET variable (?pageid=whatever would include whatever.php)

MVC (Alright guys, I'm all for it, but can't grasp the concept besides checking all tutorials and frameworks out there, do they store "view" in database? Seems to me from examples that if you have 1000 pages of same kind they can be shaped by 1 model, but I'll still need to have 1000 "views" files?)

PAC - this sounds even more logical to me, but didn't find much resources - if this is a good way to go, can you recommend any books or links?

DAL/DAO/DDD - i learned about these terms by diligently reading through stack overflow before posting question. Not sure if it belongs to this list

Sit down and create my own architecture (likely to do if nobody enlightens me here:)

Something not mentioned...

Thanks.

答: I would suggest to create a mock app with some of the web mvc frameworks in the wild and pick one, with which your development was smooth enough. Establishing your code on a solid basis is fundamental, if you want to grasp concepts of mvc and be ready to add new functionality to your web easily.</p>


问:
Time complexity of recursive algorithm for denomination task
I calculate all possible variants of input number k for 1, 2 or 5 numbers. It's easy algorithm for understanding:

```<code>//1,2,5
func foo(k: Int, result: [Int] = []) {
    if k == 0 {
        print(result)
        return
    }

    var one = result
    one.append(1)
    foo(k: k-1, result: one)

    if k >= 2 {
        var two = result
        two.append(2)
        foo(k: k-2, result: two)
    }

    if k >= 5 {
        var five = result
        five.append(5)
        foo(k: k-5, result: five)
    }
}
</code>```

So, it works. My question is what is complexity (big O) of this algorithm?
I assume it's 3^k, because of 3 recursive calls inside.
Please prove or explain your opinion.

答:
Your analysis of O(3^n) is correct, but it's not a tight bound because although the branching factor is (mostly) 3, the height of the right branches (n-5) is smaller than the middle (n-2) and left (n-1) branch.

The recurrence relation describing your code is: T(n) = T(n-1) + T(n-2) + T(n-5) + 1

Subtracting T(n+1) from T(n) (a standard trick to get rid of the constant) we get:

```<code>T(n+1) - T(n) = T(n) + T(n-1) + T(n-4) + 1 - T(n-1) - T(n-2) - T(n-5) - 1
T(n+1) = 2T(n) - T(n-2) + T(n-4) - T(n-5)
</code>```

This is a homogoneous linear recurrence relation, so has solutions of the form:

```<code>sum(A_i * a_i^n for i=0..5)
</code>```

where A_i are (complex) constants, and a_i are roots of the equation x^6 = 2x^5 - x^3 + x - 1.

So the order of growth of T(n) will be O(a^n) where a is the largest magnitude root of the equation. That happens to be real, and is approximately 1.7049.

So your code runs in O(1.705^n) time. Which is quite a lot better than O(3^n), although still of course exponential.

Body:
I calculate all possible variants of input number k for 1, 2 or 5 numbers. It's easy algorithm for understanding:

//1,2,5
func foo(k: Int, result: [Int] = []) {
    if k == 0 {
        print(result)
        return
    }

    var one = result
    one.append(1)
    foo(k: k-1, result: one)

    if k >= 2 {
        var two = result
        two.append(2)
        foo(k: k-2, result: two)
    }

    if k >= 5 {
        var five = result
        five.append(5)
        foo(k: k-5, result: five)
    }
}

So, it works. My question is what is complexity (big O) of this algorithm?
I assume it's 3^k, because of 3 recursive calls inside.
Please prove or explain your opinion.

Body:
Your analysis of O(3^n) is correct, but it's not a tight bound because although the branching factor is (mostly) 3, the height of the right branches (n-5) is smaller than the middle (n-2) and left (n-1) branch.

The recurrence relation describing your code is: T(n) = T(n-1) + T(n-2) + T(n-5) + 1

Subtracting T(n+1) from T(n) (a standard trick to get rid of the constant) we get:

T(n+1) - T(n) = T(n) + T(n-1) + T(n-4) + 1 - T(n-1) - T(n-2) - T(n-5) - 1
T(n+1) = 2T(n) - T(n-2) + T(n-4) - T(n-5)

This is a homogoneous linear recurrence relation, so has solutions of the form:

sum(A_i * a_i^n for i=0..5)

where A_i are (complex) constants, and a_i are roots of the equation x^6 = 2x^5 - x^3 + x - 1.

So the order of growth of T(n) will be O(a^n) where a is the largest magnitude root of the equation. That happens to be real, and is approximately 1.7049.

So your code runs in O(1.705^n) time. Which is quite a lot better than O(3^n), although still of course exponential.


问:
How to implement a Toolbar?
I'm new to Android Studio, and I am going through the tutorials on the website.

It shows buttons in the toolbar like, 'hide constraints' 'default margins', and 'autoconnect'. But I can't find these buttons in my Android Studio.

Can anyone help me find them and make them visible in the Toolbar.

答: Those are visible when you use a ConstrainedLayout in your Layout's xml file.</p>

Title: How to implement a Toolbar?


问:
Java println weird output
I'm getting a weird output from running this simple java program.

The output is: 0 4 2 -6

Why does the x++ print 0, it should be printing 4.

```<code>import java.util.*;
import java.io.*;

public class Java1 {

    public static void main(String[] args) throws IOException {

        int x = 4;
        int y = -5;

        System.out.println(x++ + " " + func(x++, y) + " " + --y);
    }

    public static int func(int work, int y) {

        int z = work + y;

        work++;

        y++;
        System.out.print(z + " ");
        return z + work + y;

    }
}
</code>```

答: func(x++, y) is executed first, so 0 comes from System.out.print(z + " "); in func.

Title: Java println weird output

Body:
I'm getting a weird output from running this simple java program.

The output is: 0 4 2 -6

Why does the x++ print 0, it should be printing 4.

import java.util.*;
import java.io.*;

public class Java1 {

    public static void main(String[] args) throws IOException {

        int x = 4;
        int y = -5;

        System.out.println(x++ + " " + func(x++, y) + " " + --y);
    }

    public static int func(int work, int y) {

        int z = work + y;

        work++;

        y++;
        System.out.print(z + " ");
        return z + work + y;

    }
}


答: Okay, here is what's going on: First x++ is evaluated, returning 4 (which is later printed) and leaving x at 5. Then x++ is evaluated again, passing 5 to func. Then func is evaluated with 5 and -5 parameters. In here z is 0 (5 + (-5) = 0) which is then printed (BEFORE the println in the main method. func then returns 2 (0 + 6 + (-4)) which is also added to the string. Finally --y results in -6. Now the println in the main method prints its string (4 2 -6).

Title: Java println weird output