问:
Javascript split function for getting name from a whole link?
I have several link like this:

```<code>https://www.globenewswire.com/news-release/2022/02/05/2379566/673/en/ROSEN-GLOBAL-INVESTOR-COUNSEL-Encourages-Reata-Pharmaceuticals-Inc-Investors-With-Losses-Over-100K-to-Secure-Counsel-Before-Important-February-18-Deadline-in-Securities-Class-Actio.html
</code>```

Or, it can be:

```<code>https://finance.yahoo.com/m/597b7dc4-eecf-3b45-83ac-fa87ba542bbf/bitcoin-is-back-over-%2441%2C000.html

https://www.dailyfx.com/forex/fundamental/forecast/weekly/title/2022/02/06/Mexican-Peso-Outlook-US-Inflation-Data-Banxico-Decision-will-Be-Key-for-USDMXN.html
</code>```

Anything. But I need the domain name. How can I get that.

Here from this two links, I need:

Finace Yahoo

Globe News Wire

Daily Fx

How can I find that using JavaScript.

答:
One approach:

// Object mapping a known domain name to that domain's (already-known) name:
const linkMap = {
  'www.globenewswire.com': 'Globe News Wire',
  'finance.yahoo.com': 'Yahoo Finance',
  'www.dailyfx.com': 'Daily FX'
};

