问:
Is there an example XML document that uses every feature of XML for testing?
Does anyone know where I can get a canonical XML document that uses every feature of the XML 1.0 specification that aren't mutually exclusive?

Not including various encoding flavors.

If I can get a single document encoded in UTF-8 that would be fine.

答:
It is not possible for one single document to use every feature: for example if a document uses UTF-16 encoding then it cannot also use UTF-8 encoding.

The W3C XML 1.0 Conformance Test Suite can be downloaded from http://www.w3.org/XML/Test/


来源: stackexchange

问:
How to convert corresponding character sequence from a dictionary into a readable string?
My problem states:

Write a function, called decompress, that accepts a string and a dictionary as input. The dictionary maps special character strings to sequences of characters. The function
goes through the argument string and if the character is in the dictionary, it converts it to the corresponding character sequence.  Your solution may use iteration, but it MUST be recursive (it must call itself).  Note that a special character may map to a sequence of characters that ALSO has a special character in it.  For example, in Test One below, the symbol table maps '$' to the string 'y' and '' maps to 'c'.  Hint: You can treat the resulting sequence as another string to decompress with the same symbol table.

Here is the code I currently have. I don't know how to take the values from the character sequence and convert them into the readable string. My code also raises a positional argument error.

```<code>def decompress(a_str, a_dict):

    new_string = ""

    for char in a_str:

        if char in a_dict:
            new_string.join(char)
        else:
            sub_problem = decompress(char, a_dict)
            new_string.join(sub_problem)

    return new_string

</code>```

Here are some output examples:

```<code>    Examples:
    >>> d_simple = {'*':'c','#':'00','$':'*y'}
    >>> decompress('$3#',d_simple) #Test One
    'cy300'
    >>> d = {'#':'hem','@':'T#','$':'t#','&':'$ as','*':' do ','%':' to'}
    >>> d.update({'^':' someone ', '~':'for ', '+':'~&'})
    >>> decompress("@ as can*has%*+ can't. And^has% speak up + has no voices."  ,d) #Test Two
    "Them as can do has to do for them as can't. And someone has to speak up for them as has no voices."
</code>```

答:
Your code is very close, I think you're just missing looking up the new/replacement characters in a_dict before calling the function again.

I think this is a correct solution?

def decompress(string, table):
    new_string = ''
    for char in string:
        new_char = table.get(char, char)
        if new_char == char:
            new_string += char
        else:
            new_string += decompress(new_char, table)
    return new_string
```

```d_simple = {'*': 'c', '#': '00', '$': '*y'}
print(decompress('$3#', d_simple))  # Test One
# 'cy300'
```

```d = {'#': 'hem', '@': 'T#', '$': 't#', '&': '$ as', '*': ' do ', '%': ' to'}
d.update({'^': ' someone ', '~': 'for ', '+': '~&'})
print(decompress("@ as can*has%*+ can't. And^has% speak up + has no voices.", d))  # Test Two
# "Them as can do has to do for them as can't. And someone has to speak up for them as has no voices."
```

ContentLicense: CC BY-SA 4.0

Body:
My problem states:

Write a function, called decompress, that accepts a string and a dictionary as input. The dictionary maps special character strings to sequences of characters. The function
goes through the argument string and if the character is in the dictionary, it converts it to the corresponding character sequence.  Your solution may use iteration, but it MUST be recursive (it must call itself).  Note that a special character may map to a sequence of characters that ALSO has a special character in it.  For example, in Test One below, the symbol table maps '$' to the string 'y' and '' maps to 'c'.  Hint: You can treat the resulting sequence as another string to decompress with the same symbol table.

Here is the code I currently have. I don't know how to take the values from the character sequence and convert them into the readable string. My code also raises a positional argument error.

def decompress(a_str, a_dict):

    new_string = ""

    for char in a_str:

        if char in a_dict:
            new_string.join(char)
        else:
            sub_problem = decompress(char, a_dict)
            new_string.join(sub_problem)

    return new_string

Here are some output examples:

    Examples:
    >>> d_simple = {'*':'c','#':'00','$':'*y'}
    >>> decompress('$3#',d_simple) #Test One
    'cy300'
    >>> d = {'#':'hem','@':'T#','$':'t#','&':'$ as','*':' do ','%':' to'}
    >>> d.update({'^':' someone ', '~':'for ', '+':'~&'})
    >>> decompress("@ as can*has%*+ can't. And^has% speak up + has no voices."  ,d) #Test Two
    "Them as can do has to do for them as can't. And someone has to speak up for them as has no voices."

Body:
Your code is very close, I think you're just missing looking up the new/replacement characters in a_dict before calling the function again.

I think this is a correct solution?

def decompress(string, table):
    new_string = ''
    for char in string:
        new_char = table.get(char, char)
        if new_char == char:
            new_string += char
        else:
            new_string += decompress(new_char, table)
    return new_string

d_simple = {'*': 'c', '#': '00', '$': '*y'}
print(decompress('$3#', d_simple))  # Test One
# 'cy300'

d = {'#': 'hem', '@': 'T#', '$': 't#', '&': '$ as', '*': ' do ', '%': ' to'}
d.update({'^': ' someone ', '~': 'for ', '+': '~&'})
print(decompress("@ as can*has%*+ can't. And^has% speak up + has no voices.", d))  # Test Two
# "Them as can do has to do for them as can't. And someone has to speak up for them as has no voices."


问:
Android NDK: Assertion failure: LOCAL_MAKEFILE is not defined
I was trying to build a project and when I execute a gradle task to build, I'm receiving the folllow error:

```<code>~/Library/Android/sdk/ndk/21.2.6472646/build/core/prebuilt-library.mk:20: *** Android NDK:  Assertion failure: LOCAL_MAKEFILE is not defined    .  Stop.
</code>```

I never used NDK before, and I'm not sure where I need to start.

Apparently LOCAL_MAKEFILE is not defined, but where should I define it?

Follows below, line 20 of prebuilt-library file:

```<code>    15
    16  # this file is included from prebuilt-shared-library.mk or
    17  # prebuilt-static-library.mk to declare prebuilt library binaries.
    18  #
    19
    20  $(call assert-defined, LOCAL_BUILD_SCRIPT LOCAL_MAKEFILE LOCAL_PREBUILT_PREFIX LOCAL_PREBUILT_SUFFIX)
    21
    22  $(call check-defined-LOCAL_MODULE,$(LOCAL_BUILD_SCRIPT))
    23  $(call check-LOCAL_MODULE,$(LOCAL_MAKEFILE))
    24  $(call check-LOCAL_MODULE_FILENAME)
    25
</code>```

Somebody have any idea what's going on?

Every help is welcome!

Thanks for now!

答: To solve that issue, I need to remove all the NDK version and using only the  19 and 20 versions.

Body:
I was trying to build a project and when I execute a gradle task to build, I'm receiving the folllow error:

~/Library/Android/sdk/ndk/21.2.6472646/build/core/prebuilt-library.mk:20: *** Android NDK:  Assertion failure: LOCAL_MAKEFILE is not defined    .  Stop.

I never used NDK before, and I'm not sure where I need to start.

Apparently LOCAL_MAKEFILE is not defined, but where should I define it?

Follows below, line 20 of prebuilt-library file:

    15
    16  # this file is included from prebuilt-shared-library.mk or
    17  # prebuilt-static-library.mk to declare prebuilt library binaries.
    18  #
    19
    20  $(call assert-defined, LOCAL_BUILD_SCRIPT LOCAL_MAKEFILE LOCAL_PREBUILT_PREFIX LOCAL_PREBUILT_SUFFIX)
    21
    22  $(call check-defined-LOCAL_MODULE,$(LOCAL_BUILD_SCRIPT))
    23  $(call check-LOCAL_MODULE,$(LOCAL_MAKEFILE))
    24  $(call check-LOCAL_MODULE_FILENAME)
    25

Somebody have any idea what's going on?

Every help is welcome!

Thanks for now!


问:
Saving Iterations in Different CSV Files
For a current project, I am planning to run several iterations of the script below and to save the results in different CSV files with a new file for each iteration (the CSV part is at the end of the script).

The given code currently shows the relevant results in the terminal while it only creates empty CSV files. I have spent days figuring out how to solve the situation but cannot get to a solution. Is there anyone who can help?

Note: I have updated the code in accordance with user recommendations while the original issue/challenge still persists.

```<code>import string
import json
import csv

import pandas as pd
import datetime
from dateutil.relativedelta import *

import numpy as np
import matplotlib.pyplot as plt

# Loading and reading dataset
file = open("Glassdoor_A.json", "r")
data = json.load(file)
df = pd.json_normalize(data)
df['Date'] = pd.to_datetime(df['Date'])

# Allocate periods for individual CSV file names
periods = pd.period_range('2009Q1','2018Q4',freq='Q')
ts = pd.Series(np.random.randn(40), periods)
type(ts.index)
intervals = ts.index