// selecting the first <button> element, and binding the anonymous
// function as the event-handler for the 'click' event:
document.querySelector('button').addEventListener('click', (e) => {
  // selecing all  elements that are found within
 elements,
  // iterating over them with nodeList.prototype.forEach():
  document.querySelectorAll('li a').forEach(
    // setting the text-content of the  element to be equal to
    // the value of the hostname as retrieved from the  element:
    (anchor) => anchor.textContent = linkMap[anchor.hostname]
  );
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>*,
 ::before,
 ::after {
  box-sizing: border-box;
  font: normal 1rem / 1.5 sans-serif;
  margin: 0;
  padding: 0;
}

ul {
  background-color: yellow;
  display: flex;
  gap: 1em;
  justify-content: end;
  list-style-type: none;
  margin-block: 1em;
  margin-inline: auto;
  width: clamp(15em, 600px, 80vw);
}

li:first-child {
  margin-right: auto;
}</code>```

<button>Identify Links</button>

Link 1

Link 2

Link 3

```
</div>
</div>
</p>
<p>A slightly revised approach, which takes into account that you may not have a map of domains to names:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const linkMap = {
  'www.globenewswire.com': 'Globe News Wire',
  'finance.yahoo.com': 'Yahoo Finance',
  'www.dailyfx.com': 'Daily FX'
};

document.querySelector('button').addEventListener('click', () => {
  document.querySelectorAll('li a').forEach(
    (anchor) => {
      //  here we cache the result from the linkMap:
      let siteName = linkMap[anchor.hostname];
      // here using a conditional operator (ternary) to test if there is a falsy result
      // from the Object, if there is we return the hostname after replacing the 'www' (if it exists)
      // and then take the substring from the first (0) character to the last '.' character; this
      // is a simple approach because it assumes the last '.' precedes the TLD but does not
      // account for sites such as '.co.uk' as an example.
      anchor.textContent = !siteName ? anchor.hostname.replace('www.', '').substring(0, anchor.hostname.lastIndexOf(".")) : siteName
    });
});</code>```

*,
 ::before,
 ::after {
  box-sizing: border-box;
  font: normal 1rem / 1.5 sans-serif;
  margin: 0;
  padding: 0;
}

ul {
  display: flex;
  gap: 1em;
  justify-content: end;
  list-style-type: none;
  margin-block: 1em;
  margin-inline: auto;
  width: clamp(15em, 600px, 80vw);
}

li:first-child {
  margin-right: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li><button>Identify Links</button></li>
  <li>Link 1</li>

  <li>Link 2</li>

  <li>Link 3</li>
  <li>Link 4</li>
</ul></code>```

Body:
I have several link like this:

https://www.globenewswire.com/news-release/2022/02/05/2379566/673/en/ROSEN-GLOBAL-INVESTOR-COUNSEL-Encourages-Reata-Pharmaceuticals-Inc-Investors-With-Losses-Over-100K-to-Secure-Counsel-Before-Important-February-18-Deadline-in-Securities-Class-Actio.html

Or, it can be:

https://finance.yahoo.com/m/597b7dc4-eecf-3b45-83ac-fa87ba542bbf/bitcoin-is-back-over-%2441%2C000.html

https://www.dailyfx.com/forex/fundamental/forecast/weekly/title/2022/02/06/Mexican-Peso-Outlook-US-Inflation-Data-Banxico-Decision-will-Be-Key-for-USDMXN.html

Anything. But I need the domain name. How can I get that.

Here from this two links, I need:

Finace Yahoo

Globe News Wire

Daily Fx

How can I find that using JavaScript.

Body:
One approach:

// Object mapping a known domain name to that domain's (already-known) name:
const linkMap = {
  'www.globenewswire.com': 'Globe News Wire',
  'finance.yahoo.com': 'Yahoo Finance',
  'www.dailyfx.com': 'Daily FX'
};

// selecting the first <button> element, and binding the anonymous
// function as the event-handler for the 'click' event:
document.querySelector('button').addEventListener('click', (e) => {
  // selecing all <a> elements that are found within <li> elements,
  // iterating over them with nodeList.prototype.forEach():
  document.querySelectorAll('li a').forEach(
    // setting the text-content of the <a> element to be equal to
    // the value of the hostname as retrieved from the <a> element:
    (anchor) => anchor.textContent = linkMap[anchor.hostname]
  );
});

*,
 ::before,
 ::after {
  box-sizing: border-box;
  font: normal 1rem / 1.5 sans-serif;
  margin: 0;
  padding: 0;
}

ul {
  background-color: yellow;
  display: flex;
  gap: 1em;
  justify-content: end;
  list-style-type: none;
  margin-block: 1em;
  margin-inline: auto;
  width: clamp(15em, 600px, 80vw);
}

li:first-child {
  margin-right: auto;
}

<ul>
  <li><button>Identify Links</button></li>
  <li><a href="https://www.globenewswire.com/news-release/2022/02/05/2379566/673/en/ROSEN-GLOBAL-INVESTOR-COUNSEL-Encourages-Reata-Pharmaceuticals-Inc-Investors-With-Losses-Over-100K-to-Secure-Counsel-Before-Important-February-18-Deadline-in-Securities-Class-Actio.html">Link 1</a></li>

  <li><a href="https://finance.yahoo.com/m/597b7dc4-eecf-3b45-83ac-fa87ba542bbf/bitcoin-is-back-over-%2441%2C000.html">Link 2</a></li>

  <li><a href="https://www.dailyfx.com/forex/fundamental/forecast/weekly/title/2022/02/06/Mexican-Peso-Outlook-US-Inflation-Data-Banxico-Decision-will-Be-Key-for-USDMXN.html">Link 3</a></li>
</ul>

A slightly revised approach, which takes into account that you may not have a map of domains to names:

const linkMap = {
  'www.globenewswire.com': 'Globe News Wire',
  'finance.yahoo.com': 'Yahoo Finance',
  'www.dailyfx.com': 'Daily FX'
};

document.querySelector('button').addEventListener('click', () => {
  document.querySelectorAll('li a').forEach(
    (anchor) => {
      //  here we cache the result from the linkMap:
      let siteName = linkMap[anchor.hostname];
      // here using a conditional operator (ternary) to test if there is a falsy result
      // from the Object, if there is we return the hostname after replacing the 'www' (if it exists)
      // and then take the substring from the first (0) character to the last '.' character; this
      // is a simple approach because it assumes the last '.' precedes the TLD but does not
      // account for sites such as '.co.uk' as an example.
      anchor.textContent = !siteName ? anchor.hostname.replace('www.', '').substring(0, anchor.hostname.lastIndexOf(".")) : siteName
    });
});

*,
 ::before,
 ::after {
  box-sizing: border-box;
  font: normal 1rem / 1.5 sans-serif;
  margin: 0;
  padding: 0;
}

ul {
  display: flex;
  gap: 1em;
  justify-content: end;
  list-style-type: none;
  margin-block: 1em;
  margin-inline: auto;
  width: clamp(15em, 600px, 80vw);
}

li:first-child {
  margin-right: auto;
}

<ul>
  <li><button>Identify Links</button></li>
  <li><a href="https://www.globenewswire.com/news-release/2022/02/05/2379566/673/en/ROSEN-GLOBAL-INVESTOR-COUNSEL-Encourages-Reata-Pharmaceuticals-Inc-Investors-With-Losses-Over-100K-to-Secure-Counsel-Before-Important-February-18-Deadline-in-Securities-Class-Actio.html">Link 1</a></li>

  <li><a href="https://finance.yahoo.com/m/597b7dc4-eecf-3b45-83ac-fa87ba542bbf/bitcoin-is-back-over-%2441%2C000.html">Link 2</a></li>

  <li><a href="https://www.dailyfx.com/forex/fundamental/forecast/weekly/title/2022/02/06/Mexican-Peso-Outlook-US-Inflation-Data-Banxico-Decision-will-Be-Key-for-USDMXN.html">Link 3</a></li>
  <li><a href="https://stackoverflow.com">Link 4</a></li>
</ul>


来源: stackexchange

问:
Remove/ truncate leading zeros by javascript/jquery
Suggest solution for removing or truncating leading zeros from number(any string) by javascript,jquery.</p>

答:
Use "Math.abs"

eg: Math.abs(003) = 3;

console.log(Math.abs(003))```

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Django rest framework: how to make a view to delete multiple objects?
I am building a simple Photos-Albums app with Django Rest Framework (DRF). I would like to be able to delete multiple albums at once by supplying an array of ids. I am using viewsets.ModelViewSet for the basic views.

```<code>class AlbumViewSet(viewsets.ModelViewSet):
    queryset = Album.objects.all()
    serializer_class = AlbumSerializer
</code>```

I have managed to create a view to show the albums before the delete operation by adding this function to my views.py file.

```<code>@api_view(['GET', 'DELETE'])
def delete_albums(request):
    """
        GET:    list all albums
        DELETE: delete multiple albums
    """

    if request.method == 'GET':
        albums = Album.objects.all()
        serializer = AlbumSerializer(albums, many=True)
        return Response(serializer.data)

    elif request.method == 'DELETE':
        ids = request.data
        albums = Album.objects.filter(id__in=ids)
        for album in albums:
            album.delete()
        serializer = AlbumSerializer(albums, many=True)
        return Response(serializer.data)
</code>```

If I run curl -X delete -H "Content-Type: application/json" http://localhost:8000/albums/delete -d '{"data":[1,2,3]}'  then it will delete albums with ids 1,2,3.

This is OK, except that:

It's not class-based, and I'd prefer to have everything class-based if possible

I would prefer to have a form in the view that lets me input an array e.g. [1,2,3], hit a delete button, and then see the results of the query in the browser, much like when one posts a new object through the interface.

Can anyone please outline how to achieve that? Thanks!

答:
You can use the action decorator

```<code>from rest_framework.decorators import action
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.request import Request

#import your model and serializer classes

class AlbumViewSet(viewsets.ModelViewSet):
    queryset = Album.objects.all()
    serializer_class = AlbumSerializer

    @action(methods=["DELETE"], details =False, )
    def delete(self, request:Request):
        delete_id =request.data
        delete_albums = self.queryset.filter(id__in=delete_id)

        delete_albums.delete()
        return Response( self.serializer_class(delete_albums,many=True).data)
</code>```

assuming your modelViewSet api point was /api/albums
you could now make a delete request to /api/albums/delete

You could check out the full document on viewsets at ViewSet
and on how to use action decorator provided by the django rest framework

Body:
I am building a simple Photos-Albums app with Django Rest Framework (DRF). I would like to be able to delete multiple albums at once by supplying an array of ids. I am using viewsets.ModelViewSet for the basic views.

class AlbumViewSet(viewsets.ModelViewSet):
    queryset = Album.objects.all()
    serializer_class = AlbumSerializer

I have managed to create a view to show the albums before the delete operation by adding this function to my views.py file.

@api_view(['GET', 'DELETE'])
def delete_albums(request):
    """
        GET:    list all albums
        DELETE: delete multiple albums
    """

    if request.method == 'GET':
        albums = Album.objects.all()
        serializer = AlbumSerializer(albums, many=True)
        return Response(serializer.data)

    elif request.method == 'DELETE':
        ids = request.data
        albums = Album.objects.filter(id__in=ids)
        for album in albums:
            album.delete()
        serializer = AlbumSerializer(albums, many=True)
        return Response(serializer.data)

If I run curl -X delete -H "Content-Type: application/json" http://localhost:8000/albums/delete -d '{"data":[1,2,3]}'  then it will delete albums with ids 1,2,3.

This is OK, except that:

It's not class-based, and I'd prefer to have everything class-based if possible

I would prefer to have a form in the view that lets me input an array e.g. [1,2,3], hit a delete button, and then see the results of the query in the browser, much like when one posts a new object through the interface.

Can anyone please outline how to achieve that? Thanks!

Body:
You can use the action decorator

from rest_framework.decorators import action
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.request import Request

#import your model and serializer classes

class AlbumViewSet(viewsets.ModelViewSet):
    queryset = Album.objects.all()
    serializer_class = AlbumSerializer

    @action(methods=["DELETE"], details =False, )
    def delete(self, request:Request):
        delete_id =request.data
        delete_albums = self.queryset.filter(id__in=delete_id)

        delete_albums.delete()
        return Response( self.serializer_class(delete_albums,many=True).data)

assuming your modelViewSet api point was /api/albums
you could now make a delete request to /api/albums/delete

You could check out the full document on viewsets at ViewSet
and on how to use action decorator provided by the django rest framework


问:
Android: SpannableString with correctly formated numbers
I would like to have a list of instructions that are correctly numbered in an enumeration. For that I use the SpannableString and I have the following code:

```<code>//Get string array from a sqLite Database
String [] instructions = MainActivity.sqLiteDataba.getPreparationInstructions(item);

//Create Spannable String Builder
int numberOfCurrentInstruction = 1;
SpannableStringBuilder builderInstructions =  new SpannableStringBuilder();
for (int i =0; i<instructions.length;i++) {
    if(instructions[i] == null ) {
        continue;
    }

    builderInstructions.append(numberOfCurrentInstruction + ". " + instructions[i] + "\n");
    numberOfCurrentInstruction++;
}
</code>```

The output in a textview (called in a Fragment) does not look like the desired way, as you can see in the screenshot:

I would like the numbers to serve as "bullet points" meaning that if there is a linebreak in the textView, the following text should not start under the number but with a little bit of space. Any idea how I can do that?

Update: I tried the suggested approach posted below (Darkman) with the layout inflator but unfortunately only the very first item is being displayed. Here is the code from inside a Fragment:

```<code>    String [] instructions = MainActivity.sqLiteDB.getPreparationInstructions(item);

    int numberOfCurrentInstruction = 1;
    ViewGroup main = getView().findViewById(R.id.main);
    LayoutInflater inflator = getLayoutInflater();

    for (int i =0; i<instructions.length;i++) {
        if(instructions[i] == null ) {
            continue;

        }

        ViewGroup mainLayout = (ViewGroup) inflator.inflate(R.layout.custom, main, true);
        ViewGroup customLayout = (ViewGroup) mainLayout.getChildAt(i);

        TextView num = (TextView) customLayout.getChildAt(0);
        TextView text = (TextView) customLayout.getChildAt(1);
        num.setText((numberOfCurrentInstruction) + ".");
        text.setText(instructions[i]);
        numberOfCurrentInstruction++;
    }
</code>```

Here is the custom.xml file

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

    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:gravity="right"
        android:layout_marginTop="@dimen/_2sdp"
        android:layout_marginLeft="@dimen/_5sdp"
        android:textSize="@dimen/_7ssp"/>

    <TextView
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:gravity="left"
        android:layout_marginTop="@dimen/_2sdp"
        android:layout_marginLeft="@dimen/_2sdp"
        android:layout_marginRight="@dimen/_5sdp"
        android:textSize="@dimen/_7ssp"/>
</LinearLayout>
</code>```

And the main.xml is inside a xml file for a fragment and looks like this:

```<code>    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:id="@+id/main">

    </LinearLayout>
</code>```

The array instructions has 5 elements in it and none of them is null and the for loop is executed 5 times (I checked this by using LogTag). However, only the first instruction is displayed and the others not. Any idea what the problem might be?

答:
If you use fixed-space font add several spaces after \n.
If you use monospace font adding spaces isn`t best way. In this case you can add symbols "1", "2" etc instead of spaces and set color for this symbols like background color.</p>

Body:
I would like to have a list of instructions that are correctly numbered in an enumeration. For that I use the SpannableString and I have the following code:

//Get string array from a sqLite Database
String [] instructions = MainActivity.sqLiteDataba.getPreparationInstructions(item);

//Create Spannable String Builder
int numberOfCurrentInstruction = 1;
SpannableStringBuilder builderInstructions =  new SpannableStringBuilder();
for (int i =0; i<instructions.length;i++) {
    if(instructions[i] == null ) {
        continue;
    }

    builderInstructions.append(numberOfCurrentInstruction + ". " + instructions[i] + "\n");
    numberOfCurrentInstruction++;
}

The output in a textview (called in a Fragment) does not look like the desired way, as you can see in the screenshot:

I would like the numbers to serve as "bullet points" meaning that if there is a linebreak in the textView, the following text should not start under the number but with a little bit of space. Any idea how I can do that?

Update: I tried the suggested approach posted below (Darkman) with the layout inflator but unfortunately only the very first item is being displayed. Here is the code from inside a Fragment:

    String [] instructions = MainActivity.sqLiteDB.getPreparationInstructions(item);

    int numberOfCurrentInstruction = 1;
    ViewGroup main = getView().findViewById(R.id.main);
    LayoutInflater inflator = getLayoutInflater();

    for (int i =0; i<instructions.length;i++) {
        if(instructions[i] == null ) {
            continue;

        }

        ViewGroup mainLayout = (ViewGroup) inflator.inflate(R.layout.custom, main, true);
        ViewGroup customLayout = (ViewGroup) mainLayout.getChildAt(i);

        TextView num = (TextView) customLayout.getChildAt(0);
        TextView text = (TextView) customLayout.getChildAt(1);
        num.setText((numberOfCurrentInstruction) + ".");
        text.setText(instructions[i]);
        numberOfCurrentInstruction++;
    }

Here is the custom.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:gravity="right"
        android:layout_marginTop="@dimen/_2sdp"
        android:layout_marginLeft="@dimen/_5sdp"
        android:textSize="@dimen/_7ssp"/>

    <TextView
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:gravity="left"
        android:layout_marginTop="@dimen/_2sdp"
        android:layout_marginLeft="@dimen/_2sdp"
        android:layout_marginRight="@dimen/_5sdp"
        android:textSize="@dimen/_7ssp"/>
</LinearLayout>

And the main.xml is inside a xml file for a fragment and looks like this:

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:id="@+id/main">

    </LinearLayout>

The array instructions has 5 elements in it and none of them is null and the for loop is executed 5 times (I checked this by using LogTag). However, only the first instruction is displayed and the others not. Any idea what the problem might be?


问:
my code for linked list is printing address in python
```<code>class Node:

    def __init__(self, data = None, next = None):
        self.data = data
        self.next = next

class link:

    def __init__(self):
        self.head = None

    def insert_begining(self, data):
       node = Node(data, self.head)
       self.head = node

    def print(self):

        itr = self.head
        space = ''

        while itr:
            space += str(itr.next) + '-->'
            itr = itr.next
        print(space)

if __name__ == '__main__':
    root = link()

    root.insert_begining(5)

    root.insert_begining(10)

    root.print()
#output of my code = <__main__.Node object at 0x00000209175AB9A0>-->None-->
</code>```

答:
Your Node class need a __str__ method to tell how to print it

```<code>class Node:
    def __str__(self):
        return str(self.data)
</code>```

Then in Link, you may use itr and not itr.next in the result construction, and I suggest a list to join instead of concatenation to avoid an arrow pointing to nothing at the end

```<code>def print(self):
    itr = self.head
    result = []
    while itr:
        result.append(str(itr))
        itr = itr.next
    print(' --> '.join(result))
</code>```

```<code>root = link()
root.insert_begining(5)
root.insert_begining(10)
root.insert_begining(15)
root.print()  # 15 --> 10 --> 5
</code>```

Body:
Your Node class need a __str__ method to tell how to print it

class Node:
    def __str__(self):
        return str(self.data)

Then in Link, you may use itr and not itr.next in the result construction, and I suggest a list to join instead of concatenation to avoid an arrow pointing to nothing at the end

def print(self):
    itr = self.head
    result = []
    while itr:
        result.append(str(itr))
        itr = itr.next
    print(' --> '.join(result))

root = link()
root.insert_begining(5)
root.insert_begining(10)
root.insert_begining(15)
root.print()  # 15 --> 10 --> 5


问:
Serializing a class with dynamic attribute to and from JSON
I have a class with 2 fields as ENUM and 3rd field as dynamic. The third field may contain Enum, Object, list or a string.

This dynamic field is throwing error when json.encode is executed.

This is my class:

```<code>    class Msg {
  /// Constructor
  Msg({
    required this.type,
    required this.signal,
    **required this.content,**
  });

  /// Create the model from Json.
  Msg.fromJson(Map<String, dynamic> json) {
    type = Type.values[json['Type'] as int];
    signal = Signal.values[json['Signal'] as int];
    **content = json['SyncContent'] as dynamic;**
  }

  Type? type;

  Signal? signal;

  /// Actual message it may be string or object or objectList
  **dynamic syncContent;**

  /// Create a Json object of the message.
  Map<String, dynamic> toJson() {
    final data = <String, dynamic>{};

    data['Type'] = type!.name;
    data['Signal'] = signal!.name;
    **data['Content'] = content!;**

    return data;
  }

  @override
  String toString() {
    return '{"Type": ${type!.index} , "Signal": ${signal!.index}, "content": $content}';
  }
}
</code>```

Msg.toString() returns the following JSON string

```<code>JSON {"Type": 0 , "Signal": 3, "Content": content.start }
</code>```

when I call

```<code>json.decode(messageJson) as Map<String, dynamic>;
</code>```

It throws error for converting Content back to dynamic. Following is the error:

```<code>Unhandled exception:
FormatException: Unexpected character (at character 50)
{"Type": 0 , "Signal": 3, "Content": Content.start}
                                     ^

#0      _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1405:5)
Reload already in progress, ignoring request
</code>```

Is there any way to convert a class containing dynamic field to JSON and back from JSON to class.

答: json in dart only accept String, boolean, num means int or double, List, Map and null. in you json content.start is not one of them. you cant decode it.

Body:
I have a class with 2 fields as ENUM and 3rd field as dynamic. The third field may contain Enum, Object, list or a string.

This dynamic field is throwing error when json.encode is executed.

This is my class:

    class Msg {
  /// Constructor
  Msg({
    required this.type,
    required this.signal,
    **required this.content,**
  });

  /// Create the model from Json.
  Msg.fromJson(Map<String, dynamic> json) {
    type = Type.values[json['Type'] as int];
    signal = Signal.values[json['Signal'] as int];
    **content = json['SyncContent'] as dynamic;**
  }

  Type? type;

  Signal? signal;

  /// Actual message it may be string or object or objectList
  **dynamic syncContent;**

  /// Create a Json object of the message.
  Map<String, dynamic> toJson() {
    final data = <String, dynamic>{};

    data['Type'] = type!.name;
    data['Signal'] = signal!.name;
    **data['Content'] = content!;**

    return data;
  }

  @override
  String toString() {
    return '{"Type": ${type!.index} , "Signal": ${signal!.index}, "content": $content}';
  }
}

Msg.toString() returns the following JSON string

JSON {"Type": 0 , "Signal": 3, "Content": content.start }

when I call

json.decode(messageJson) as Map<String, dynamic>;

It throws error for converting Content back to dynamic. Following is the error:

Unhandled exception:
FormatException: Unexpected character (at character 50)
{"Type": 0 , "Signal": 3, "Content": Content.start}
                                     ^

#0      _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1405:5)
Reload already in progress, ignoring request

Is there any way to convert a class containing dynamic field to JSON and back from JSON to class.


问:
Handle .net exceptions at application level
I was reading a couple of articles a while back which I think described a behaviour where you can, in a .net application (specifically VB.net), allow an exception to occur, and then handle it in some kind of application-level exception handler, as opposed to within a Try/Catch block.
My google-fu is weak at the moment, so I'm not having much luck guessing what this feature is called in order to find information about it.

If this rings a bell for any of you, can you point me in the right direction on what exactly the feature is called so that I can search for it?

Sample code is always welcome, of course, but this is mostly just a case of me forgetting the name of the feature and being unable to search for it.

答:
For web applications you can handle it in the Global.asax.cs in the Application_Error method.  Here's our code:</p>

```<code>protected void Application_Error(object sender, EventArgs e)
    {
        Exception ex = HttpContext.Current.Server.GetLastError();

        if (ex is HttpUnhandledException && ex.InnerException != null)
            ex = ex.InnerException;

        SendErrorMail(ex);  //Or log in database or whatever you want to do with it
    }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
For web applications you can handle it in the Global.asax.cs in the Application_Error method.  Here's our code:

protected void Application_Error(object sender, EventArgs e)
    {
        Exception ex = HttpContext.Current.Server.GetLastError();

        if (ex is HttpUnhandledException && ex.InnerException != null)
            ex = ex.InnerException;

        SendErrorMail(ex);  //Or log in database or whatever you want to do with it
    }

OwnerDisplayName: Nick DeVore


问:
Null terminating int arrays
If I want to dynamically create an int array in C++ and then delete it later, do I need to null terminate the int array? If so, how do I do it? If not, how does the computer know how much memory to free?

```<code>int *array = new int[x];
..do some stuff..
delete array;
</code>```

I know for a char array it deletes up to a null character ('\0') and if you don't have a terminating null character in your string you'll probably get memory violation errors but how does this apply to arrays of ints (and other arrays, like arrays of structs)?

答:
I know for a char array it deletes up to a null character ('\0') and if you don't have a terminating null character in your string you'll probably get memory violation errors but how does this apply to arrays of ints (and other arrays, like arrays of structs)?

That's probably because the C++ internals happens to crash at the '\0' character.

For arrays, use:

```<code>delete [] array;
</code>```

C++ handles the size of the array and how much to delete.

Title: Null terminating int arrays

Body:
If I want to dynamically create an int array in C++ and then delete it later, do I need to null terminate the int array? If so, how do I do it? If not, how does the computer know how much memory to free?

int *array = new int[x];
..do some stuff..
delete array;

I know for a char array it deletes up to a null character ('\0') and if you don't have a terminating null character in your string you'll probably get memory violation errors but how does this apply to arrays of ints (and other arrays, like arrays of structs)?

Body:
I know for a char array it deletes up to a null character ('\0') and if you don't have a terminating null character in your string you'll probably get memory violation errors but how does this apply to arrays of ints (and other arrays, like arrays of structs)?

That's probably because the C++ internals happens to crash at the '\0' character.

For arrays, use:

delete [] array;

C++ handles the size of the array and how much to delete.


问:
Activity indicator in SwiftUI
Trying to add a full screen activity indicator in SwiftUI.

I can use .overlay(overlay: ) function in View Protocol.

With this, I can make any view overlay, but I can't find the iOS default style UIActivityIndicatorView equivalent in SwiftUI.

How can I make a default style spinner with SwiftUI?

NOTE: This is not about adding activity indicator in UIKit framework.

答:
I have modified Matteo Pacini's Answer for macOS using AppKit and SwiftUI. This allows you to use NSProgressIndicator in SwiftUI while retaining capability for macOS 10.15.

```<code>import AppKit
import SwiftUI

struct ActivityIndicator: NSViewRepresentable {

    @Binding var isAnimating: Bool
    let style: NSProgressIndicator.Style

    func makeNSView(context: NSViewRepresentableContext<ActivityIndicator>) -> NSProgressIndicator {
        let progressIndicator = NSProgressIndicator()
        progressIndicator.style = self.style
        return progressIndicator
    }

    func updateNSView(_ nsView: NSProgressIndicator, context: NSViewRepresentableContext<ActivityIndicator>) {
        isAnimating ? nsView.startAnimation(nil) : nsView.stopAnimation(nil)
    }

}
</code>```

Usage is as follows:

```<code>ActivityIndicator(isAnimating: .constant(true), style: .spinning)
</code>```

Title: Activity indicator in SwiftUI

Body:
I have modified Matteo Pacini's Answer for macOS using AppKit and SwiftUI. This allows you to use NSProgressIndicator in SwiftUI while retaining capability for macOS 10.15.

import AppKit
import SwiftUI

struct ActivityIndicator: NSViewRepresentable {

    @Binding var isAnimating: Bool
    let style: NSProgressIndicator.Style

    func makeNSView(context: NSViewRepresentableContext<ActivityIndicator>) -> NSProgressIndicator {
        let progressIndicator = NSProgressIndicator()
        progressIndicator.style = self.style
        return progressIndicator
    }

    func updateNSView(_ nsView: NSProgressIndicator, context: NSViewRepresentableContext<ActivityIndicator>) {
        isAnimating ? nsView.startAnimation(nil) : nsView.stopAnimation(nil)
    }

}

Usage is as follows:

ActivityIndicator(isAnimating: .constant(true), style: .spinning)


问:
Retriveing url from within <content:encoded> using BeautifulSoup
I'm struggling to retrieve a link to an image from inside an rss feed. I'm basically trying to get the url from 'src=' but all of the methods I've tried don't seem to be able to draw it out.

<content:encoded>
Using sklearn’s GridSearchCV on random forest model

Image by Annie Spratt via Unsplash

Finding the optimal tuning parameters for a machine learning problem can often be very difficult. We may encounter overfitting, which means our machine learning model trains too specifically on our training dataset and causes higher levels of error when applied to our test/holdout datasets. Or, we may run into underfitting, which means our model doesn’t train specifically enough to our training dataset. </content:encoded>

Below is the code I've been trying so far.

```<code>from bs4 import BeautifulSoup
import requests

resp = requests.get("https://towardsdatascience.com/feed")
soup = BeautifulSoup(resp.content, features='xml')
items = soup.findAll('item')
content_item = {}
content_item['title'] = items[0].title.text
content_item['link'] = items[0].link.text
content_item['Twitter'] = '@TDataScience'
content_item['Media'] = items[0].encoded['src']
</code>```

As ever, any help you can offer would be very gratefully received.

Thanks in advance.

答:
The first problem is that some items do not have <content:encoded> tag that is why it return NoneType object error when trying to access its contents. Even if all of them had that tag, still you wouldn't be able to get urls since it is xml encoded (as its name indicates). Therefore, you need to decode it using html.unescape() (or any other decoder that fits your needs) before applying further operations:

```<code>import requests
import html
from bs4 import BeautifulSoup

resp = requests.get("https://towardsdatascience.com/feed")
soup = BeautifulSoup(resp.content, features='xml')
items = soup.findAll('item')

content_item = {}
for each_item in items[:5]: # using first 5 elements just to test
    content_item['title'] = each_item.title.text
    content_item['link'] = each_item.link.text
    content_item['Twitter'] = '@TDataScience'

    if each_item.find('content:encoded'):
        # decode and form the new soup
        decoded_html = BeautifulSoup(html.unescape(each_item.encoded.text), 'lxml')

        content_item['Media'] = decoded_html.img["src"]
    else:
        content_item['Media'] = None

    print(content_item)
</code>```

The output would look like:

```<code>{'title': '3 Steps to Getting a Job in Data with Zero Experience', 'link': 'https://towardsdatascience.com/3-steps-to-getting-a-job-in-data-with-zero-experience-ccaad96d6477?source=rss----7f60cf5620c9---4', 'Twitter': '@TDataScience', 'Media': None}
{'title': 'AI for painting: Unraveling Neural Style Transfer', 'link': 'https://towardsdatascience.com/ai-for-painting-unraveling-neural-style-transfer-5ac08a20a580?source=rss----7f60cf5620c9---4', 'Twitter': '@TDataScience', 'Media': 'https://cdn-images-1.medium.com/max/1024/0*DQt1CKiJSDMrzaWA'}
{'title': 'A Novel Way to Use Batch Normalization', 'link': 'https://towardsdatascience.com/a-novel-way-to-use-batch-normalization-837176d53525?source=rss----7f60cf5620c9---4', 'Twitter': '@TDataScience', 'Media': 'https://cdn-images-1.medium.com/max/1024/0*rRQ5moh4bTSCY1zR'}
{'title': 'How to Build A Pooled OLS Regression Model For Panel Data Sets', 'link': 'https://towardsdatascience.com/how-to-build-a-pooled-ols-regression-model-for-panel-data-sets-a78358f9c2a?source=rss----7f60cf5620c9---4', 'Twitter': '@TDataScience', 'Media': 'https://cdn-images-1.medium.com/max/1024/1*nv5gPBul4YsKGctA7b4OZg.png'}
{'title': 'Understanding the native R pipe |>', 'link': 'https://towardsdatascience.com/understanding-the-native-r-pipe-98dea6d8b61b?source=rss----7f60cf5620c9---4', 'Twitter': '@TDataScience', 'Media': 'https://cdn-images-1.medium.com/max/1024/1*pnjfZFqrY1opjEVNOSjcSg.png'}
</code>```

Note that there are multiple  tags inside <content:encoded> tag, I just fetched the first one as an example.

Body:
I'm struggling to retrieve a link to an image from inside an rss feed. I'm basically trying to get the url from 'src=' but all of the methods I've tried don't seem to be able to draw it out.

<content:encoded>
Using sklearn’s GridSearchCV on random forest model

Image by Annie Spratt via Unsplash

Finding the optimal tuning parameters for a machine learning problem can often be very difficult. We may encounter overfitting, which means our machine learning model trains too specifically on our training dataset and causes higher levels of error when applied to our test/holdout datasets. Or, we may run into underfitting, which means our model doesn’t train specifically enough to our training dataset. </content:encoded>

Below is the code I've been trying so far.

from bs4 import BeautifulSoup
import requests

resp = requests.get("https://towardsdatascience.com/feed")
soup = BeautifulSoup(resp.content, features='xml')
items = soup.findAll('item')
content_item = {}
content_item['title'] = items[0].title.text
content_item['link'] = items[0].link.text
content_item['Twitter'] = '@TDataScience'
content_item['Media'] = items[0].encoded['src']

As ever, any help you can offer would be very gratefully received.

Thanks in advance.

Body:
The first problem is that some items do not have <content:encoded> tag that is why it return NoneType object error when trying to access its contents. Even if all of them had that tag, still you wouldn't be able to get urls since it is xml encoded (as its name indicates). Therefore, you need to decode it using html.unescape() (or any other decoder that fits your needs) before applying further operations:

import requests
import html
from bs4 import BeautifulSoup

resp = requests.get("https://towardsdatascience.com/feed")
soup = BeautifulSoup(resp.content, features='xml')
items = soup.findAll('item')

content_item = {}
for each_item in items[:5]: # using first 5 elements just to test
    content_item['title'] = each_item.title.text
    content_item['link'] = each_item.link.text
    content_item['Twitter'] = '@TDataScience'

    if each_item.find('content:encoded'):
        # decode and form the new soup
        decoded_html = BeautifulSoup(html.unescape(each_item.encoded.text), 'lxml')

        content_item['Media'] = decoded_html.img["src"]
    else:
        content_item['Media'] = None

    print(content_item)

The output would look like:

{'title': '3 Steps to Getting a Job in Data with Zero Experience', 'link': 'https://towardsdatascience.com/3-steps-to-getting-a-job-in-data-with-zero-experience-ccaad96d6477?source=rss----7f60cf5620c9---4', 'Twitter': '@TDataScience', 'Media': None}
{'title': 'AI for painting: Unraveling Neural Style Transfer', 'link': 'https://towardsdatascience.com/ai-for-painting-unraveling-neural-style-transfer-5ac08a20a580?source=rss----7f60cf5620c9---4', 'Twitter': '@TDataScience', 'Media': 'https://cdn-images-1.medium.com/max/1024/0*DQt1CKiJSDMrzaWA'}
{'title': 'A Novel Way to Use Batch Normalization', 'link': 'https://towardsdatascience.com/a-novel-way-to-use-batch-normalization-837176d53525?source=rss----7f60cf5620c9---4', 'Twitter': '@TDataScience', 'Media': 'https://cdn-images-1.medium.com/max/1024/0*rRQ5moh4bTSCY1zR'}
{'title': 'How to Build A Pooled OLS Regression Model For Panel Data Sets', 'link': 'https://towardsdatascience.com/how-to-build-a-pooled-ols-regression-model-for-panel-data-sets-a78358f9c2a?source=rss----7f60cf5620c9---4', 'Twitter': '@TDataScience', 'Media': 'https://cdn-images-1.medium.com/max/1024/1*nv5gPBul4YsKGctA7b4OZg.png'}
{'title': 'Understanding the native R pipe |>', 'link': 'https://towardsdatascience.com/understanding-the-native-r-pipe-98dea6d8b61b?source=rss----7f60cf5620c9---4', 'Twitter': '@TDataScience', 'Media': 'https://cdn-images-1.medium.com/max/1024/1*pnjfZFqrY1opjEVNOSjcSg.png'}

Note that there are multiple <img> tags inside <content:encoded> tag, I just fetched the first one as an example.


问:
Finding the last occurrence of x in the array
I want to find the last occurrence of x(13) in the array which is 6, but my code only finds the first occurrences which is 4, is there a way I can solve this?</p>
```<code>/* Application Program */
int[] arr = {9, 12, 2, 8, 13, -8, 13, 9};
int index = lastIndexOf(arr, 13);

if(index != -1)
    System.out.println(index);
else
    System.out.println("not found");

/* Method */
public static int lastIndexOf(int[] arr, int x){
    for(int i = 0; i<arr.length; i++){
        if(arr[i] == x){
            return i;
        }
    }
    return -1;
}
</code>```

答:
```<code>Using java Map based approach.

 public static int lastIndexOfV1(int[] arr, int x) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < arr.length; i++) {
            map.put(arr[i], i);
        }
        return map.get(x);
    }
</code>```

Body:
I want to find the last occurrence of x(13) in the array which is 6, but my code only finds the first occurrences which is 4, is there a way I can solve this?

/* Application Program */
int[] arr = {9, 12, 2, 8, 13, -8, 13, 9};
int index = lastIndexOf(arr, 13);

if(index != -1)
    System.out.println(index);
else
    System.out.println("not found");

/* Method */
public static int lastIndexOf(int[] arr, int x){
    for(int i = 0; i<arr.length; i++){
        if(arr[i] == x){
            return i;
        }
    }
    return -1;
}


问:
PHPMailer: SMTP ERROR: Failed to connect to server: (0) with godaddy
I am getting the error:

```<code>    2020-05-03 02:33:55 SMTP ERROR: Failed to connect to server: (0)
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
</code>```

I have looked at all GoDaddy articles and stack articles I can find and tried their solutions - such as changing ports, etc. I have also tried with both my Gmail and cPanel web/email accounts. Most solutions out there for this error, however, are not relating to GoDaddy, and their solutions are to do with XAMPP, etc.
Any help is greatly appreciated :)

As reference, here is the PHP code:

```<code>use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require 'src/Exception.php';
require 'src/PHPMailer.php';
require 'src/SMTP.php';

$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl';
$mail->Host = "localhost";
$mail->Port = 465;
$mail->IsHTML(true);
$mail->Username = "abc@def.com";
$mail->Password = "xxx";
$mail->SetFrom("abc@def.com");
$mail->Subject = "Test";
$mail->Body = "hello";
$mail->AddAddress("uvw@xyz.com");

 if(!$mail->Send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
 } else {
    echo "Message has been sent";
 }
</code>```

答:
Before sending emails using the Gmail's SMTP Server, you to make some of the security and permission level settings under your Google Account Security Settings.

change

$mail->host  = "localhost";

to

$mail->Host = "smtp.gmail.com";

Use real email for sender and receiver 'Make sure of the password'

change

$mail->SMTPSecure = 'ssl';

to

$mail->SMTPSecure = 'tls';

```<code>   //tls for localhost and ssl for host server 'onligne'
</code>```

may work for you :)

Body:
I am getting the error:

    2020-05-03 02:33:55 SMTP ERROR: Failed to connect to server: (0)
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

I have looked at all GoDaddy articles and stack articles I can find and tried their solutions - such as changing ports, etc. I have also tried with both my Gmail and cPanel web/email accounts. Most solutions out there for this error, however, are not relating to GoDaddy, and their solutions are to do with XAMPP, etc.
Any help is greatly appreciated :)

As reference, here is the PHP code:

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require 'src/Exception.php';
require 'src/PHPMailer.php';
require 'src/SMTP.php';

$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl';
$mail->Host = "localhost";
$mail->Port = 465;
$mail->IsHTML(true);
$mail->Username = "abc@def.com";
$mail->Password = "xxx";
$mail->SetFrom("abc@def.com");
$mail->Subject = "Test";
$mail->Body = "hello";
$mail->AddAddress("uvw@xyz.com");

 if(!$mail->Send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
 } else {
    echo "Message has been sent";
 }

Body:
Before sending emails using the Gmail's SMTP Server, you to make some of the security and permission level settings under your Google Account Security Settings.

change

$mail->host  = "localhost";

to

$mail->Host = "smtp.gmail.com";

Use real email for sender and receiver 'Make sure of the password'

change

$mail->SMTPSecure = 'ssl';