# Create individual empty files with headers
for i in intervals:
    name = 'Glassdoor_A_' + 'Text Main_' + str(i)
    with open(name+'.csv', 'w', newline='') as file:
        writer = csv.writer(file)

        # Create an empty dictionary
        d = dict()

        # Filtering by date
        start_date = pd.to_datetime('2009-01-01')
        end_date = pd.to_datetime('2009-03-31')
        last_end_date = pd.to_datetime('2017-12-31')
        mnthBeg = pd.offsets.MonthBegin(3)
        mnthEnd = pd.offsets.MonthEnd(3)
        while end_date <= last_end_date:
            filtered_dates = df[df.Date.between(start_date, end_date)]
            n = len(filtered_dates.index)
            print(f'Date range: {start_date.strftime("%Y-%m-%d")} - {end_date.strftime("%Y-%m-%d")},  {n} rows.')
            if n > 0:
                print(filtered_dates)
            start_date += mnthBeg
            end_date += mnthEnd

            # Processing Text Main section
            for index, row in filtered_dates.iterrows():
                line = row['Text Main']

                # Remove the leading spaces and newline character
                line = line.split(' ')
                line = [val.strip() for val in line]

                # Convert the characters in line to
                # lowercase to avoid case mismatch
                line = [val.lower() for val in line]

                # Remove the punctuation marks from the line
                line = [val.translate(val.maketrans("", "", string.punctuation)) for val in line]
                print(line)
                # Split the line into words
                # words = [val.split(" ") for val in line]
                # print(words)
                # Iterate over each word in line
                for word in line:
                    # Check if the word is already in dictionary
                    if word in d.keys():
                        # Increment count of word by 1
                        d[word] = d[word] + 1
                    else:
                        # Add the word to dictionary with count 1
                        d[word] = 1

                        print(d)

        # Print the contents of dictionary
        for key in list(d.keys()):
            print(key, ":", d[key])

            # Count the total number of words
            total = sum(d.values())
            percent = d[key] / total

            print(d[key], total, percent)

            # Save as CSV file
            while end_date <= last_end_date:

                for index, row in filtered_dates.iterrows():

                    for i in data:
                        name = 'Glassdoor_A_' + str(i)
                        with open(name+'.csv', 'a', newline='') as file:
                            writer.writerow(["Word", "Occurrences", "Percentage"])
                            writer.writerows([key, d[key], percent] for key in list(d.keys()))
</code>```

答:
Wrt your inner loop which writes the CSV files:

```<code># Create individual file names
for i in data:
    name = 'Glassdoor_A_' + str(i)

    # Save output in CSV file
    with open(name+'.csv', 'w', newline='') as file:
        ...
</code>```

⬆ is executed for each iteration of the outer loop for index, row in filtered_dates.iterrows():. So each iteration while overwrite the previously created files. Try using mode as 'a' (append) and write the headers with empty data outside of these two loops.

Without getting into the details of what you're calculating and writing out, the way to make it append data to the outfiles would be:

Create the files with just the headers at the start of the script.

The last inner loop should write to the files in append mode.

So, at the start of your script, add:

```<code>data = json.load(file)
# Create individual empty files with headers
for i in data:
    name = 'Glassdoor_A_' + str(i)
    with open(name+'.csv', 'w', newline='') as file:
        writer = csv.writer(file)  # you probably don't need to use the csv module for the first part
        writer.writerow(["Text Main Words", "Text Main Occurrences"])
        # nothing else here for now
</code>```

Then at the end of your script, for the inner most loop where you're writing out the data, do:

```<code>while end_date <= last_end_date:
    ...
    for index, row in filtered_dates.iterrows():
        ...
        for i in data:
            name = 'Glassdoor_A_' + str(i)
            with open(name+'.csv', 'a', newline='') as file:  # note the 'append' mode
                writer = csv.writer(file)
                writer.writerows([occurrence])

</code>```

Btw, that last line writer.writerows([occurrence]) should probably be writer.writerows(list(occurrence)) if occurrence is not already a list of tuples or a list of lists with two elements in each inner list.

Body:
For a current project, I am planning to run several iterations of the script below and to save the results in different CSV files with a new file for each iteration (the CSV part is at the end of the script).

The given code currently shows the relevant results in the terminal while it only creates empty CSV files. I have spent days figuring out how to solve the situation but cannot get to a solution. Is there anyone who can help?

Note: I have updated the code in accordance with user recommendations while the original issue/challenge still persists.

import string
import json
import csv

import pandas as pd
import datetime
from dateutil.relativedelta import *

import numpy as np
import matplotlib.pyplot as plt

# Loading and reading dataset
file = open("Glassdoor_A.json", "r")
data = json.load(file)
df = pd.json_normalize(data)
df['Date'] = pd.to_datetime(df['Date'])

# Allocate periods for individual CSV file names
periods = pd.period_range('2009Q1','2018Q4',freq='Q')
ts = pd.Series(np.random.randn(40), periods)
type(ts.index)
intervals = ts.index

# Create individual empty files with headers
for i in intervals:
    name = 'Glassdoor_A_' + 'Text Main_' + str(i)
    with open(name+'.csv', 'w', newline='') as file:
        writer = csv.writer(file)

        # Create an empty dictionary
        d = dict()

        # Filtering by date
        start_date = pd.to_datetime('2009-01-01')
        end_date = pd.to_datetime('2009-03-31')
        last_end_date = pd.to_datetime('2017-12-31')
        mnthBeg = pd.offsets.MonthBegin(3)
        mnthEnd = pd.offsets.MonthEnd(3)
        while end_date <= last_end_date:
            filtered_dates = df[df.Date.between(start_date, end_date)]
            n = len(filtered_dates.index)
            print(f'Date range: {start_date.strftime("%Y-%m-%d")} - {end_date.strftime("%Y-%m-%d")},  {n} rows.')
            if n > 0:
                print(filtered_dates)
            start_date += mnthBeg
            end_date += mnthEnd

            # Processing Text Main section
            for index, row in filtered_dates.iterrows():
                line = row['Text Main']

                # Remove the leading spaces and newline character
                line = line.split(' ')
                line = [val.strip() for val in line]

                # Convert the characters in line to
                # lowercase to avoid case mismatch
                line = [val.lower() for val in line]

                # Remove the punctuation marks from the line
                line = [val.translate(val.maketrans("", "", string.punctuation)) for val in line]
                print(line)
                # Split the line into words
                # words = [val.split(" ") for val in line]
                # print(words)
                # Iterate over each word in line
                for word in line:
                    # Check if the word is already in dictionary
                    if word in d.keys():
                        # Increment count of word by 1
                        d[word] = d[word] + 1
                    else:
                        # Add the word to dictionary with count 1
                        d[word] = 1

                        print(d)

        # Print the contents of dictionary
        for key in list(d.keys()):
            print(key, ":", d[key])

            # Count the total number of words
            total = sum(d.values())
            percent = d[key] / total

            print(d[key], total, percent)

            # Save as CSV file
            while end_date <= last_end_date:

                for index, row in filtered_dates.iterrows():

                    for i in data:
                        name = 'Glassdoor_A_' + str(i)
                        with open(name+'.csv', 'a', newline='') as file:
                            writer.writerow(["Word", "Occurrences", "Percentage"])
                            writer.writerows([key, d[key], percent] for key in list(d.keys()))

Body:
Wrt your inner loop which writes the CSV files:

# Create individual file names
for i in data:
    name = 'Glassdoor_A_' + str(i)

    # Save output in CSV file
    with open(name+'.csv', 'w', newline='') as file:
        ...

⬆ is executed for each iteration of the outer loop for index, row in filtered_dates.iterrows():. So each iteration while overwrite the previously created files. Try using mode as 'a' (append) and write the headers with empty data outside of these two loops.

Without getting into the details of what you're calculating and writing out, the way to make it append data to the outfiles would be:

Create the files with just the headers at the start of the script.

The last inner loop should write to the files in append mode.

So, at the start of your script, add:

data = json.load(file)
# Create individual empty files with headers
for i in data:
    name = 'Glassdoor_A_' + str(i)
    with open(name+'.csv', 'w', newline='') as file:
        writer = csv.writer(file)  # you probably don't need to use the csv module for the first part
        writer.writerow(["Text Main Words", "Text Main Occurrences"])
        # nothing else here for now

Then at the end of your script, for the inner most loop where you're writing out the data, do:

while end_date <= last_end_date:
    ...
    for index, row in filtered_dates.iterrows():
        ...
        for i in data:
            name = 'Glassdoor_A_' + str(i)
            with open(name+'.csv', 'a', newline='') as file:  # note the 'append' mode
                writer = csv.writer(file)
                writer.writerows([occurrence])

Btw, that last line writer.writerows([occurrence]) should probably be writer.writerows(list(occurrence)) if occurrence is not already a list of tuples or a list of lists with two elements in each inner list.


问:
How to create touch events using Angular 2+ version?
How to create angular touch events, because angular does not have in built touch events like (click) etc ?</p>

答:
You can create event listeners or assign functions to window object's events in components OnInit. An example that closes dropdown when clicking outside of dropdown.

template

```<code><div class="dropdown">
  <button (click)="optionsDropdownActive = !optionsDropdownActive" class = "dropdown-button">
    dropdown
  </button>
  <div *ngIf="optionsDropdownActive" class = "dropdown-list">
      <a href="#" class="dropdown-item">Item 1</a>
      <a href="#" class="dropdown-item">Item 2</a>
  </div>
</div>
</code>```

component

```<code>optionsDropdownActive = false;

ngOnInit () {
    window.onclick = (e) => {
      if(!e.target.matches('.dropdown *') ) {
        this.optionsDropdownActive = false;
      }
    }

    window.ontouchstart =(e) => {
      if(!e.target.matches('.dropdown *')) {
        this.optionsDropdownActive = false
      }
    }
 }
</code>```

Body:
You can create event listeners or assign functions to window object's events in components OnInit. An example that closes dropdown when clicking outside of dropdown.

template

<div class="dropdown">
  <button (click)="optionsDropdownActive = !optionsDropdownActive" class = "dropdown-button">
    dropdown
  </button>
  <div *ngIf="optionsDropdownActive" class = "dropdown-list">
      <a href="#" class="dropdown-item">Item 1</a>
      <a href="#" class="dropdown-item">Item 2</a>
  </div>
</div>

component

optionsDropdownActive = false;

ngOnInit () {
    window.onclick = (e) => {
      if(!e.target.matches('.dropdown *') ) {
        this.optionsDropdownActive = false;
      }
    }

    window.ontouchstart =(e) => {
      if(!e.target.matches('.dropdown *')) {
        this.optionsDropdownActive = false
      }
    }
 }


问:
in react useEffect life cycle, i am getting infinite result
In react hook life cycle, When i login with another account, state doesn't updates. if I remove dependency array , the errors blows up of memory exceeded of updates

const [admin, setAdmin] = useState({});

useEffect(() => {
    const jwt = localStorage.getItem("token");
    if (jwt) {
      const user = jwtDecode(jwt);
      setAdmin(user);
    }
}, [admin])```