to

$mail->SMTPSecure = 'tls';

   //tls for localhost and ssl for host server 'onligne'

may work for you :)


问:
Docker: go get from a private GitHub repo
I'm trying to run a container that will expose a golang service from a package that I have on a private GitHub repo.

Since I am working with GCE, my starter image is google/debian:wheezy.

After installing all the required dependancies and tools, I am running

```<code>RUN go get github.com/<my_org>/<my_package>
</code>```

where the package is a private repo.

I have added my GitHub SSH keys to allow the cloning from the private repo to the docker file:

```<code>ADD priv/id_rsa /root/.ssh/id_rsa
ADD priv/id_rsa.pub /root/.ssh/id_rsa.pub
</code>```

Still, I am getting an error during the go get process when go tried to clone the repo:

```<code># cd .; git clone https://github.com/<my_org>/<my_package> /gopath/src/github.com/<my_org>/<my_package>
Cloning into '/gopath/src/github.com/<my_org>/<my_package>'...
fatal: could not read Username for 'https://github.com': No such device or address
package github.com/<my_org>/<my_package>: exit status 128
</code>```

To debug the problem, from the Dockerfile, I am running:

```<code>RUN ssh-keyscan -t rsa github.com 2>&1 >> /root/.ssh/known_hosts
</code>```

And this tells me there are some problems. It looks like validating the private key is OK but something weird is going on the the public key. This is the complete ssh-keyscan result:

```<code>OpenSSH_6.0p1 Debian-4+deb7u2, OpenSSL 1.0.1e 11 Feb 2013
Pseudo-terminal will not be allocated because stdin is not a terminal.
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug1: Connecting to github.com [192.30.252.129] port 22.
debug1: Connection established.
debug1: permanently_set_uid: 0/0
debug1: identity file /root/.ssh/id_rsa type 1
debug1: Checking blacklist file /usr/share/ssh/blacklist.RSA-2048
debug1: Checking blacklist file /etc/ssh/blacklist.RSA-2048
debug1: identity file /root/.ssh/id_rsa-cert type -1
debug1: identity file /root/.ssh/id_dsa type -1
debug1: identity file /root/.ssh/id_dsa-cert type -1
debug1: identity file /root/.ssh/id_ecdsa type -1
debug1: identity file /root/.ssh/id_ecdsa-cert type -1
debug1: Remote protocol version 2.0, remote software version libssh-0.6.0
debug1: no match: libssh-0.6.0
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_6.0p1 Debian-4+deb7u2
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr hmac-sha1 none
debug1: kex: client->server aes128-ctr hmac-sha1 none
debug1: sending SSH2_MSG_KEX_ECDH_INIT
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: RSA 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48
debug1: Host 'github.com' is known and matches the RSA host key.
debug1: Found key in /root/.ssh/known_hosts:1
Warning: Permanently added the RSA host key for IP address '192.30.252.129' to the list of known hosts.
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /root/.ssh/id_rsa
debug1: Server accepts key: pkalg ssh-rsa blen 279
debug1: key_parse_private_pem: PEM_read_PrivateKey failed
debug1: read PEM private key done: type <unknown>
debug1: read_passphrase: can't open /dev/tty: No such device or address
debug1: Trying private key: /root/.ssh/id_dsa
debug1: Trying private key: /root/.ssh/id_ecdsa
debug1: No more authentication methods to try.
Permission denied (publickey).
</code>```

I have tried chmod 600 and chmod 700 on the priv/public keys, this did not help.

Any clues? Has anyone succeeding in running go get that fetches from private repos on debian from docker?

答:
i had this problem in Github and i fix it using personal access token:

first of all please use ARG for your Dockerfile vars(inputs):

after that configure your git with github personal access token

GITHUB_PAT -> github personal access token

```<code>FROM golang:1.17 as builder

ARG GITHUB_PAT

WORKDIR /your-app
COPY go.mod .
COPY go.sum .
RUN git config --global url."https://${GITHUB_PAT}:x-oauth-basic@github.com/".insteadOf "https://github.com/"
RUN go mod download
COPY . .
RUN go build -ldflags '-w -s' -o ./out ./main.go

FROM golang:1.17

WORKDIR /app

COPY --from=builder /your-app/out ./
WORKDIR /app/

ENTRYPOINT [ "./out" ]
</code>```

Body:
I'm trying to run a container that will expose a golang service from a package that I have on a private GitHub repo.

Since I am working with GCE, my starter image is google/debian:wheezy.

After installing all the required dependancies and tools, I am running

RUN go get github.com/<my_org>/<my_package>

where the package is a private repo.

I have added my GitHub SSH keys to allow the cloning from the private repo to the docker file:

ADD priv/id_rsa /root/.ssh/id_rsa
ADD priv/id_rsa.pub /root/.ssh/id_rsa.pub

Still, I am getting an error during the go get process when go tried to clone the repo:

# cd .; git clone https://github.com/<my_org>/<my_package> /gopath/src/github.com/<my_org>/<my_package>
Cloning into '/gopath/src/github.com/<my_org>/<my_package>'...
fatal: could not read Username for 'https://github.com': No such device or address
package github.com/<my_org>/<my_package>: exit status 128

To debug the problem, from the Dockerfile, I am running:

RUN ssh-keyscan -t rsa github.com 2>&1 >> /root/.ssh/known_hosts

And this tells me there are some problems. It looks like validating the private key is OK but something weird is going on the the public key. This is the complete ssh-keyscan result:

OpenSSH_6.0p1 Debian-4+deb7u2, OpenSSL 1.0.1e 11 Feb 2013
Pseudo-terminal will not be allocated because stdin is not a terminal.
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug1: Connecting to github.com [192.30.252.129] port 22.
debug1: Connection established.
debug1: permanently_set_uid: 0/0
debug1: identity file /root/.ssh/id_rsa type 1
debug1: Checking blacklist file /usr/share/ssh/blacklist.RSA-2048
debug1: Checking blacklist file /etc/ssh/blacklist.RSA-2048
debug1: identity file /root/.ssh/id_rsa-cert type -1
debug1: identity file /root/.ssh/id_dsa type -1
debug1: identity file /root/.ssh/id_dsa-cert type -1
debug1: identity file /root/.ssh/id_ecdsa type -1
debug1: identity file /root/.ssh/id_ecdsa-cert type -1
debug1: Remote protocol version 2.0, remote software version libssh-0.6.0
debug1: no match: libssh-0.6.0
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_6.0p1 Debian-4+deb7u2
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr hmac-sha1 none
debug1: kex: client->server aes128-ctr hmac-sha1 none
debug1: sending SSH2_MSG_KEX_ECDH_INIT
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: RSA 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48
debug1: Host 'github.com' is known and matches the RSA host key.
debug1: Found key in /root/.ssh/known_hosts:1
Warning: Permanently added the RSA host key for IP address '192.30.252.129' to the list of known hosts.
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /root/.ssh/id_rsa
debug1: Server accepts key: pkalg ssh-rsa blen 279
debug1: key_parse_private_pem: PEM_read_PrivateKey failed
debug1: read PEM private key done: type <unknown>
debug1: read_passphrase: can't open /dev/tty: No such device or address
debug1: Trying private key: /root/.ssh/id_dsa
debug1: Trying private key: /root/.ssh/id_ecdsa
debug1: No more authentication methods to try.
Permission denied (publickey).

I have tried chmod 600 and chmod 700 on the priv/public keys, this did not help.

Any clues? Has anyone succeeding in running go get that fetches from private repos on debian from docker?

Body:
i had this problem in Github and i fix it using personal access token:

first of all please use ARG for your Dockerfile vars(inputs):

after that configure your git with github personal access token

GITHUB_PAT -> github personal access token

FROM golang:1.17 as builder

ARG GITHUB_PAT

WORKDIR /your-app
COPY go.mod .
COPY go.sum .
RUN git config --global url."https://${GITHUB_PAT}:x-oauth-basic@github.com/".insteadOf "https://github.com/"
RUN go mod download
COPY . .
RUN go build -ldflags '-w -s' -o ./out ./main.go

FROM golang:1.17

WORKDIR /app

COPY --from=builder /your-app/out ./
WORKDIR /app/

ENTRYPOINT [ "./out" ]


问:
Discord.js isnt sending the embed due to non-empty string error
```<code>const { SlashCommandBuilder } = require('@discordjs/builders')
const discord = require('discord.js')
const open = require('openweather-api-node');
module.exports = {
    data: new SlashCommandBuilder()
        .setName('weather')
        .setDescription('Shows the Weather condition of a place')
        .addStringOption(option =>
            option.setName('city')
                .setDescription('Name of the city')
                .setRequired(true)),

    async execute(Discord, client, interaction) {

        let city = interaction.options.getString('city');

        let weather = new open({
            key: process.env.WEATHER,

            units: 'metric'
        })

        weather.setLanguage('en')
     let info = await   weather.getCurrent({ locationName: city })

      if(!info) return interaction.reply({content:"Oops "})
            //location
            var lon = info.lon.toString()
            var lat = info.lat.toString()
            let Timezone = info.timezone

            //Temperature
            var temp =  info.weather.temp.cur.toString()
            let feel_like = info.weather.feels_like.cur
            let min = info.weather.temp.min
            let max =info.weather.temp.max

            //air condition
            let pressure = info.weather.pressure
            let humidity = info.weather.humidity + '%'
            let wind = info.weather.wind.speed + 'km/h'

            //description

            let sky = info.weather.description
            let status = info.weather.main

        console.log(temp)
        console.log(lon)
        console.log(lat)

            let new1 = new discord.MessageEmbed()
            new1.setTitle(city + `'s Weather`)
            new1.setDescription('bruh pls work')
            new1.setColor('#0099ff')
            new1.addFields('**Location**', `Latitude:`+ lat,true)
            new1.addFields('**Temperature**', `${temp}℃`,true)
            new1.setTimestamp()
            new1.setFooter({ text: 'Information by Open-Weather' })

            interaction.reply({embeds:[new1]})

    }
}
</code>```

So this is my code
the temp,lan,lat variables were number but i changed them into string
and even checked with the typeof method
It gave me a string

But still i'm facing out this error called RangeError [EMBED_FIELD_NAME]: MessageEmbed field names must be non-empty string

Please help me if you know whats the solution

答: You use addFields to add one field, maybe you should try addField</p>

Body:
const { SlashCommandBuilder } = require('@discordjs/builders')
const discord = require('discord.js')
const open = require('openweather-api-node');
module.exports = {
    data: new SlashCommandBuilder()
        .setName('weather')
        .setDescription('Shows the Weather condition of a place')
        .addStringOption(option =>
            option.setName('city')
                .setDescription('Name of the city')
                .setRequired(true)),

    async execute(Discord, client, interaction) {

        let city = interaction.options.getString('city');

        let weather = new open({
            key: process.env.WEATHER,

            units: 'metric'
        })

        weather.setLanguage('en')
     let info = await   weather.getCurrent({ locationName: city })

      if(!info) return interaction.reply({content:"Oops "})
            //location
            var lon = info.lon.toString()
            var lat = info.lat.toString()
            let Timezone = info.timezone

            //Temperature
            var temp =  info.weather.temp.cur.toString()
            let feel_like = info.weather.feels_like.cur
            let min = info.weather.temp.min
            let max =info.weather.temp.max

            //air condition
            let pressure = info.weather.pressure
            let humidity = info.weather.humidity + '%'
            let wind = info.weather.wind.speed + 'km/h'

            //description

            let sky = info.weather.description
            let status = info.weather.main

        console.log(temp)
        console.log(lon)
        console.log(lat)

            let new1 = new discord.MessageEmbed()
            new1.setTitle(city + `'s Weather`)
            new1.setDescription('bruh pls work')
            new1.setColor('#0099ff')
            new1.addFields('**Location**', `Latitude:`+ lat,true)
            new1.addFields('**Temperature**', `${temp}℃`,true)
            new1.setTimestamp()
            new1.setFooter({ text: 'Information by Open-Weather' })

            interaction.reply({embeds:[new1]})

    }
}

So this is my code
the temp,lan,lat variables were number but i changed them into string
and even checked with the typeof method
It gave me a string

But still i'm facing out this error called RangeError [EMBED_FIELD_NAME]: MessageEmbed field names must be non-empty string

Please help me if you know whats the solution


问:
SQL Server 2008 Query is slow in production but fast in development
I have a query that runs in about 2-4 minutes on production but runs in a couple of seconds on development. Both of these databases are on the same exact server. (no lectures about dev and production, production is really still in development).

I mean, I can just open two query windows and get the two different results consistently. I have ran RedGate SQLCompare and there is no schema difference (indexes and so forth) difference. I have disabled the site that connects to the DB so there should be no connections other than my Management Studio session.

What could be causing this? I create the development database by copying the production one (in the Management Studio, right click database and click "Copy Database")

This is really strange. I don't want to make any index changes because the weird thing is that the copy is blazing fast but the production is very, very slow but should be essentially exact copies.

答: In my case it turned out to be because the production database is off site (different city) and the development database is in the building. duh. The query was returning a lot of data and of course that amount of data takes longer over the external network. I simply didn't connect the dots since the production DB was so much faster than the old development box and most of our queries don't return enough data for the network to be the speed factor. Rather it is but the production box is so much faster that even with the slower network connection most queries were still returning faster than from the development box.</p>


问:
specify mime type for dataUri when using webpacks asset/inline
I'm loading audio files with webpacks asset/inline

```<code>{
  test: /\.(wav)$/i,
  type: 'asset/inline',
}
</code>```
```<code>import someWAV from './wav/some.wav'
</code>```

working all fine, files get imported as dataUris.

But the dataUri beginning with: data:audio/wave;base64,

I need to change the mime-type to audio/wav (without the trailing e) to make it work with the audio library I use.

Can you do that in the webpack config, rather than doing something ugly like this?

```<code>someWAV = someWAV.replace('audio/wave', 'audio/wav')
</code>```

I tried just adding the mimeType parameter to the rule, but that didn't work at all...

答:
thanks @grzegorz-t, content in the generator callback is the raw content though, so you need to do something like this:

{
  test: /\.wav/,
  type: 'asset/inline',
  generator: {
    dataUrl: (content) => {
      return `data:audio/wav;base64,${content.toString('base64')}`
    },
  },
}
```

Body:
I'm loading audio files with webpacks asset/inline

{
  test: /\.(wav)$/i,
  type: 'asset/inline',
}

import someWAV from './wav/some.wav'

working all fine, files get imported as dataUris.

But the dataUri beginning with: data:audio/wave;base64,

I need to change the mime-type to audio/wav (without the trailing e) to make it work with the audio library I use.

Can you do that in the webpack config, rather than doing something ugly like this?

someWAV = someWAV.replace('audio/wave', 'audio/wav')

I tried just adding the mimeType parameter to the rule, but that didn't work at all...


问:
what's a processing storage for HIVE?
I'm new to hive and read about it online too. But still having doubts which are not cleared.

for hive external tables, hive keep table's metadata within HDFS, but not in its warehouse which is also in HDFS. correct ?

whether its internal or external table, in both cases data of table will be available in HDFS only but NOWHERE else. Mean to say, data can taken from anywhere but has to be loaded in HDFS, because HIVE uses hadoop's processing engine to process data. Correct ?

internal table, table's metadata and table's data both will be available in HIVE's data warehouse, and this data warehouse will be at nowhere else but in HDFS only. correct ?

in external table, table's metadata and table's data both will be NOT available in HIVE's data warehouse but in HDFS. But hive must be keeping some info with itself that where is table's metadata located and where is its data located in HDFS, correct ?

Can anyone share feedback to above understanding ?

THanks

答:
Hive uses relational database like MySQL, MariaDB, PostgreSQL, Oracle, DerbyDB(for embedded deployment only) for storing metadata (databases, tables definitions, statistics, grants, etc). See deployment modes and database requirements. Does not matter Internal or external table, the metadata are stored in the relational database.

Yes, the data is stored in HDFS, but also Hive supports integration with external databases using JDBC storage handler. Such table looks like normal Hive table, but the data is stored in some database, your queries executed in the database, predicate push-down works, you can use hive native tables with storage handler tables in single query. Also HBase storage handler is available, Kafka storage handler, etc, you can write your own storage handler.

Depending on your Hive version/vendor It is possible to create many tables (both managed and external at the same time) on top of the same location in HDFS. Though Cloudera prefers to have managed tables in dedicated HDFS location for them, see https://stackoverflow.com/a/67073849/2700344 and does not allow to specify location for managed tables outside the warehouse root by default. Read abot the difference between managed and external tables here.

Title: what's a processing storage for HIVE?


问:
How to print numpy objects without line breaks
I am logging input arguments to a function using

```<code>logging.debug('Input to this function = %s',
              inspect.getargvalues(inspect.currentframe())[3])