I just want that if the user logged in with another account, the state should update immediately.

答:
That's because, you're setting the state in useEffects and hence triggering it again and again...

Whenever, state changes, useEffects get triggered if the same state has been passed as a dependency in it. That's exactly what you've done.

To fix this, Move setAdmin(user); in another method or remove [admin] from the dependency.

Body:
In react hook life cycle, When i login with another account, state doesn't updates. if I remove dependency array , the errors blows up of memory exceeded of updates

const [admin, setAdmin] = useState({});

useEffect(() => {
    const jwt = localStorage.getItem("token");
    if (jwt) {
      const user = jwtDecode(jwt);
      setAdmin(user);
    }
}, [admin])

I just want that if the user logged in with another account, the state should update immediately.


问:
Joining Models in Python DRF Serializer without introducing Foreign key
So I am relatively new to Django, and DRF. I recently started a project to learn more about the platform.

I also found best practice guide line which I am following at the moment. Here is the Django Style Guide

The guild line says that every App should completely decouple itself and use UUID instead of foreign key,
And every business rule should go into services.py (Which I like btw.)

Here comes the problem. I am not sure how I can construct two models together to produce a nested JSON Output.

Ex: I have Post() model and Comments() model. and Comment model uses uuid of Post model as a referential id.

Now in my API.py, I am not sure how I can join these two together in the Serializer.py

FYI the code below is only for demo purposes, may not be executable

Model

```<code>class Post(models.Model):
    user_id = models.UUIDField(default=uuid.uuid4)
    title = models.CharField(max_length=100)
    description = models.CharField(max_length=100)
    pictures = models.CharField(max_length=100)
    lat = models.CharField(max_length=16)
    long = models.CharField(max_length=16)
    vote = models.CharField(max_length=100)
    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now_add=True)

class Comment(models.Model):
    post_id =  models.UUIDField(default=uuid.uuid4)
    parent_id = models.ForeignKey("self", on_delete=models.CASCADE)
    text = models.CharField(max_length=1000)
    up_vote = models.IntegerField()
    down_vote = models.IntegerField()
    user_id = models.UUIDField(default=uuid.uuid4)
    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now_add=True)
</code>```

Service

```<code>def get_report(id) -> Dict:
    logger.info('Get an Report by Id')

    post= Post.objects.get(id=id)

    return {
        'post'= post
    }

def get_comments(id) -> Dict:
    logger.info('Get an Report by Id')

    comments = Comment.objects.filter(post_id=id)

    return {
        'comments' = comments
    }
</code>```

API

```<code>class ReportGetApi(APIView):
     class OutputSerializer(serializers.ModelSerializer):
        comments = CommentsSerializer(many=True, read_only=True)
        class Meta:
            model = Post
            fields = ('id', 'title', 'description', 'pictures', 'lat', 'long', 'vote', 'comments')

    class CommentsSerializer(serializers.ModelSerializer):
        class Meta:
            model = Comments
            fields = ('post_id', 'parent_id', 'text', 'up_vote', 'down_vote', 'user_id', 'created_at', 'modified_at')

    def get(self, request):
        post = PostService.get_post() #Only one item
        comments = PostService.get_comments() #Many Items

        serializer = self.OutputSerializer(post, many=True)

        return Response(serializer.data)
</code>```

答:
You actually don't need a services file to do what you're asking. DRF can handle what you want directly with serializers and using a RetrieveAPIView.

So using your models you have above you could have something like the following:

serializers.py

from rest_framework import serializers

from . import models

class CommentSerializer(serializers.ModelSerializer):

    id = serializers.IntegerField(read_only=True)

    class Meta:
        model = models.Comment
        fields = '__all__'

class PostSerializer(serializers.ModelSerializer):

    id = serializers.IntegerField(read_only=True)
    comments = serializers.SerializerMethodField()

    class Meta:
        model = models.Post
        fields = '__all__'

    def get_comments(self, obj):
        comments = models.Comment.objects.filter(post_id=obj.id)
        return CommentSerializer(comments, many=True).data

```

<p><strong>views.py</strong></p>

<pre class="lang-py prettyprint-override"><code>from rest_framework import generics
from . import serializers, models

class ReportApi(generics.RetrieveAPIView):
    serializer_class = serializers.PostSerializer
    queryset = models.Post.objects.all()
</code>```

You would need to specify the URL to pass in the primary key of the Post object you want to retrieve like so:

urls.py

from django.urls import path

from api import views

app_name = 'api'
urlpatterns = [
    path('get_post_report/<pk>/', views.ReportApi.as_view()),
]
```

<p>Then you would access the view using something like <code>http://example.com/api/get_post_report/12345678/</code>.</p>

```Note: You must configure the urls.py within your project's
urls file to use 'api/' for including your app's urls for the
'/api/' part of the url above to be a part of the url.
```

<p>If you don't know how to set up urls refer to the Django Tutorial </p>

<p>This will then give you something like the following:</p>

<p><strong>response.json</strong></p>

```{
    "id": 1,
    "comments": [
        {
            "id": 1,
            "post_id": "00000000-0000-0000-0000-000000000001",
            "text": "Comment Text",
            "up_vote": 0,
            "down_vote": 0,
            "user_id": "00000000-0000-0000-0000-000000000001",
            "created_at": "2020-05-29T13:14:07.103072Z",
            "modified_at": "2020-05-29T13:14:07.103124Z",
            "parent_id": null
        }
    ],
    "user_id": "00000000-0000-0000-0000-000000000001",
    "title": "My Post",
    "description": "Post Description",
    "pictures": "No Pictures",
    "lat": "12",
    "long": "12",
    "vote": "12",
    "created_at": "2020-05-29T13:14:07.102316Z",
    "modified_at": "2020-05-29T13:14:07.102356Z"
}
```

<h1>Lastly</h1>

<hr>

<p>I looked at the guide you are referring to and did not see a reference to decouple models with UUID's. While you <em>can</em> do that (and in some cases may be necessary) I would think hard on whether you truly need that much decoupling. </p>

<p>There are reasons to use foreign keys over UUID's such as accessing the related models easier and faster. Decoupling using UUID's means you will need to write more boilerplate code every time you need to access a related model.</p>

<p>It comes down to deciding whether you need decoupling or a better developer experience with (subjectively) cleaner code. Please don't just follow a guide and assume it's law. More experience will help with this.</p>

<p>For example, if you used a foreign key relationship your <code>PostSerializer</code> could look like the following:</p>

<p><strong>example_serializers.py</strong></p>

<pre class="lang-py prettyprint-override"><code>class PostSerializer(serializers.ModelSerializer):

    id = serializers.IntegerField(read_only=True)
    comments = CommentSerializer(many=True)

    class Meta:
        model = models.Post
        fields = '__all__'
</code>```

See how we got rid of the get_comments(self, obj) method? That was just one bit of boilerplate that we got rid of by making the design decision to use foreign key relationships. Now just imagine a codebase of millions of lines of code and many serializers. Remember, the more code you write the more testing/debugging you need to do as well.

Again, just my opinion, but be sure you actually need to decouple your models before you do it.

Also, I strongly recommend you follow the DRF tutorial. It reviews everything you need to accomplish what I just posted here.

Hope this helps!

Body:
So I am relatively new to Django, and DRF. I recently started a project to learn more about the platform.

I also found best practice guide line which I am following at the moment. Here is the Django Style Guide

The guild line says that every App should completely decouple itself and use UUID instead of foreign key,
And every business rule should go into services.py (Which I like btw.)

Here comes the problem. I am not sure how I can construct two models together to produce a nested JSON Output.

Ex: I have Post() model and Comments() model. and Comment model uses uuid of Post model as a referential id.

Now in my API.py, I am not sure how I can join these two together in the Serializer.py

FYI the code below is only for demo purposes, may not be executable

Model

class Post(models.Model):
    user_id = models.UUIDField(default=uuid.uuid4)
    title = models.CharField(max_length=100)
    description = models.CharField(max_length=100)
    pictures = models.CharField(max_length=100)
    lat = models.CharField(max_length=16)
    long = models.CharField(max_length=16)
    vote = models.CharField(max_length=100)
    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now_add=True)

class Comment(models.Model):
    post_id =  models.UUIDField(default=uuid.uuid4)
    parent_id = models.ForeignKey("self", on_delete=models.CASCADE)
    text = models.CharField(max_length=1000)
    up_vote = models.IntegerField()
    down_vote = models.IntegerField()
    user_id = models.UUIDField(default=uuid.uuid4)
    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now_add=True)

Service

def get_report(id) -> Dict:
    logger.info('Get an Report by Id')

    post= Post.objects.get(id=id)

    return {
        'post'= post
    }

def get_comments(id) -> Dict:
    logger.info('Get an Report by Id')

    comments = Comment.objects.filter(post_id=id)

    return {
        'comments' = comments
    }

API

class ReportGetApi(APIView):
     class OutputSerializer(serializers.ModelSerializer):
        comments = CommentsSerializer(many=True, read_only=True)
        class Meta:
            model = Post
            fields = ('id', 'title', 'description', 'pictures', 'lat', 'long', 'vote', 'comments')

    class CommentsSerializer(serializers.ModelSerializer):
        class Meta:
            model = Comments
            fields = ('post_id', 'parent_id', 'text', 'up_vote', 'down_vote', 'user_id', 'created_at', 'modified_at')

    def get(self, request):
        post = PostService.get_post() #Only one item
        comments = PostService.get_comments() #Many Items

        serializer = self.OutputSerializer(post, many=True)

        return Response(serializer.data)

Body:
You actually don't need a services file to do what you're asking. DRF can handle what you want directly with serializers and using a RetrieveAPIView.

So using your models you have above you could have something like the following:

serializers.py

from rest_framework import serializers

from . import models

class CommentSerializer(serializers.ModelSerializer):

    id = serializers.IntegerField(read_only=True)

    class Meta:
        model = models.Comment
        fields = '__all__'

class PostSerializer(serializers.ModelSerializer):

    id = serializers.IntegerField(read_only=True)
    comments = serializers.SerializerMethodField()

    class Meta:
        model = models.Post
        fields = '__all__'

    def get_comments(self, obj):
        comments = models.Comment.objects.filter(post_id=obj.id)
        return CommentSerializer(comments, many=True).data

views.py

from rest_framework import generics
from . import serializers, models

class ReportApi(generics.RetrieveAPIView):
    serializer_class = serializers.PostSerializer
    queryset = models.Post.objects.all()

You would need to specify the URL to pass in the primary key of the Post object you want to retrieve like so:

urls.py

from django.urls import path

from api import views

app_name = 'api'
urlpatterns = [
    path('get_post_report/<pk>/', views.ReportApi.as_view()),
]

Then you would access the view using something like http://example.com/api/get_post_report/12345678/.

Note: You must configure the urls.py within your project's
urls file to use 'api/' for including your app's urls for the
'/api/' part of the url above to be a part of the url.

If you don't know how to set up urls refer to the Django Tutorial

This will then give you something like the following:

response.json

{
    "id": 1,
    "comments": [
        {
            "id": 1,
            "post_id": "00000000-0000-0000-0000-000000000001",
            "text": "Comment Text",
            "up_vote": 0,
            "down_vote": 0,
            "user_id": "00000000-0000-0000-0000-000000000001",
            "created_at": "2020-05-29T13:14:07.103072Z",
            "modified_at": "2020-05-29T13:14:07.103124Z",
            "parent_id": null
        }
    ],
    "user_id": "00000000-0000-0000-0000-000000000001",
    "title": "My Post",
    "description": "Post Description",
    "pictures": "No Pictures",
    "lat": "12",
    "long": "12",
    "vote": "12",
    "created_at": "2020-05-29T13:14:07.102316Z",
    "modified_at": "2020-05-29T13:14:07.102356Z"
}

Lastly

I looked at the guide you are referring to and did not see a reference to decouple models with UUID's. While you can do that (and in some cases may be necessary) I would think hard on whether you truly need that much decoupling.

There are reasons to use foreign keys over UUID's such as accessing the related models easier and faster. Decoupling using UUID's means you will need to write more boilerplate code every time you need to access a related model.

It comes down to deciding whether you need decoupling or a better developer experience with (subjectively) cleaner code. Please don't just follow a guide and assume it's law. More experience will help with this.

For example, if you used a foreign key relationship your PostSerializer could look like the following:

example_serializers.py

class PostSerializer(serializers.ModelSerializer):

    id = serializers.IntegerField(read_only=True)
    comments = CommentSerializer(many=True)

    class Meta:
        model = models.Post
        fields = '__all__'

See how we got rid of the get_comments(self, obj) method? That was just one bit of boilerplate that we got rid of by making the design decision to use foreign key relationships. Now just imagine a codebase of millions of lines of code and many serializers. Remember, the more code you write the more testing/debugging you need to do as well.

Again, just my opinion, but be sure you actually need to decouple your models before you do it.

Also, I strongly recommend you follow the DRF tutorial. It reviews everything you need to accomplish what I just posted here.

Hope this helps!


问:
How to make 32-bit applications in Python in a 64-bit PC
I use pyinstaller or cx_Freeze whenever I want my Python file to convert it into a .exe package, but the problem is, my PC is 64-bit, and if I make that application, it only runs on a 64-bit PC, that's why I want to know, is there a way to develop 32-bit applications on a 64-bit PC using any module or anything? Please I really need an answer!</p>

答:
After installing both a 32 bit and 64 bit version of Python try running the following command to create the required exe distributable.

```<code>python -m pyinstaller {args}
</code>```

Or it can be

```<code>python3.5 -m pyinstaller {args}
</code>```

Body:
After installing both a 32 bit and 64 bit version of Python try running the following command to create the required exe distributable.

python -m pyinstaller {args}

Or it can be

python3.5 -m pyinstaller {args}


问:
What is wrong with my jquery code with respect to promise
I am quite new to jQuery, and I am having a difficult time querying an api with
jQuery.

There appears to be no syntax error but code is not firing - all the variables and functions have been defined

```<code>$.get(githubsearch).success(function(r){
    displayResults(r.items);
})
.fail(function(err){
    console.log("failed to query Github");
})
.done(function(){
});
</code>```

答:
The anser is simple, your code is not correct use this.

```<code>var data = {
    name: "Test"
}
var url = "https://www.api.site.com/v1/getuser" //example site
//you can remove data if not required
//request can be get or post
$.post(url, data, function (response) {
//    success data
    console.log(response)
}).fail(function (response) {
//    failed data
    console.log(response)
});
</code>```

Please format your code before posting.

Body:
I am quite new to jQuery, and I am having a difficult time querying an api with
jQuery.

There appears to be no syntax error but code is not firing - all the variables and functions have been defined

$.get(githubsearch).success(function(r){
    displayResults(r.items);
})
.fail(function(err){
    console.log("failed to query Github");
})
.done(function(){
});

Body:
The anser is simple, your code is not correct use this.

var data = {
    name: "Test"
}
var url = "https://www.api.site.com/v1/getuser" //example site
//you can remove data if not required
//request can be get or post
$.post(url, data, function (response) {
//    success data
    console.log(response)
}).fail(function (response) {
//    failed data
    console.log(response)
});

Please format your code before posting.


问:
Manipulating entries of matrices in R
I have a matrix, say 10x10, and I want to make each row entry to be the sum of all entries in that particular row, e.g. all entries in row1 takes the value of the sum of row1, all entries in row2 takes the value of the sum of row two and so on.</p>

Title: Manipulating entries of matrices in R

Body:
Take a 3x3 matrix for example:

x <- matrix(1:9, 3, 3, T)
x

#      [,1] [,2] [,3]
# [1,]    1    2    3
# [2,]    4    5    6
# [3,]    7    8    9

x[] <- rowSums(x)
x

#      [,1] [,2] [,3]
# [1,]    6    6    6
# [2,]   15   15   15
# [3,]   24   24   24


问:
File not found when loading from assets?
I included several pre-made .png files in my assets folder, but only some of them are getting through without error:

```<code>AssetManager assetManager = context.getAssets();
Inputstream in = assetManager.open(assetName);
</code>```

where assetName is a String containing something like "myPic.png".

It seems to work for some of the files, but for others it throws java.io.FileNotFoundException: myPic.png even though I see it right there in the Assets folder alongside plenty of other files that seem to be making the cut.

答:
If you are running into this during an Android Instrumentation Test, the issue can be fixed by changing this:

```<code>ApplicationProvider.getApplicationContext().getAssets().open(YOUR_FILE)
</code>```

to this:

```<code>InputStream inputStream = InstrumentationRegistry.getInstrumentation().
     getContext().getAssets().open(YOUR_FILE);
</code>```

The application provider knows to redirect resource requests to your instrumentation resources and then fallback to the application under test, but it does not have the same intelligence for assets

ContentLicense: CC BY-SA 3.0

Body:
I included several pre-made .png files in my assets folder, but only some of them are getting through without error:

AssetManager assetManager = context.getAssets();
Inputstream in = assetManager.open(assetName);

where assetName is a String containing something like "myPic.png".

It seems to work for some of the files, but for others it throws java.io.FileNotFoundException: myPic.png even though I see it right there in the Assets folder alongside plenty of other files that seem to be making the cut.

Body:
If you are running into this during an Android Instrumentation Test, the issue can be fixed by changing this:

ApplicationProvider.getApplicationContext().getAssets().open(YOUR_FILE)

to this:

InputStream inputStream = InstrumentationRegistry.getInstrumentation().
     getContext().getAssets().open(YOUR_FILE);

The application provider knows to redirect resource requests to your instrumentation resources and then fallback to the application under test, but it does not have the same intelligence for assets


答:
There is no success function in $.get

You can also use $.ajax. Find difference here

I am writing both ways whatever you like.

```<code>$.ajax({
        url: githubsearch,
        type: 'get',
        success: function (data) {
             displayResults(data);
        },
        error: function(err){
          console.error(err);
        }
}).done(function() {
      console.log("finished");
});
</code>```

2nd Example

```<code>$.get( githubsearch, function(data) {
   displayResults(data);
})
.done(function() {
    console.log("finished");
})
.fail(function() {
     console.error(err);
})
</code>```

Title: What is wrong with my jquery code with respect to promise

Body:
There is no success function in $.get

You can also use $.ajax. Find difference here

I am writing both ways whatever you like.

$.ajax({
        url: githubsearch,
        type: 'get',
        success: function (data) {
             displayResults(data);
        },
        error: function(err){
          console.error(err);
        }
}).done(function() {
      console.log("finished");
});

2nd Example

$.get( githubsearch, function(data) {
   displayResults(data);
})
.done(function() {
    console.log("finished");
})
.fail(function() {
     console.error(err);
})


问:
Why returns Int? python
in this video(at 7min30seconds), the code bellow I copied from this video returns 3, although
mine returns 4.04.
I do not understand why codes in the video returns Int, though mine returns Float.