</code>```

But I do not want the line breaks inserted within numpy objects.  numpy.set_printoptions(linewidth=np.nan) removes some, but line breaks are still inserted in 2D objects such as

```<code>array([[ 0.84148239,  0.71467895,  0.00946744,  0.3471317 ],
       [ 0.68041249,  0.20310698,  0.89486761,  0.97799646],
       [ 0.22328803,  0.32401271,  0.96479887,  0.43404245]])
</code>```

I want it to be like this:

```<code>array([[ 0.84148239,  0.71467895,  0.00946744,  0.3471317 ], [ 0.68041249,  0.20310698,  0.89486761,  0.97799646], [ 0.22328803,  0.32401271,  0.96479887,  0.43404245]])
</code>```

How can I do this?  Thanks.

Body:
I am logging input arguments to a function using

logging.debug('Input to this function = %s',
              inspect.getargvalues(inspect.currentframe())[3])

But I do not want the line breaks inserted within numpy objects.  numpy.set_printoptions(linewidth=np.nan) removes some, but line breaks are still inserted in 2D objects such as

array([[ 0.84148239,  0.71467895,  0.00946744,  0.3471317 ],
       [ 0.68041249,  0.20310698,  0.89486761,  0.97799646],
       [ 0.22328803,  0.32401271,  0.96479887,  0.43404245]])

I want it to be like this:

array([[ 0.84148239,  0.71467895,  0.00946744,  0.3471317 ], [ 0.68041249,  0.20310698,  0.89486761,  0.97799646], [ 0.22328803,  0.32401271,  0.96479887,  0.43404245]])

How can I do this?  Thanks.

Body:
This solution also works:

myArray = np.array([[ 0.84148239,  0.71467895,  0.00946744,  0.3471317 ],
       [ 0.68041249,  0.20310698,  0.89486761,  0.97799646],
       [ 0.22328803,  0.32401271,  0.96479887,  0.43404245]])

print(np.array2string(myArray).replace('\n','').replace(' ',', '))

Output:

[[0.84148239, 0.71467895, 0.00946744, 0.3471317, ], [0.68041249, 0.20310698, 0.89486761, 0.97799646], [0.22328803, 0.32401271, 0.96479887, 0.43404245]]


问:
Bootstrap 5 background color is having opacity
I'm trying to create a OR divider, but in bootstrap 5 its not working correctly which is working properly in bootstrap 4. In my project bootstrap 5 is being used. Background color of text is having some opacity.

HTML:

```<code><div class="or-line-block pt-2">
    <h6 class="text-center m-0"><span class="or-txt px-2">OR</span></h6>
    <hr class="or-line">