https://www.youtube.com/watch?v=HWW-jA6YjHk&list=UUNc-Wa_ZNBAGzFkYbAHw9eg&index=29

```<code>def num_coins(cents):
    if cents < 1:
        return 0
    coins = [25, 10, 5, 1]
    num_of_coins = 0
    for coin in coins:
        num_of_coins += cents / coin
        cents = cents % coin
        if cents == 0:
            break
    return num_of_coins

print(num_coins(31))
</code>```

答:
Use this to get the right answer :

```<code>def num_coins(cents):
    if cents < 1:
        return 0
    coins = [25, 10, 5, 1]
    num_of_coins = 0
    for coin in coins:
        num_of_coins += int(cents / coin)
        cents = cents % coin
        if cents == 0:
            break
    return num_of_coins

print(num_coins(31))
</code>```

/ operator is not similar for python 2 and python 3

Title: Why returns Int? python

Body:
in this video(at 7min30seconds), the code bellow I copied from this video returns 3, although
mine returns 4.04.
I do not understand why codes in the video returns Int, though mine returns Float.

https://www.youtube.com/watch?v=HWW-jA6YjHk&list=UUNc-Wa_ZNBAGzFkYbAHw9eg&index=29

def num_coins(cents):
    if cents < 1:
        return 0
    coins = [25, 10, 5, 1]
    num_of_coins = 0
    for coin in coins:
        num_of_coins += cents / coin
        cents = cents % coin
        if cents == 0:
            break
    return num_of_coins

print(num_coins(31))

Body:
Use this to get the right answer :

def num_coins(cents):
    if cents < 1:
        return 0
    coins = [25, 10, 5, 1]
    num_of_coins = 0
    for coin in coins:
        num_of_coins += int(cents / coin)
        cents = cents % coin
        if cents == 0:
            break
    return num_of_coins

print(num_coins(31))

/ operator is not similar for python 2 and python 3


问:
Here Maps Geocode API leads to Cross-Origin error
I use the first example here in order to get the geo coordinates based on an address:
https://developer.here.com/documentation/maps/3.1.15.1/dev_guide/topics/geocoding.html

My JavaScript coding looks almost the same as in the official documentation:

```<code>var platform = new H.service.Platform({
  'apikey': 'HERE IS MY API KEY'
});

// Get an instance of the geocoding service:
var service = platform.getSearchService();

service.geocode({
  q: 'Berlin'
}, (result) => {
  result.items.forEach((item) => {
    console.log("test");
  });
}, alert);
</code>```

However, when the geocode request is sent, I get the following error:

```<code>Access to XMLHttpRequest at '**https://geocode.search.hereapi.com/v1/geocode?xnlp=CL_JSMv3.1.16.1&apikey=[HERE IS MY API KEY]&q=Berlin**' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

The API key is sent correctly, why do I still get the CORS error?
If I enter the request URL manually in the browser, I get a response and everything is fine.

答: If you are testing this code by opening the file in the browser, you may get this error. I suggest using a local server for testing.</p>

Body:
I use the first example here in order to get the geo coordinates based on an address:
https://developer.here.com/documentation/maps/3.1.15.1/dev_guide/topics/geocoding.html

My JavaScript coding looks almost the same as in the official documentation:

var platform = new H.service.Platform({
  'apikey': 'HERE IS MY API KEY'
});

// Get an instance of the geocoding service:
var service = platform.getSearchService();

service.geocode({
  q: 'Berlin'
}, (result) => {
  result.items.forEach((item) => {
    console.log("test");
  });
}, alert);

However, when the geocode request is sent, I get the following error:

Access to XMLHttpRequest at '**https://geocode.search.hereapi.com/v1/geocode?xnlp=CL_JSMv3.1.16.1&apikey=[HERE IS MY API KEY]&q=Berlin**' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

The API key is sent correctly, why do I still get the CORS error?
If I enter the request URL manually in the browser, I get a response and everything is fine.


问:
SQLiteDatabase.openOrCreateDatabase isn't working
I've a database in my assets folder. I've tried the below code to load the database.

```<code>public SQLiteDatabase db;

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

    db = SQLiteDatabase.openOrCreateDatabase(new File("file:///android_asset/e2b.db"), null);
    Toast.makeText(getBaseContext(), "Error" + db.isOpen(), Toast.LENGTH_LONG).show();
}
</code>```

I've just tried to open it. Hasn't used it yet. But, when I run my app the window doesn't open with below popup(error)

Unfortunately, MyDBApp has stopped

The LogCat is below.

05-12 13:10:01.673 16004 16004 I   art                                          Late-enabling -Xcheck:jni
  05-12 13:10:01.877 16004 16004 W   System                                       ClassLoader referenced unknown path: /data/app/com.aashakil.e2b2edict-1/lib/arm
  05-12 13:10:02.227 16004 16004 D   AccessibilityManager                         getInstance() new sInstance = android.view.accessibility.AccessibilityManager@ec2dd0e, context = com.aashakil.e2b2edict.MainActivity@f26932f, userId = 0
  05-12 13:10:02.288 16004 16004 E   SQLiteLog                                    (14) cannot open file at line 31278 of [2ef4f3a5b1]
  05-12 13:10:02.288 16004 16004 E   SQLiteLog                                    (14) os_unix.c:31278: (2) open(//file:/android_asset/e2b.db) -
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               Failed to open database 'file:/android_asset/e2b.db'.
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:207)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:191)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:806)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:791)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:709)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:702)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at com.aashakil.e2b2edict.MainActivity.onCreate(MainActivity.java:20)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.app.Activity.performCreate(Activity.java:6251)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2370)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2477)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.app.ActivityThread.-wrap11(ActivityThread.java)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1345)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.os.Handler.dispatchMessage(Handler.java:102)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.os.Looper.loop(Looper.java:148)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.app.ActivityThread.main(ActivityThread.java:5452)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at java.lang.reflect.Method.invoke(Native Method)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:762)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
  05-12 13:10:02.331 16004 16004 D   AndroidRuntime                               Shutting down VM
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               FATAL EXCEPTION: main
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               Process: com.aashakil.e2b2edict, PID: 16004
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               java.lang.RuntimeException: Unable to start activity ComponentInfo{com.aashakil.e2b2edict/com.aashakil.e2b2edict.MainActivity}: android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2417)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2477)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.app.ActivityThread.-wrap11(ActivityThread.java)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1345)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.os.Handler.dispatchMessage(Handler.java:102)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.os.Looper.loop(Looper.java:148)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.app.ActivityThread.main(ActivityThread.java:5452)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at java.lang.reflect.Method.invoke(Native Method)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:762)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               Caused by: android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:207)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:191)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:806)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:791)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:709)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:702)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at com.aashakil.e2b2edict.MainActivity.onCreate(MainActivity.java:20)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.app.Activity.performCreate(Activity.java:6251)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2370)

答:
Instead of calling openOrCreateDatabase inside fragment, you need to call it

In Activity :

```<code>SQLiteDatabase db = openOrCreateDatabase("DATABASE",android.content.Context.MODE_PRIVATE ,null);
</code>```

The correct way in Fragment:

```<code>SQLiteDatabase db = getActivity().openOrCreateDatabase("DATABASE",android.content.Context.MODE_PRIVATE ,null);**
</code>```

Body:
I've a database in my assets folder. I've tried the below code to load the database.

public SQLiteDatabase db;

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

    db = SQLiteDatabase.openOrCreateDatabase(new File("file:///android_asset/e2b.db"), null);
    Toast.makeText(getBaseContext(), "Error" + db.isOpen(), Toast.LENGTH_LONG).show();
}

I've just tried to open it. Hasn't used it yet. But, when I run my app the window doesn't open with below popup(error)

Unfortunately, MyDBApp has stopped

The LogCat is below.

05-12 13:10:01.673 16004 16004 I   art                                          Late-enabling -Xcheck:jni
  05-12 13:10:01.877 16004 16004 W   System                                       ClassLoader referenced unknown path: /data/app/com.aashakil.e2b2edict-1/lib/arm
  05-12 13:10:02.227 16004 16004 D   AccessibilityManager                         getInstance() new sInstance = android.view.accessibility.AccessibilityManager@ec2dd0e, context = com.aashakil.e2b2edict.MainActivity@f26932f, userId = 0
  05-12 13:10:02.288 16004 16004 E   SQLiteLog                                    (14) cannot open file at line 31278 of [2ef4f3a5b1]
  05-12 13:10:02.288 16004 16004 E   SQLiteLog                                    (14) os_unix.c:31278: (2) open(//file:/android_asset/e2b.db) -
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               Failed to open database 'file:/android_asset/e2b.db'.
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:207)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:191)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:806)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:791)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:709)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:702)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at com.aashakil.e2b2edict.MainActivity.onCreate(MainActivity.java:20)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.app.Activity.performCreate(Activity.java:6251)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2370)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2477)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.app.ActivityThread.-wrap11(ActivityThread.java)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1345)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.os.Handler.dispatchMessage(Handler.java:102)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.os.Looper.loop(Looper.java:148)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at android.app.ActivityThread.main(ActivityThread.java:5452)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at java.lang.reflect.Method.invoke(Native Method)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:762)
  05-12 13:10:02.331 16004 16004 E   SQLiteDatabase                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
  05-12 13:10:02.331 16004 16004 D   AndroidRuntime                               Shutting down VM
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               FATAL EXCEPTION: main
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               Process: com.aashakil.e2b2edict, PID: 16004
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               java.lang.RuntimeException: Unable to start activity ComponentInfo{com.aashakil.e2b2edict/com.aashakil.e2b2edict.MainActivity}: android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2417)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2477)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.app.ActivityThread.-wrap11(ActivityThread.java)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1345)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.os.Handler.dispatchMessage(Handler.java:102)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.os.Looper.loop(Looper.java:148)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.app.ActivityThread.main(ActivityThread.java:5452)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at java.lang.reflect.Method.invoke(Native Method)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:762)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               Caused by: android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:207)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:191)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:806)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:791)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:709)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:702)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at com.aashakil.e2b2edict.MainActivity.onCreate(MainActivity.java:20)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.app.Activity.performCreate(Activity.java:6251)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
  05-12 13:10:02.333 16004 16004 E   AndroidRuntime                               at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2370)

Body:
Instead of calling openOrCreateDatabase inside fragment, you need to call it

In Activity :

SQLiteDatabase db = openOrCreateDatabase("DATABASE",android.content.Context.MODE_PRIVATE ,null);

The correct way in Fragment:

SQLiteDatabase db = getActivity().openOrCreateDatabase("DATABASE",android.content.Context.MODE_PRIVATE ,null);**


问:
What does registering a DLL do?
I know how to register dlls but I've never really been sure why I'm doing it or under what conditions a dll must be registered.  Could somebody explain or point me to some documentation?  </p>

答:
What is most commonly referred to as DLL registering is when it implements a COM object. regsvr32 ensures that an instance of the object can be created. When e.g. VBScript uses New or CreateObject(), the registration ensures that COM knows what DLL to load in order to make a new instance, whether by name or CLSID.

See "the layman's explanation" for a (very) brief summary.

OwnerDisplayName: stimms

ContentLicense: CC BY-SA 2.5

Title: What does registering a DLL do?

LastEditorDisplayName: gbjbaanb

OwnerDisplayName: Pontus Gagge


问:
Calculate Spark column value depending on another row value on the same column
I'm working on Apache spark 2.3.0 cloudera4 and I have an issue processing a Dataframe.

I've got this input dataframe:

```<code>+---+---+----+
| id| d1| d2 |
+---+---+----+
|  1|   | 2.0|
|  2|   |-4.0|
|  3|   | 6.0|
|  4|3.0|    |
+---+---+----+
</code>```

And I need this output:

```<code>+---+---+----+----+
| id| d1| d2 |  r |
+---+---+----+----+
|  1|   | 2.0| 7.0|
|  2|   |-4.0| 5.0|
|  3|   | 6.0| 9.0|
|  4|3.0|    | 3.0|
+---+---+.---+----+
</code>```

Which is, from an iterating perspective, get the biggest id row (4) and put the d1 value on the r column, then take the next row (3) and put r[4] + d2[3] on r column, and so on.

Is it posible to do something like that on Spark? because I will need a computed value from a row to calculate the value for another row.

答:
How about this? The important bit is sum($"r1").over(Window.orderBy($"id".desc) which calculates a cumulative sum of a column. Other than that, I'm creating a couple of helper columns to get the max id and get the ordering right.

```<code>val result = df
  .withColumn("max_id", max($"id").over(Window.rowsBetween(Window.unboundedPreceding, Window.unboundedFollowing)))
  .withColumn("r1", when($"id" === $"max_id", $"d1").otherwise($"d2"))
  .withColumn("r", sum($"r1").over(Window.orderBy($"id".desc)))
  .drop($"max_id").drop($"r1")
  .orderBy($"id")
result.show

+---+----+----+---+
| id|  d1|  d2|  r|
+---+----+----+---+
|  1|null| 2.0|7.0|
|  2|null|-4.0|5.0|
|  3|null| 6.0|9.0|
|  4| 3.0|null|3.0|
+---+----+----+---+
</code>```

Body:
I'm working on Apache spark 2.3.0 cloudera4 and I have an issue processing a Dataframe.

I've got this input dataframe:

+---+---+----+
| id| d1| d2 |
+---+---+----+
|  1|   | 2.0|
|  2|   |-4.0|
|  3|   | 6.0|
|  4|3.0|    |
+---+---+----+

And I need this output:

+---+---+----+----+
| id| d1| d2 |  r |
+---+---+----+----+
|  1|   | 2.0| 7.0|
|  2|   |-4.0| 5.0|
|  3|   | 6.0| 9.0|
|  4|3.0|    | 3.0|
+---+---+.---+----+

Which is, from an iterating perspective, get the biggest id row (4) and put the d1 value on the r column, then take the next row (3) and put r[4] + d2[3] on r column, and so on.

Is it posible to do something like that on Spark? because I will need a computed value from a row to calculate the value for another row.

Body:
How about this? The important bit is sum($"r1").over(Window.orderBy($"id".desc) which calculates a cumulative sum of a column. Other than that, I'm creating a couple of helper columns to get the max id and get the ordering right.

val result = df
  .withColumn("max_id", max($"id").over(Window.rowsBetween(Window.unboundedPreceding, Window.unboundedFollowing)))
  .withColumn("r1", when($"id" === $"max_id", $"d1").otherwise($"d2"))
  .withColumn("r", sum($"r1").over(Window.orderBy($"id".desc)))
  .drop($"max_id").drop($"r1")
  .orderBy($"id")
result.show

+---+----+----+---+
| id|  d1|  d2|  r|
+---+----+----+---+
|  1|null| 2.0|7.0|
|  2|null|-4.0|5.0|
|  3|null| 6.0|9.0|
|  4| 3.0|null|3.0|
+---+----+----+---+


问:
Get original sys.argv
Is there a way to obtain the original argv value from python after execution code like this:

```<code>sys.argv[0]=""
</code>```

In fact I search for the unwritable version of sys.argv.

I would prefer a OS independent solution, but I'm working on windows, so a windows only solution would be sufficient

答:
On Linux you could use:</p>

```<code>open("/proc/{}/cmdline".format(os.getpid())).read()[:-1].split("\x00")[1:]
</code>```

Title: Get original sys.argv

Body:
Is there a way to obtain the original argv value from python after execution code like this:

sys.argv[0]=""

In fact I search for the unwritable version of sys.argv.

I would prefer a OS independent solution, but I'm working on windows, so a windows only solution would be sufficient

Body:
On Linux you could use:

open("/proc/{}/cmdline".format(os.getpid())).read()[:-1].split("\x00")[1:]


问:
Implementation of ceil() and floor()
Just curious how are these implemented. I can't see where I would start. Do they work directly on the float's/double's bits?

Also where can I find the source code of functions from math.h? All I find are either headers with prototypes or files with functions that call other functions from somewhere else.

EDIT: Part of the message was lost after editing the title. What I meant in particular were the ceil() and floor() functions.

答: While modern CPU do have hardware implementation of common transcendantal functions like sin, cos, etc..., it is rarely used as is. It may be for portability reason, speed, accuracy, etc... Instead, approximation algorithms are used.</p>

Title: Implementation of ceil() and floor()


问:
PresentModalViewController not showing navigation bar on next view
Hello I am using One tab bar button on toolbar , this button will show next view with table view ,Here is my code

```<code>[self presentModalViewController:self.navigationController
                            animated:YES];
</code>```

my problem is that when I click this tab bar button it will showing next view with tableview but not navigation bar. because of this i am unable to perform delete operation in tableView.

How to solve the issue?

答:
Swift 5.1
Presenting ViewController with navigation bar AND toolbar in fullscreen mode. If you don't put the row marked on comment the toolbar never show itself.</p>

```<code>let sb = UIStoryboard(name: "retail_mainScreen", bundle: nil)
        guard let mainVC = sb.instantiateViewController(withIdentifier: "mainScreen") as? retail_mainGest else { return }
        let navController = UINavigationController(rootViewController: mainVC)
        navController.isToolbarHidden = false //<--- remember this or toolbar will not appear
        navController.modalPresentationStyle = .fullScreen

         sender.vista.present(navController, animated: true, completion: nil)
</code>```

Body:
Hello I am using One tab bar button on toolbar , this button will show next view with table view ,Here is my code

[self presentModalViewController:self.navigationController
                            animated:YES];

my problem is that when I click this tab bar button it will showing next view with tableview but not navigation bar. because of this i am unable to perform delete operation in tableView.

How to solve the issue?

Body:
Swift 5.1
Presenting ViewController with navigation bar AND toolbar in fullscreen mode. If you don't put the row marked on comment the toolbar never show itself.

let sb = UIStoryboard(name: "retail_mainScreen", bundle: nil)
        guard let mainVC = sb.instantiateViewController(withIdentifier: "mainScreen") as? retail_mainGest else { return }
        let navController = UINavigationController(rootViewController: mainVC)
        navController.isToolbarHidden = false //<--- remember this or toolbar will not appear
        navController.modalPresentationStyle = .fullScreen

         sender.vista.present(navController, animated: true, completion: nil)


问:
Vlookup() equivalent in Dplyr
My df looks like:

```<code>library(tidyverse)
df_1 <- tibble::tribble(
          ~sub_date, ~value_1, ~value_2,
          "2020-05",       58,      130,
          "2020-05",       58,       "check",
          "2020-03",       50,      120,
          "2020-03",       55,       "check",
          "2020-03",       55,       "check"
          )
</code>```

I want to change the values of the rows containing "check" with the reference values here:

```<code>df_ref <- tibble::tribble(
            ~sub_date, ~ref_value,
            "2020-05",        123,
            "2020-03",        234
            )
</code>```

Basically - using the df_ref table as a reference only for the rows containing check.

I want to use the equivalent of a lookup() in excel, used in a if() function.

Final result being:

```<code>df_final <- tibble::tribble(
              ~sub_date, ~value_1, ~value_2,
              "2020-05",       58,      130,
              "2020-05",       58,      123,
              "2020-03",       50,      120,
              "2020-03",       55,      234,
              "2020-03",       55,      234
              )