</div>
</code>```

CSS:

```<code>.or-txt{
    background-color: white;
}
.or-line{
    margin-top: -10px;
    border-color: rgba(#333, 0.1);
}
</code>```

In Bootstrap 4:

In Bootstrap 5:

What is the issue. Please help

答:
I've been made this way</p>
```<code><div style="width: 100%; height: 20px; border-bottom: 1px solid darkgray; text-align: center">
    <span style="font-size: 20px; background-color: white; padding: 0 10px;">
      or<!--Padding is optional-->
    </span>
  </div>
</code>```

Body:
I'm trying to create a OR divider, but in bootstrap 5 its not working correctly which is working properly in bootstrap 4. In my project bootstrap 5 is being used. Background color of text is having some opacity.

HTML:

OR

CSS:

.or-txt{
    background-color: white;
}
.or-line{
    margin-top: -10px;
    border-color: rgba(#333, 0.1);
}

In Bootstrap 4:

In Bootstrap 5:

What is the issue. Please help

Body:
I've been made this way

<div style="width: 100%; height: 20px; border-bottom: 1px solid darkgray; text-align: center">
    <span style="font-size: 20px; background-color: white; padding: 0 10px;">
      or<!--Padding is optional-->
    </span>
  </div>


问:
Kafka SSL : Create Topic Error while executing topic command : KeeperErrorCode = NoAuth for /config/topics/ssl-topic
I have set up SSL for zookeeper and Kafka clients. Zookeeper server and Kafka broker is started successfully. While I have created kafka topic then it gives the error.

kafka-topics.bat -zookeeper localhost:2181 --create --topic ssl-topic  --partitions 1 --replication-factor 1

Error :

Error while executing topic command : KeeperErrorCode = NoAuth for
/config/topics/ssl-topic [2022-02-06 14:08:24,637] ERROR
org.apache.zookeeper.KeeperException$NoAuthException: KeeperErrorCode
= NoAuth for /config/topics/ssl-topic
at org.apache.zookeeper.KeeperException.create(KeeperException.java:120)
at org.apache.zookeeper.KeeperException.create(KeeperException.java:54)
at kafka.zookeeper.AsyncResponse.maybeThrow(ZooKeeperClient.scala:564)
at kafka.zk.KafkaZkClient.createRecursive(KafkaZkClient.scala:1644)
at kafka.zk.KafkaZkClient.createOrSet$1(KafkaZkClient.scala:364)
at kafka.zk.KafkaZkClient.setOrCreateEntityConfigs(KafkaZkClient.scala:374)
at kafka.zk.AdminZkClient.createTopicWithAssignment(AdminZkClient.scala:93)
at kafka.zk.AdminZkClient.createTopic(AdminZkClient.scala:57)
at kafka.admin.TopicCommand$ZookeeperTopicService.createTopic(TopicCommand.scala:353)
at kafka.admin.TopicCommand$TopicService.createTopic(TopicCommand.scala:196)
at kafka.admin.TopicCommand$TopicService.createTopic$(TopicCommand.scala:191)
at kafka.admin.TopicCommand$ZookeeperTopicService.createTopic(TopicCommand.scala:345)
at kafka.admin.TopicCommand$.main(TopicCommand.scala:62)
at kafka.admin.TopicCommand.main(TopicCommand.scala)  (kafka.admin.TopicCommand$)

Zookeeper.properties are like

```<code>dataDir=D:/tmp/zookeeper

admin.enableServer=true admin.serverPort=8080

ssl.client.enable=true secureClientPort=2182 authProvider.x509=org.apache.zookeeper.server.auth.X509AuthenticationProvider serverCnxnFactory=org.apache.zookeeper.server.NettyServerCnxnFactory ssl.trustStore.location=C:/kafka_2.12-2.5.0/ssl/kafka.zookeeper.truststore.jks ssl.trustStore.password=pass ssl.keyStore.location=C:/kafka_2.12-2.5.0/ssl/kafka.zookeeper.keystore.jks ssl.keyStore.password=pass ssl.clientAuth=need
</code>```

Server.properties are like

```<code>zookeeper.connect=localhost:2182
zookeeper.clientCnxnSocket=org.apache.zookeeper.ClientCnxnSocketNetty
zookeeper.ssl.client.enable=true
zookeeper.ssl.protocol=TLSv1.2
zookeeper.ssl.truststore.location=C:/kafka_2.12-2.5.0/ssl/kafka.broker.truststore.jks
zookeeper.ssl.truststore.password=Becker77
zookeeper.ssl.keystore.location=C:/kafka_2.12-2.5.0/ssl/kafka.broker.keystore.jks
zookeeper.ssl.keystore.password=Becker77
zookeeper.set.acl=true

ssl.truststore.location=C:/kafka_2.12-2.5.0/ssl/kafka.broker.truststore.jks
ssl.truststore.password=Becker77
ssl.keystore.location=C:/kafka_2.12-2.5.0/ssl/kafka.broker.keystore.jks
ssl.keystore.password=Becker77
ssl.key.password=Becker77
security.inter.broker.protocol=SSL
ssl.client.auth=required
ssl.protocol=TLSv1.2
</code>```

答: Try Setting  zookeeper.set.acl=false or configure acl

Body:
I have set up SSL for zookeeper and Kafka clients. Zookeeper server and Kafka broker is started successfully. While I have created kafka topic then it gives the error.

kafka-topics.bat -zookeeper localhost:2181 --create --topic ssl-topic  --partitions 1 --replication-factor 1

Error :

Error while executing topic command : KeeperErrorCode = NoAuth for
/config/topics/ssl-topic [2022-02-06 14:08:24,637] ERROR
org.apache.zookeeper.KeeperException$NoAuthException: KeeperErrorCode
= NoAuth for /config/topics/ssl-topic
at org.apache.zookeeper.KeeperException.create(KeeperException.java:120)
at org.apache.zookeeper.KeeperException.create(KeeperException.java:54)
at kafka.zookeeper.AsyncResponse.maybeThrow(ZooKeeperClient.scala:564)
at kafka.zk.KafkaZkClient.createRecursive(KafkaZkClient.scala:1644)
at kafka.zk.KafkaZkClient.createOrSet$1(KafkaZkClient.scala:364)
at kafka.zk.KafkaZkClient.setOrCreateEntityConfigs(KafkaZkClient.scala:374)
at kafka.zk.AdminZkClient.createTopicWithAssignment(AdminZkClient.scala:93)
at kafka.zk.AdminZkClient.createTopic(AdminZkClient.scala:57)
at kafka.admin.TopicCommand$ZookeeperTopicService.createTopic(TopicCommand.scala:353)
at kafka.admin.TopicCommand$TopicService.createTopic(TopicCommand.scala:196)
at kafka.admin.TopicCommand$TopicService.createTopic$(TopicCommand.scala:191)
at kafka.admin.TopicCommand$ZookeeperTopicService.createTopic(TopicCommand.scala:345)
at kafka.admin.TopicCommand$.main(TopicCommand.scala:62)
at kafka.admin.TopicCommand.main(TopicCommand.scala)  (kafka.admin.TopicCommand$)

Zookeeper.properties are like

dataDir=D:/tmp/zookeeper

admin.enableServer=true admin.serverPort=8080

ssl.client.enable=true secureClientPort=2182 authProvider.x509=org.apache.zookeeper.server.auth.X509AuthenticationProvider serverCnxnFactory=org.apache.zookeeper.server.NettyServerCnxnFactory ssl.trustStore.location=C:/kafka_2.12-2.5.0/ssl/kafka.zookeeper.truststore.jks ssl.trustStore.password=pass ssl.keyStore.location=C:/kafka_2.12-2.5.0/ssl/kafka.zookeeper.keystore.jks ssl.keyStore.password=pass ssl.clientAuth=need

Server.properties are like

zookeeper.connect=localhost:2182
zookeeper.clientCnxnSocket=org.apache.zookeeper.ClientCnxnSocketNetty
zookeeper.ssl.client.enable=true
zookeeper.ssl.protocol=TLSv1.2
zookeeper.ssl.truststore.location=C:/kafka_2.12-2.5.0/ssl/kafka.broker.truststore.jks
zookeeper.ssl.truststore.password=Becker77
zookeeper.ssl.keystore.location=C:/kafka_2.12-2.5.0/ssl/kafka.broker.keystore.jks
zookeeper.ssl.keystore.password=Becker77
zookeeper.set.acl=true

ssl.truststore.location=C:/kafka_2.12-2.5.0/ssl/kafka.broker.truststore.jks
ssl.truststore.password=Becker77
ssl.keystore.location=C:/kafka_2.12-2.5.0/ssl/kafka.broker.keystore.jks
ssl.keystore.password=Becker77
ssl.key.password=Becker77
security.inter.broker.protocol=SSL
ssl.client.auth=required
ssl.protocol=TLSv1.2


问:
mypy error for setup with inheritance of function that depends on class function defined differently in both classes
I have a setup that looks as following:

```<code>from typing import TypeVar

MyType = TypeVar('MyType', bound='TestClass')

class TestClass():
    def __init__(self, number):
        self.number = number

    def __mul__(self, multiplicator: int) -> 'TestClass':
        return TestClass(self.number*multiplicator)

    def test_mul(self: MyType, multiplicator: int) -> MyType:
        return self*multiplicator

class InheritingClass(TestClass):

    def __mul__(self, multiplicator: int) -> 'InheritingClass':
        return InheritingClass(self.number*multiplicator+1)
</code>```

Evaluating this with mypy returns the error Incompatible return value type (got "TestClass", expected "MyType") in the line return self*multiplicator in TestClass.test_mul

The goal here is to ultimately have two different objects, where one inherits the properties of the other, and have them use the same test_mul function while making use of a different __mul__ function. I want to be able to call the test_mul function on either class, with the respective __mul__ functions of each class being called accordingly. Is there a way to achieve that without altering the way a new instance of the own class is returned in each __mul__ function? If not, how would an alternative look here?

答:
The problem is in __mul__ in TestClass: it should return MyType and use type(self).

```<code>MyType = TypeVar('MyType', bound='TestClass')

class TestClass():

    def __init__(self, number):
        self.number = number

    def __mul__(self: MyType, multiplicator: int) -> MyType:
        return type(self)(self.number * multiplicator)

    def test_mul(self: MyType, multiplicator: int) -> MyType:
        x: MyType = self * multiplicator
        return x

class InheritingClass(TestClass):

    def __mul__(self, multiplicator: int) -> 'InheritingClass':
        return InheritingClass(self.number * multiplicator + 1)

tc = TestClass(1)
tcx = tc * 3
tcy = tc.test_mul(4)
if TYPE_CHECKING:
    # Mypy: Revealed type is "Tuple[TestClass*, TestClass*]"
    reveal_type((tcx, tcy))
ic = InheritingClass(2)
icx = ic * 3
icy = ic.test_mul(4)
if TYPE_CHECKING:
    # Mypy: Revealed type is "Tuple[InheritingClass, InheritingClass*]"
    reveal_type((icx, icy))
</code>```

Body:
I have a setup that looks as following:

from typing import TypeVar

MyType = TypeVar('MyType', bound='TestClass')

class TestClass():
    def __init__(self, number):
        self.number = number

    def __mul__(self, multiplicator: int) -> 'TestClass':
        return TestClass(self.number*multiplicator)

    def test_mul(self: MyType, multiplicator: int) -> MyType:
        return self*multiplicator

class InheritingClass(TestClass):

    def __mul__(self, multiplicator: int) -> 'InheritingClass':
        return InheritingClass(self.number*multiplicator+1)

Evaluating this with mypy returns the error Incompatible return value type (got "TestClass", expected "MyType") in the line return self*multiplicator in TestClass.test_mul

The goal here is to ultimately have two different objects, where one inherits the properties of the other, and have them use the same test_mul function while making use of a different __mul__ function. I want to be able to call the test_mul function on either class, with the respective __mul__ functions of each class being called accordingly. Is there a way to achieve that without altering the way a new instance of the own class is returned in each __mul__ function? If not, how would an alternative look here?

Body:
The problem is in __mul__ in TestClass: it should return MyType and use type(self).

MyType = TypeVar('MyType', bound='TestClass')

class TestClass():

    def __init__(self, number):
        self.number = number

    def __mul__(self: MyType, multiplicator: int) -> MyType:
        return type(self)(self.number * multiplicator)

    def test_mul(self: MyType, multiplicator: int) -> MyType:
        x: MyType = self * multiplicator
        return x

class InheritingClass(TestClass):

    def __mul__(self, multiplicator: int) -> 'InheritingClass':
        return InheritingClass(self.number * multiplicator + 1)

tc = TestClass(1)
tcx = tc * 3
tcy = tc.test_mul(4)
if TYPE_CHECKING:
    # Mypy: Revealed type is "Tuple[TestClass*, TestClass*]"
    reveal_type((tcx, tcy))
ic = InheritingClass(2)
icx = ic * 3
icy = ic.test_mul(4)
if TYPE_CHECKING:
    # Mypy: Revealed type is "Tuple[InheritingClass, InheritingClass*]"
    reveal_type((icx, icy))


问:
How do you get the values from a function in javascript?
I am very new to the Javascript and I am wondering how I can get the values from a function.

From my given code I would like to get the values of TheName, TheHeight, and TheGender, TheSexuality when I run the function so that I can use them for other purposes in my program.

Code:

```<code>function prng ()
{
    var Name = Object.values(person.Names);
    var Height = Object.values(person.Heights);
    var Gender = Object.values(person.Genders);
    var Sexuality = Object.values(person.Sexualities);
    var TheName = Name[Math.floor(Math.random() * Name.length)];
    var TheHeight = Height[Math.floor(Math.random() * Height.length)];
    var TheGender = Gender[Math.floor(Math.random() * Gender.length)];
    var TheSexuality = Sexuality[Math.floor(Math.random() * Sexuality.length)];
    console.log('Name: ' + TheName + ', Height: ' + TheHeight +
    ', Gender: ' + TheGender + ', Sexuality: ' + TheSexuality);
}
</code>```

Any help would be greatly appreciated. :)

答:
you write something like that:

function nameYourFunction ()
{
...
instead of console.log(...) you write:
return 'Name: ' + TheName +...+ TheSexuality;

}

or you add all varibles to one object like that:
https://www.w3schools.com/js/js_objects.asp

Body:
I am very new to the Javascript and I am wondering how I can get the values from a function.

From my given code I would like to get the values of TheName, TheHeight, and TheGender, TheSexuality when I run the function so that I can use them for other purposes in my program.

Code:

function prng ()
{
    var Name = Object.values(person.Names);
    var Height = Object.values(person.Heights);
    var Gender = Object.values(person.Genders);
    var Sexuality = Object.values(person.Sexualities);
    var TheName = Name[Math.floor(Math.random() * Name.length)];
    var TheHeight = Height[Math.floor(Math.random() * Height.length)];
    var TheGender = Gender[Math.floor(Math.random() * Gender.length)];
    var TheSexuality = Sexuality[Math.floor(Math.random() * Sexuality.length)];
    console.log('Name: ' + TheName + ', Height: ' + TheHeight +
    ', Gender: ' + TheGender + ', Sexuality: ' + TheSexuality);
}

Any help would be greatly appreciated. :)


问:
TypeError: Object(...) is not a function (redux)
I am having a TypeError (TypeError: Object(...) is not a function) when I want to dispatch an action. I'm not using any middleware and don't know what I can do to solve it. I had this error already yesterday but somehow managed to solve it (i donk know how i did this)

This is the App.js:

```<code>import React from "react";
import { store } from "../store";
import { withdrawMoney} from "../actions";

const App = () => {
return (
  <div className="app">
    <div className="card">
      <div className="card-header">
        Welcome to your bank account
      </div>
      <div className="card-body">
        <h1>Hello, {store.getState().name}!</h1>
        <ul className="list-group">
          <li className="list-group-item">
            <h4>Your total amount:</h4>
            {store.getState().balance}
          </li>
        </ul>
        <button className="btn btn-primary card-link" data-amount="5000" onClick={dispatchBtnAction}>Withdraw $5,000</button>
        <button className="btn btn-primary card-link" data-amount="10000" onClick={dispatchBtnAction}>Witdhraw $10,000</button>
      </div>
    </div>
  </div>
);
}

function dispatchBtnAction(e) {
  store.dispatch(withdrawMoney(e.target.dataset.amount));
}

export default App;
</code>```

Here is the actioncreator:

```<code>function withdrawMoney(amount) {
  return {
    type: "ADD_TODO",
    amount
  }
}
</code>```

If you need here is the reducer:

```<code>export default (state, action) => {
  console.log(action);
  return state
}
</code>```

As you can see I'm a very new to redux but I'd like to know what mistake I make all the time when dispatching an action. Thanks

答:
I was using redux toolkit and for me the problem was an extra '}'
such that my 'reducers' object, in 'createSlice' function, already had a closing curly brace before my second reducer
and my 2nd reducer was actually outside the 'reducers' object,
making it not a reducer and hence not working even when you export or import it properly.

So the problem is not in your export or import, but actually where your function is defined.
This may be different for other users, but in my case this turned out to be the cause of this error.

Body:
I am having a TypeError (TypeError: Object(...) is not a function) when I want to dispatch an action. I'm not using any middleware and don't know what I can do to solve it. I had this error already yesterday but somehow managed to solve it (i donk know how i did this)

This is the App.js:

import React from "react";
import { store } from "../store";
import { withdrawMoney} from "../actions";

const App = () => {
return (

        Welcome to your bank account

Hello, {store.getState().name}!

Your total amount:

            {store.getState().balance}

        <button className="btn btn-primary card-link" data-amount="5000" onClick={dispatchBtnAction}>Withdraw $5,000</button>
        <button className="btn btn-primary card-link" data-amount="10000" onClick={dispatchBtnAction}>Witdhraw $10,000</button>

);
}

function dispatchBtnAction(e) {
  store.dispatch(withdrawMoney(e.target.dataset.amount));
}

export default App;

Here is the actioncreator:

function withdrawMoney(amount) {
  return {
    type: "ADD_TODO",
    amount
  }
}

If you need here is the reducer:

export default (state, action) => {
  console.log(action);
  return state
}

As you can see I'm a very new to redux but I'd like to know what mistake I make all the time when dispatching an action. Thanks


问:
Why does this OpenGL + WIN32 code produce Vertical lines?
To be clear, I've extensively tested this code and found the issue is somewhere with the code written prior to the WGL code. It's precisely in the WIN32 code. Now I think it could partially be caused by calling gluOrth2D but even then, that shouldn't be the primary cause as far I as I understand. I may figure this out myself just by messing with stuff but considering this issue (that occured in a much larger project) has taken up a lot of my time I thought it was worth posting this encase anyone else runs into the same problem. I'm hoping for an explanation as well as fix/correction.</p>
```<code>#include <GL/glew.h>
#include <glfw3.h>
#define GLFW_EXPOSE_NATIVE_WGL
#define GLFW_EXPOSE_NATIVE_WIN32
#include <glfw3native.h>

constexpr int width = 1000, height = 1000;

bool running = true;

LRESULT CALLBACK WIN32_processMessage(HWND hwnd, UINT msg,
    WPARAM wparam, LPARAM lparam)
{
    return DefWindowProcA(hwnd, msg, wparam, lparam);
}

int main()
{
    HINSTANCE hinst = GetModuleHandleA(NULL);

    HICON icon = LoadIcon(hinst, IDI_APPLICATION);

    WNDCLASSA* wc = (WNDCLASSA*)memset(malloc(sizeof(WNDCLASSA)), 0, sizeof(WNDCLASSA));
    if (wc == NULL)
    {
        return -1;
    }

    wc->style = CS_DBLCLKS;
    wc->lpfnWndProc = WIN32_processMessage;
    wc->cbClsExtra = 0;
    wc->cbWndExtra = 0;
    wc->hInstance = hinst;
    wc->hIcon = icon;
    wc->hCursor = LoadCursor(NULL, IDC_ARROW);
    wc->hbrBackground = NULL;
    wc->lpszClassName = "toast_window_class";

    if (!RegisterClassA(wc))
    {
        return 1;
    }

    UINT32 windowX = 100;
    UINT32 windowY = 100;
    UINT32 windowWidth = width;
    UINT32 windowHeight = height;

    UINT32 windowStyle = WS_OVERLAPPED | WS_SYSMENU | WS_CAPTION;
    UINT32 windowExStyle = WS_EX_APPWINDOW;

    windowStyle |= WS_MAXIMIZEBOX;
    windowStyle |= WS_MINIMIZEBOX;
    windowStyle |= WS_THICKFRAME;

    RECT borderRect = { 0,0,0,0 };
    AdjustWindowRectEx(&borderRect, windowStyle, 0, windowExStyle);

    windowX += borderRect.left;
    windowY += borderRect.top;

    windowWidth += borderRect.right - borderRect.left;
    windowWidth += borderRect.bottom - borderRect.top;

    HWND window = CreateWindowExA(windowExStyle, "toast_window_class", (LPCSTR)"test",
        windowStyle, windowX, windowY, windowWidth, windowHeight, 0, 0, hinst, 0);

    if (window == 0)
    {
        return 2;
    }

    bool shouldActivate = true;
    const int showWindowCommandFlags = shouldActivate ? SW_SHOW : SW_SHOWNOACTIVATE;

    ShowWindow(window, showWindowCommandFlags);

    // WGL -----------------------------------------------------------
    HDC device = GetDC(window);

    PIXELFORMATDESCRIPTOR pfd;
    pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
    pfd.nVersion = 1;
    pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
    pfd.iPixelType = PFD_TYPE_RGBA;
    pfd.cColorBits = 32;
    pfd.cAlphaBits = 0;
    pfd.cAccumBits = 0;
    pfd.cDepthBits = 0;
    pfd.cStencilBits = 0;
    pfd.cAuxBuffers = 0;
    pfd.iLayerType = PFD_MAIN_PLANE;

    SetPixelFormat(device, ChoosePixelFormat(device, &pfd), &pfd);

    HGLRC render = wglCreateContext(device);

    wglMakeCurrent(device, render);

    // GLEW ---------------------------------------------------------

    const GLint res = glewInit();

    if (GLEW_OK != res)
    {
        return 1;
    }

    // setup OpenGL --------------------------------------------------
    gluOrtho2D(0, width, 0, height);

    // main loop -----------------------------------------------------
    while (running)
    {
        glClear(GL_COLOR_BUFFER_BIT);

        // rendering
        glBegin(GL_POINTS);
        for (int x = 10; x < width - 10; ++x)
        {
            for (int y = 10; y < height - 10; ++y)
            {
                glVertex2f(x, y);
            }
        }
        glEnd();

        SwapBuffers(device);
    }

    return 0;
}
</code>```

答:
Don't use GL_POINTS for drawing an image pixel-by-pixel.

For one, it's probably the most inefficient way (on any system, in any configuration) to go about, due to the way OpenGL, its implementations, and modern GPU do work. Instead – if using OpenGL – create a 2D array of the desired size, fill in the pixel values to your desire, then load the picture into a texture and draw a textured quad, or better yet a rectangle covering triangle which you crop using glScissor.

Back to your point-to-point drawing problems. The issue you're running is essentially rounding errors and the way OpenGL is transforming between modelview space, over projection space into NDC and finally the viewport. BTW, you're not calling glViewport, so any adjustments in window size are not taken into account.

The call to glOrtho2D will setup the transformation matrix (in your case the modelview, since you didn't bother to switch to the projection matrix) so that coordinates in the range [0; width]×[0; height] will map to NDC coordinates [-1; 1]×[-1; 1]. These ranges are closed, i.e. they do include their limiting values. However pixels in a pixel grid are addressed in a range over the integer numbers with the end of the range being open (i.e. ℤ²∩[0; width(×[0; height(). And that means, that if you use the viewport extents for an orthogonal projection without adjustment, there'll be an ever so slight difference between pixel indices and OpenGL coordinates. I'll leave it to you, as an exercise, to figure out the math for what kind of adjustment to make (hint, you'll have to subtract a certain fractional value of the viewport extents to some of the glOrtho parameters).

Now for certain window sizes you won't notice this problem, because for all "pixel" locations you put into OpenGL the round off will happen to coerce them toward your desired pixel locations. But for other window sizes, for certain coordinate values, the round off goes the other way, and you're left with columns and/or rows untouched. Which leads to the lines you're seeing sometimes.

Body:
To be clear, I've extensively tested this code and found the issue is somewhere with the code written prior to the WGL code. It's precisely in the WIN32 code. Now I think it could partially be caused by calling gluOrth2D but even then, that shouldn't be the primary cause as far I as I understand. I may figure this out myself just by messing with stuff but considering this issue (that occured in a much larger project) has taken up a lot of my time I thought it was worth posting this encase anyone else runs into the same problem. I'm hoping for an explanation as well as fix/correction.

#include <GL/glew.h>
#include <glfw3.h>
#define GLFW_EXPOSE_NATIVE_WGL
#define GLFW_EXPOSE_NATIVE_WIN32
#include <glfw3native.h>

constexpr int width = 1000, height = 1000;

bool running = true;

LRESULT CALLBACK WIN32_processMessage(HWND hwnd, UINT msg,
    WPARAM wparam, LPARAM lparam)
{
    return DefWindowProcA(hwnd, msg, wparam, lparam);
}

int main()
{
    HINSTANCE hinst = GetModuleHandleA(NULL);

    HICON icon = LoadIcon(hinst, IDI_APPLICATION);

    WNDCLASSA* wc = (WNDCLASSA*)memset(malloc(sizeof(WNDCLASSA)), 0, sizeof(WNDCLASSA));
    if (wc == NULL)
    {
        return -1;
    }

    wc->style = CS_DBLCLKS;
    wc->lpfnWndProc = WIN32_processMessage;
    wc->cbClsExtra = 0;
    wc->cbWndExtra = 0;
    wc->hInstance = hinst;
    wc->hIcon = icon;
    wc->hCursor = LoadCursor(NULL, IDC_ARROW);
    wc->hbrBackground = NULL;
    wc->lpszClassName = "toast_window_class";

    if (!RegisterClassA(wc))
    {
        return 1;
    }

    UINT32 windowX = 100;
    UINT32 windowY = 100;
    UINT32 windowWidth = width;
    UINT32 windowHeight = height;

    UINT32 windowStyle = WS_OVERLAPPED | WS_SYSMENU | WS_CAPTION;
    UINT32 windowExStyle = WS_EX_APPWINDOW;

    windowStyle |= WS_MAXIMIZEBOX;
    windowStyle |= WS_MINIMIZEBOX;
    windowStyle |= WS_THICKFRAME;

    RECT borderRect = { 0,0,0,0 };
    AdjustWindowRectEx(&borderRect, windowStyle, 0, windowExStyle);

    windowX += borderRect.left;
    windowY += borderRect.top;

    windowWidth += borderRect.right - borderRect.left;
    windowWidth += borderRect.bottom - borderRect.top;

    HWND window = CreateWindowExA(windowExStyle, "toast_window_class", (LPCSTR)"test",
        windowStyle, windowX, windowY, windowWidth, windowHeight, 0, 0, hinst, 0);

    if (window == 0)
    {
        return 2;
    }

    bool shouldActivate = true;
    const int showWindowCommandFlags = shouldActivate ? SW_SHOW : SW_SHOWNOACTIVATE;

    ShowWindow(window, showWindowCommandFlags);

    // WGL -----------------------------------------------------------
    HDC device = GetDC(window);

    PIXELFORMATDESCRIPTOR pfd;
    pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
    pfd.nVersion = 1;
    pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
    pfd.iPixelType = PFD_TYPE_RGBA;
    pfd.cColorBits = 32;
    pfd.cAlphaBits = 0;
    pfd.cAccumBits = 0;
    pfd.cDepthBits = 0;
    pfd.cStencilBits = 0;
    pfd.cAuxBuffers = 0;
    pfd.iLayerType = PFD_MAIN_PLANE;

    SetPixelFormat(device, ChoosePixelFormat(device, &pfd), &pfd);

    HGLRC render = wglCreateContext(device);

    wglMakeCurrent(device, render);

    // GLEW ---------------------------------------------------------

    const GLint res = glewInit();

    if (GLEW_OK != res)
    {
        return 1;
    }

    // setup OpenGL --------------------------------------------------
    gluOrtho2D(0, width, 0, height);

    // main loop -----------------------------------------------------
    while (running)
    {
        glClear(GL_COLOR_BUFFER_BIT);

        // rendering
        glBegin(GL_POINTS);
        for (int x = 10; x < width - 10; ++x)
        {
            for (int y = 10; y < height - 10; ++y)
            {
                glVertex2f(x, y);
            }
        }
        glEnd();

        SwapBuffers(device);
    }

    return 0;
}


问:
i used laravel pagination links, but i got big icos. < > call in tailwind css code
Hello $data = User::paginate(5); return view('users',compact('data'));  {!! $data->links() !!}

答:
Laravel uses tailwind JIT mode which imports (when you run npm run dev) required classes when they are needed, the pagination is not included in your HTML explicitly with links() so I believe required classes are not included

in the file tailwind.config.js, make sure that all the following are included in content:[]

content: [
    './resources/**/*.blade.php',
    './resources/**/*.js',
    './resources/**/*.vue',
    './vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php',
],
```


答: Everything seems correct except last one. When you create external table table metadata will be stored in the Hive otherwise you can not query through hive. HDFS itself keeps control of your data when you create external table. While when you create internal table Hive will be responsible. Dropping internal table drops your data and metadata but dropping external table only drops metadata from Hive. But your data will be remain inside of your file system. Thats why we are changing table types a lot as a workaround when some of our external connection is not compatible with our hive version.</p>

Title: what's a processing storage for HIVE?

Body:
I'm new to hive and read about it online too. But still having doubts which are not cleared.

for hive external tables, hive keep table's metadata within HDFS, but not in its warehouse which is also in HDFS. correct ?

whether its internal or external table, in both cases data of table will be available in HDFS only but NOWHERE else. Mean to say, data can taken from anywhere but has to be loaded in HDFS, because HIVE uses hadoop's processing engine to process data. Correct ?

internal table, table's metadata and table's data both will be available in HIVE's data warehouse, and this data warehouse will be at nowhere else but in HDFS only. correct ?

in external table, table's metadata and table's data both will be NOT available in HIVE's data warehouse but in HDFS. But hive must be keeping some info with itself that where is table's metadata located and where is its data located in HDFS, correct ?

Can anyone share feedback to above understanding ?

THanks