</code>```

答:
This code should work

```<code>df_1 %>%
  mutate(value_2 = as.numeric(na_if(value_2, "check"))) %>%
  left_join(df_ref, by = "sub_date") %>%
  mutate(value_2 = coalesce(value_2, ref_value)) %>%
  select(-ref_value)
</code>```

Small explanation: first we set to NA all the "check" values thanks to na_if, then we join with the lookup table, then we coalesce the two columns value_2 and ref_value, i.e. take the first non-missing value between the two.

Output

```<code># A tibble: 5 x 3
#   sub_date value_1 value_2
#   <chr>      <dbl>   <dbl>
# 1 2020-05       58     130
# 2 2020-05       58     123
# 3 2020-03       50     120
# 4 2020-03       55     234
# 5 2020-03       55     234
</code>```

Small note: your df_1 doesn't work as you pasted it in your question. Below I adjusted its values as character so that it works

```<code>df_1 <- tibble::tribble(
  ~sub_date, ~value_1, ~value_2,
  "2020-05",       58,      "130",
  "2020-05",       58,      "check",
  "2020-03",       50,      "120",
  "2020-03",       55,      "check",
  "2020-03",       55,      "check"
)
</code>```

Title: Vlookup() equivalent in Dplyr

Body:
My df looks like:

library(tidyverse)
df_1 <- tibble::tribble(
          ~sub_date, ~value_1, ~value_2,
          "2020-05",       58,      130,
          "2020-05",       58,       "check",
          "2020-03",       50,      120,
          "2020-03",       55,       "check",
          "2020-03",       55,       "check"
          )

I want to change the values of the rows containing "check" with the reference values here:

df_ref <- tibble::tribble(
            ~sub_date, ~ref_value,
            "2020-05",        123,
            "2020-03",        234
            )

Basically - using the df_ref table as a reference only for the rows containing check.

I want to use the equivalent of a lookup() in excel, used in a if() function.

Final result being:

df_final <- tibble::tribble(
              ~sub_date, ~value_1, ~value_2,
              "2020-05",       58,      130,
              "2020-05",       58,      123,
              "2020-03",       50,      120,
              "2020-03",       55,      234,
              "2020-03",       55,      234
              )

Body:
This code should work

df_1 %>%
  mutate(value_2 = as.numeric(na_if(value_2, "check"))) %>%
  left_join(df_ref, by = "sub_date") %>%
  mutate(value_2 = coalesce(value_2, ref_value)) %>%
  select(-ref_value)

Small explanation: first we set to NA all the "check" values thanks to na_if, then we join with the lookup table, then we coalesce the two columns value_2 and ref_value, i.e. take the first non-missing value between the two.

Output

# A tibble: 5 x 3
#   sub_date value_1 value_2
#   <chr>      <dbl>   <dbl>
# 1 2020-05       58     130
# 2 2020-05       58     123
# 3 2020-03       50     120
# 4 2020-03       55     234
# 5 2020-03       55     234

Small note: your df_1 doesn't work as you pasted it in your question. Below I adjusted its values as character so that it works

df_1 <- tibble::tribble(
  ~sub_date, ~value_1, ~value_2,
  "2020-05",       58,      "130",
  "2020-05",       58,      "check",
  "2020-03",       50,      "120",
  "2020-03",       55,      "check",
  "2020-03",       55,      "check"
)


问:
Using "$RANDOM" to generate a random string in Bash
I am trying to use the Bash variable $RANDOM to create a random string that consists of 8 characters from a variable that contains integer and alphanumeric digits, e.g., var="abcd1234ABCD".

How can I do that?

答:
For those looking for a random alpha-numeric string in bash:

LC_ALL=C tr -dc A-Za-z0-9 </dev/urandom | head -c 64

The same as a well-documented function:

function rand-str {
    # Return random alpha-numeric string of given LENGTH
    #
    # Usage: VALUE=$(rand-str $LENGTH)
    #    or: VALUE=$(rand-str)

    local DEFAULT_LENGTH=64
    local LENGTH=${1:-$DEFAULT_LENGTH}

    LC_ALL=C tr -dc A-Za-z0-9 </dev/urandom | head -c $LENGTH
    # LC_ALL=C: required for Mac OS X - https://unix.stackexchange.com/a/363194/403075
    # -dc: delete complementary set == delete all except given set
}
```


问:
Accessing an ActionScript function via Javascript
I'm trying to call a function in an action script using the ExternalInterface.addCallback API, but I can't seem to get it to work.  Here's what I have:

ActionScript:

```<code>//MyClass.as
package {

    import flash.display.Sprite;
    import flash.external.ExternalInterface;

    public class MyClass extends Sprite
    {
        public function MyClass()
        {
            ExternalInterface.addCallback('getStringJS', getStringAS);
        }

        public function getStringAS():String
        {
            return "Hello World!";
        }
    }
}
</code>```

NOTE: I'm compiling this into an swf using the flex mxmlc compiler if that matters.

HTML/Javascript:

```<code><!doctype html>
<html>
    <head>
        <title>User Identification</title>
    <head>
    <body>
        <object id="MyClass" name="MyClass" type="application/x-shockwave-flash" data="MyClass.swf" width="1" height="1">
            <param name="movie" value="MyClass.swf">
            <embed src="MyClass.swf" width="1" height="1">
        </object>
        <script type="text/javascript">
            var flash = document.getElementById("MyClass");
            var str = flash.getStringJS();
            alert(str);
        </script>
    </body>
</html>
</code>```

The error I'm getting is:

```<code>Uncaught TypeError: Object #<HTMLObjectElement> has no method 'getStringJS'
</code>```

I also tried adding in a timeout in case the swf file wasn't loading, but I didn't have any success with that method either.

Any thoughts?

Cheers,

Mike

答:
I think the issue is a matter of the flash not being loaded. I tried your code using the window.onload event and it worked for me:

The flash is the same...

HTML/JS :

```<code><!doctype html>
<html>
    <head>
        <title>User Identification</title>
    <head>
    <body>

        <object id="MyClass" name="MyClass" type="application/x-shockwave-flash" data="MyClass.swf" width="1" height="1">
            <param name="movie" value="MyClass.swf">
            <embed src="MyClass.swf" width="1" height="1">
        </object>

        <script>

            window.onload = function() {

                var flash = document.getElementById("MyClass");
                var test = flash.getStringJS("test");
                alert(test);   //pops up with "Hello World!" on Firefox

            };

        </script>
    </body>
</html>
</code>```

Does that help?

Body:
I'm trying to call a function in an action script using the ExternalInterface.addCallback API, but I can't seem to get it to work.  Here's what I have:

ActionScript:

//MyClass.as
package {

    import flash.display.Sprite;
    import flash.external.ExternalInterface;

    public class MyClass extends Sprite
    {
        public function MyClass()
        {
            ExternalInterface.addCallback('getStringJS', getStringAS);
        }

        public function getStringAS():String
        {
            return "Hello World!";
        }
    }
}

NOTE: I'm compiling this into an swf using the flex mxmlc compiler if that matters.

HTML/Javascript:

<!doctype html>

        <title>User Identification</title>

        <object id="MyClass" name="MyClass" type="application/x-shockwave-flash" data="MyClass.swf" width="1" height="1">
            <param name="movie" value="MyClass.swf">
            <embed src="MyClass.swf" width="1" height="1">
        </object>

The error I'm getting is:

Uncaught TypeError: Object #<HTMLObjectElement> has no method 'getStringJS'

I also tried adding in a timeout in case the swf file wasn't loading, but I didn't have any success with that method either.

Any thoughts?

Cheers,

Mike

Body:
I think the issue is a matter of the flash not being loaded. I tried your code using the window.onload event and it worked for me:

The flash is the same...

HTML/JS :

<!doctype html>
<html>
    <head>
        <title>User Identification</title>
    <head>
    <body>

        <object id="MyClass" name="MyClass" type="application/x-shockwave-flash" data="MyClass.swf" width="1" height="1">
            <param name="movie" value="MyClass.swf">
            <embed src="MyClass.swf" width="1" height="1">
        </object>

        <script>

            window.onload = function() {

                var flash = document.getElementById("MyClass");
                var test = flash.getStringJS("test");
                alert(test);   //pops up with "Hello World!" on Firefox

            };

        </script>
    </body>
</html>

Does that help?


问:
Using variables inside for loops
I'm trying to compare sizes of files inside two directories.
My problem is that when I store the sizes of the files inside of a "for" loop, my variable takes all the sizes at once instead of taking them one by one.

Here is the part of my code that is problematic :

```<code>for dir1Files in dir1/*
do
    sizeFile1=`stat -c%s $dir1Files`
    for dir2Files in dir2/*
    do
        sizeFile2=`stat -c%s $dir2Files`
        diffSize=$((sizeFile1-sizeFile2))
        echo "$diffSize"
    done
done
</code>```

I realised, thanks to set -x, that my variables sizeFile1 and sizeFile2 are not integers. Instead, they are a few lines long and contain the sizes of my files in directories, with "one line = one integer", if that makes sense.
For example, with three files in dir1, my variable sizeFile1 is :

```<code>12500
14534
23000
</code>```

What I would like is for my variable to vary from 12500 to 14534 to 23000. How should I do that ? I'm guessing I need to change my "for" into something else ?

Thanks in advance.

答:
Nothing in this is broken 100% of the time, but it certainly can be broken if run with unusual filenames present. To make this code more robust:

Use quotes whenever you expand a variable. This prevents a file named dir1/ * (with the space in its name) from being replaced with a list of all files in the current directory when generating a stat command line.

Use shopt -s nullglob to make the loops not run at all when no glob matches exist, instead of running with the glob expression as a filename itself.

```<code>shopt -s nullglob  # prevent dir1/* from ever evaluating to itself
for dir1File in dir1/*; do
    sizeFile1=$(stat -c%s "$dir1File")
    for dir2File in dir2/*; do
        sizeFile2=$(stat -c%s "$dir2File")
        diffSize=$((sizeFile1-sizeFile2))
        echo "$diffSize"
    done
done
</code>```

Title: Using variables inside for loops

Body:
I'm trying to compare sizes of files inside two directories.
My problem is that when I store the sizes of the files inside of a "for" loop, my variable takes all the sizes at once instead of taking them one by one.

Here is the part of my code that is problematic :

for dir1Files in dir1/*
do
    sizeFile1=`stat -c%s $dir1Files`
    for dir2Files in dir2/*
    do
        sizeFile2=`stat -c%s $dir2Files`
        diffSize=$((sizeFile1-sizeFile2))
        echo "$diffSize"
    done
done

I realised, thanks to set -x, that my variables sizeFile1 and sizeFile2 are not integers. Instead, they are a few lines long and contain the sizes of my files in directories, with "one line = one integer", if that makes sense.
For example, with three files in dir1, my variable sizeFile1 is :

12500
14534
23000

What I would like is for my variable to vary from 12500 to 14534 to 23000. How should I do that ? I'm guessing I need to change my "for" into something else ?

Thanks in advance.

Body:
Nothing in this is broken 100% of the time, but it certainly can be broken if run with unusual filenames present. To make this code more robust:

Use quotes whenever you expand a variable. This prevents a file named dir1/ * (with the space in its name) from being replaced with a list of all files in the current directory when generating a stat command line.

Use shopt -s nullglob to make the loops not run at all when no glob matches exist, instead of running with the glob expression as a filename itself.

shopt -s nullglob  # prevent dir1/* from ever evaluating to itself
for dir1File in dir1/*; do
    sizeFile1=$(stat -c%s "$dir1File")
    for dir2File in dir2/*; do
        sizeFile2=$(stat -c%s "$dir2File")
        diffSize=$((sizeFile1-sizeFile2))
        echo "$diffSize"
    done
done


问:
jasper report detect if datail band or subreport is present in current page
I'm developing a report with jasper.

The main report has several subreports.

Only one of these subreport has a fixed text with a note number, something like this.

```<code>my text<sup>(2)</sup>
</code>```

In main report I must print the footnote, but only in all the pages in which the text with the note is present.

An image to better explain:

Is there something that permit to detect if a subreport is present in the current page?

Or something that permit to detect if a detail band is present in the current page?

Or something that permit to detect if a particular text will be printed in current page?

Or other strategy to handle this particular situation?

答:
. Create Variable in main report 'subReportCount'
  Type = Integer, default 0
  Reset Type = 'Page'

. Place this variable (hidden) somewhere after Subreport

. Create variable 'SubVar' in subreport , expression == $V{REPORT_COUNT}

. In main, go to subreport properties -> Edit return Values - >
  Set From Varible= SubVar , To Variable=subReportCount,  Calculation type = Sum

. Page Footer Print When Expression =  $V{subReportCount} > 0

This may work if you are trying if subreport is printed atleast once in page.

Body:
I'm developing a report with jasper.

The main report has several subreports.

Only one of these subreport has a fixed text with a note number, something like this.

my text(2)

In main report I must print the footnote, but only in all the pages in which the text with the note is present.

An image to better explain:

Is there something that permit to detect if a subreport is present in the current page?

Or something that permit to detect if a detail band is present in the current page?

Or something that permit to detect if a particular text will be printed in current page?

Or other strategy to handle this particular situation?


问:
Google App Engine firewall and internal access and error 403
We have 2 app engine app (flex and standard) running on separate projects and we want project A to request project B with https to xxx.appspot.com URL.

Our firewall on both projects Denies all IPs(*) and whitelisted App Engine internal addresss (10.1.0.41, 0.1.0.40, 10.0.0.1 and 0.1.0.30) as explained in the doc.

Yet we receive a "403 error forbidden access" (which disappears when disabling the firewall).

This post is similar to mine but the responses didn't help me.

Is there anything else I can do ?
Did anyone got this to work ?

Thank you in advance.

答:
As you may already know, GCP Projects represent a trust boundary within an organization. Hence, inter-project communication between App Engine services would require Public IP communication or using Shared VPC, which allows connecting between networks from different projects. There should be no internal communication between App Engine Services over different projects. Hence, whitelisting App Engine internal IP addresses might not be useful in this situation.

About using Public App Engine IP addresses, as illustrated in this document. App Engine hosts services on a dynamic public IP address of a Google load balancer. Due to that, the IP address can be changed any time and any Static IP can not be provided.  For outbound services, a large pool of IP addresses are used which you can obtain as outlined in this document


问:
Why does importing as modules and writing creates a different result?
```
def matrixdets(a):
    x=(a[0][0] * a[1][1] * a[2][2]) + \
      (a[0][1] * a[1][2] * a[2][0]) + \
      (a[0][2] * a[1][0] * a[2][1])
    print(x)
```

I wrote this code to find a certain value of a matrix. It returns a number when I type the function in python. However, when i import this as a module, it just returns the matrix i orginally entered. Why does that happen?

答:
As Graeme said, it doesn't return anything. When you import it, the function gets compiled at the time of importation.

Does your module define a and then run matrixdets on it? It will do that even when you import the function from a module, since importing a module executes all the code inside it.

You need to be clearer about what precisely you're doing and what your output is.

Body:
def matrixdets(a):
    x=(a[0][0] * a[1][1] * a[2][2]) + \
      (a[0][1] * a[1][2] * a[2][0]) + \
      (a[0][2] * a[1][0] * a[2][1])
    print(x)

I wrote this code to find a certain value of a matrix. It returns a number when I type the function in python. However, when i import this as a module, it just returns the matrix i orginally entered. Why does that happen?


问:
How to speed up MySQL query involving a "like" condition on a varchar column?
I have a table with a varchar column that contains stock market tickers. The values can have the stock exchange prepended to the actual ticker, but some don't. For example:

```<code>NYSE:MSFT
NYSE:AAPL
AMT:STZ
^SPX
JMAT
</code>```

These are all valid tickers. Now, when someone searches for a ticker, then the query looks something like:

```<code>select * from stocks where ticker like '%'.$string.'%'
</code>```

The table, in production, will have over 100k entries. I want to get ahead of that potential problem by indexing on the column, but it appears based on MySQL docs that it is not possible, not for a query like this anyway.

The docs state that a varchar index is possible, but in a like query it won't work if there's a wildcard before the search string. And I do need a wildcard before the search string.

Is there another option to speeding up this query?

答:
Like you said, there is no possibility to use index in combination with using '%wildcard%'.
There is possibility to use feature called: Full Text Searching (FTS), that can improve your searching performence in comparison with using LIKE operator.

Some example performance analysis is here

There is a lot of discussions about FTS, you can read on StackOverflow ofcourse.

Body:
I have a table with a varchar column that contains stock market tickers. The values can have the stock exchange prepended to the actual ticker, but some don't. For example:

NYSE:MSFT
NYSE:AAPL
AMT:STZ
^SPX
JMAT

These are all valid tickers. Now, when someone searches for a ticker, then the query looks something like:

select * from stocks where ticker like '%'.$string.'%'

The table, in production, will have over 100k entries. I want to get ahead of that potential problem by indexing on the column, but it appears based on MySQL docs that it is not possible, not for a query like this anyway.

The docs state that a varchar index is possible, but in a like query it won't work if there's a wildcard before the search string. And I do need a wildcard before the search string.

Is there another option to speeding up this query?


问:
Error from chokidar (C:\): Error: EBUSY: resource busy or locked, lstat 'C:\DumpStack.log.tmp
Using Angular and during ng serve, I'm getting the error:</p>

```<code>Error from chokidar (C:\): Error: EBUSY: resource busy or locked, lstat 'C:\DumpStack.log.tmp'
Error from chokidar (C:\): Error: EBUSY: resource busy or locked, lstat 'C:\hiberfil.sys'
Error from chokidar (C:\): Error: EBUSY: resource busy or locked, lstat 'C:\pagefile.sys'
Error from chokidar (C:\): Error: EBUSY: resource busy or locked, lstat 'C:\swapfile.sys'
</code>```

答:
If you are using polyfills, this error will occur if you activated the following polyfill (from src/polyfills.ts):</p>

```<code>/** IE10 and IE11 requires the following for NgClass support on SVG elements */
import 'classlist.js';  // Run `npm install --save classlist.js`.
</code>```

<p>...and did not run the corresponding npm install: </p>

```<code>npm install --save classlist.js
</code>```

Body:
Using Angular and during ng serve, I'm getting the error:

Error from chokidar (C:\): Error: EBUSY: resource busy or locked, lstat 'C:\DumpStack.log.tmp'
Error from chokidar (C:\): Error: EBUSY: resource busy or locked, lstat 'C:\hiberfil.sys'
Error from chokidar (C:\): Error: EBUSY: resource busy or locked, lstat 'C:\pagefile.sys'
Error from chokidar (C:\): Error: EBUSY: resource busy or locked, lstat 'C:\swapfile.sys'

Body:
If you are using polyfills, this error will occur if you activated the following polyfill (from src/polyfills.ts):

/** IE10 and IE11 requires the following for NgClass support on SVG elements */
import 'classlist.js';  // Run `npm install --save classlist.js`.

...and did not run the corresponding npm install:

npm install --save classlist.js


问:
Is there any processor in NiFi which helps me add a unique identifier to each record?
My processor is querying a DB2 table and loads data to S3 and then ingest it into Snowflake.
I have unique account numbers in my table and I need to add a column with unique identifier for each unique account number. </p>

答:
Maybe this will help you:

${UUID()} returns random value, similar to de305d54-75b4-431b-adb2-eb6b9e546013

Pass this has attribute and then in content?