问:
How to convert an integer to a string in any base?
Python allows easy creation of an integer from a string of a given base via

```<code>int(str, base).
</code>```

I want to perform the inverse: creation of a string from an integer,
i.e. I want some function int2base(num, base), such that:

```<code>int(int2base(x, b), b) == x
</code>```

The function name/argument order is unimportant.

For any number x and base b that int() will accept.

This is an easy function to write: in fact it's easier than describing it in this question. However, I feel like I must be missing something.

I know about the functions bin, oct, hex, but I cannot use them for a few reasons:

Those functions are not available on older versions of Python, with which I need compatibility with (2.2)

I want a general solution that can be called the same way for different bases

I want to allow bases other than 2, 8, 16

Related

Python elegant inverse function of int(string, base)

Integer to base-x system using recursion in python

Base 62 conversion in Python

How to convert an integer to the shortest url-safe string in Python?

答:
The below provided Python code converts a Python integer to a string in arbitrary base ( from 2 up to infinity ) and works in both directions. So all the created strings can be converted back to Python integers by providing a string for N instead of an integer.
The code works only on positive numbers by intention (there is in my eyes some hassle about negative values and their bit representations I don't want to dig into). Just pick from this code what you need, want or like, or just have fun learning about available options. Much is there only for the purpose of documenting all the various available approaches ( e.g. the Oneliner seems not to be fast, even if promised to be ).

I like the by Salvador Dali proposed format for infinite large bases. A nice proposal which works optically well even for simple binary bit representations. Notice that the width=x padding parameter in case of infiniteBase=True formatted string applies to the digits and not to the whole number. It seems, that code handling infiniteBase digits format runs even a bit faster than the other options - another reason for using it?

I don't like the idea of using Unicode for extending the number of symbols available for digits, so don't look in the code below for it, because it's not there. Use the proposed infiniteBase format instead or store integers as bytes for compression purposes.

```<code>    def inumToStr( N, base=2, width=1, infiniteBase=False,\
    useNumpy=False, useRecursion=False, useOneliner=False, \
    useGmpy=False, verbose=True):
    ''' Positive numbers only, but works in BOTH directions.
    For strings in infiniteBase notation set for bases <= 62
    infiniteBase=True . Examples of use:
    inumToStr( 17,  2, 1, 1)             # [1,0,0,0,1]
    inumToStr( 17,  3, 5)                #       00122
    inumToStr(245, 16, 4)                #        00F5
    inumToStr(245, 36, 4,0,1)            #        006T
    inumToStr(245245245245,36,10,0,1)    #  0034NWOQBH
    inumToStr(245245245245,62)           #     4JhA3Th
        245245245245 == int(gmpy2.mpz('4JhA3Th',62))
    inumToStr(245245245245,99,2) # [25,78, 5,23,70,44]
    ----------------------------------------------------
    inumToStr( '[1,0,0,0,1]',2, infiniteBase=True ) # 17
    inumToStr( '[25,78, 5,23,70,44]', 99) # 245245245245
    inumToStr( '0034NWOQBH', 36 )         # 245245245245
    inumToStr( '4JhA3Th'   , 62 )         # 245245245245
    ----------------------------------------------------
    --- Timings for N = 2**4096, base=36:
                                      standard: 0.0023
                                      infinite: 0.0017
                                      numpy   : 0.1277
                                      recursio; 0.0022
                                      oneliner: 0.0146
                For N = 2**8192:
                                      standard: 0.0075
                                      infinite: 0.0053
                                      numpy   : 0.1369
    max. recursion depth exceeded:    recursio/oneliner
    '''
    show = print
    if type(N) is str and ( infiniteBase is True or base > 62 ):
        lstN = eval(N)
        if verbose: show(' converting a non-standard infiniteBase bits string to Python integer')
        return sum( [ item*base**pow for pow, item in enumerate(lstN[::-1]) ] )
    if type(N) is str and base <= 36:
        if verbose: show('base <= 36. Returning Python int(N, base)')
        return int(N, base)
    if type(N) is str and base <= 62:
        if useGmpy:
            if verbose: show(' base <= 62, useGmpy=True, returning int(gmpy2.mpz(N,base))')
            return int(gmpy2.mpz(N,base))
        else:
            if verbose: show(' base <= 62, useGmpy=False, self-calculating return value)')
            lstStrOfDigits="0123456789"+ \
                "abcdefghijklmnopqrstuvwxyz".upper() + \
                "abcdefghijklmnopqrstuvwxyz"
            dictCharToPow = {}
            for index, char in enumerate(lstStrOfDigits):
                dictCharToPow.update({char : index})
            return sum( dictCharToPow[item]*base**pow for pow, item in enumerate(N[::-1]) )
        #:if
    #:if

    if useOneliner and base <= 36:
        if verbose: show(' base <= 36, useOneliner=True, running the Oneliner code')
        d="0123456789abcdefghijklmnopqrstuvwxyz"
        baseit = lambda a=N, b=base: (not a) and d[0]  or \
        baseit(a-a%b,b*base)+d[a%b%(base-1) or (a%b) and (base-1)]
        return baseit().rjust(width, d[0])[1:]

    if useRecursion and base <= 36:
        if verbose: show(' base <= 36, useRecursion=True, running recursion algorythm')
        BS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        def to_base(n, b):
            return "0" if not n else to_base(n//b, b).lstrip("0") + BS[n%b]
        return to_base(N, base).rjust(width,BS[0])

    if base > 62 or infiniteBase:
        if verbose: show(' base > 62 or infiniteBase=True, returning a non-standard digits string')
        # Allows arbitrary large base with 'width=...'
        # applied to each digit (useful also for bits )
        N, digit = divmod(N, base)
        strN = str(digit).rjust(width, ' ')+']'
        while N:
            N, digit = divmod(N, base)
            strN = str(digit).rjust(width, ' ') + ',' + strN
        return '[' + strN
    #:if

    if base == 2:
        if verbose: show(" base = 2, returning Python str(f'{N:0{width}b}')")
        return str(f'{N:0{width}b}')
    if base == 8:
        if verbose: show(" base = 8, returning Python str(f'{N:0{width}o}')")
        return str(f'{N:0{width}o}')
    if base == 16:
        if verbose: show(" base = 16, returning Python str(f'{N:0{width}X}')")
        return str(f'{N:0{width}X}')

    if base <= 36:
        if useNumpy:
            if verbose: show(" base <= 36, useNumpy=True, returning np.base_repr(N, base)")
            import numpy as np
            strN = np.base_repr(N, base)
            return strN.rjust(width, '0')
        else:
            if verbose: show(' base <= 36, useNumpy=False, self-calculating return value)')
            lstStrOfDigits="0123456789"+"abcdefghijklmnopqrstuvwxyz".upper()
            strN = lstStrOfDigits[N % base] # rightmost digit
            while N >= base:
                N //= base # consume already converted digit
                strN = lstStrOfDigits[N % base] + strN # add digits to the left
            #:while
            return strN.rjust(width, lstStrOfDigits[0])
        #:if
    #:if

    if base <= 62:
        if useGmpy:
            if verbose: show(" base <= 62, useGmpy=True, returning gmpy2.digits(N, base)")
            import gmpy2
            strN = gmpy2.digits(N, base)
            return strN.rjust(width, '0')
            # back to Python int from gmpy2.mpz with
            #     int(gmpy2.mpz('4JhA3Th',62))
        else:
            if verbose: show(' base <= 62, useGmpy=False, self-calculating return value)')
            lstStrOfDigits= "0123456789" + \
                "abcdefghijklmnopqrstuvwxyz".upper() + \
                "abcdefghijklmnopqrstuvwxyz"
            strN = lstStrOfDigits[N % base] # rightmost digit
            while N >= base:
                N //= base # consume already converted digit
                strN = lstStrOfDigits[N % base] + strN # add digits to the left
            #:while
            return strN.rjust(width, lstStrOfDigits[0])
        #:if
    #:if
#:def
</code>```

Body:
Python allows easy creation of an integer from a string of a given base via

int(str, base).

I want to perform the inverse: creation of a string from an integer,
i.e. I want some function int2base(num, base), such that:

int(int2base(x, b), b) == x

The function name/argument order is unimportant.

For any number x and base b that int() will accept.

This is an easy function to write: in fact it's easier than describing it in this question. However, I feel like I must be missing something.

I know about the functions bin, oct, hex, but I cannot use them for a few reasons:

Those functions are not available on older versions of Python, with which I need compatibility with (2.2)

I want a general solution that can be called the same way for different bases

I want to allow bases other than 2, 8, 16

Related

Python elegant inverse function of int(string, base)

Integer to base-x system using recursion in python

Base 62 conversion in Python

How to convert an integer to the shortest url-safe string in Python?

Body:
The below provided Python code converts a Python integer to a string in arbitrary base ( from 2 up to infinity ) and works in both directions. So all the created strings can be converted back to Python integers by providing a string for N instead of an integer.
The code works only on positive numbers by intention (there is in my eyes some hassle about negative values and their bit representations I don't want to dig into). Just pick from this code what you need, want or like, or just have fun learning about available options. Much is there only for the purpose of documenting all the various available approaches ( e.g. the Oneliner seems not to be fast, even if promised to be ).

I like the by Salvador Dali proposed format for infinite large bases. A nice proposal which works optically well even for simple binary bit representations. Notice that the width=x padding parameter in case of infiniteBase=True formatted string applies to the digits and not to the whole number. It seems, that code handling infiniteBase digits format runs even a bit faster than the other options - another reason for using it?

I don't like the idea of using Unicode for extending the number of symbols available for digits, so don't look in the code below for it, because it's not there. Use the proposed infiniteBase format instead or store integers as bytes for compression purposes.

    def inumToStr( N, base=2, width=1, infiniteBase=False,\
    useNumpy=False, useRecursion=False, useOneliner=False, \
    useGmpy=False, verbose=True):
    ''' Positive numbers only, but works in BOTH directions.
    For strings in infiniteBase notation set for bases <= 62
    infiniteBase=True . Examples of use:
    inumToStr( 17,  2, 1, 1)             # [1,0,0,0,1]
    inumToStr( 17,  3, 5)                #       00122
    inumToStr(245, 16, 4)                #        00F5
    inumToStr(245, 36, 4,0,1)            #        006T
    inumToStr(245245245245,36,10,0,1)    #  0034NWOQBH
    inumToStr(245245245245,62)           #     4JhA3Th
        245245245245 == int(gmpy2.mpz('4JhA3Th',62))
    inumToStr(245245245245,99,2) # [25,78, 5,23,70,44]
    ----------------------------------------------------
    inumToStr( '[1,0,0,0,1]',2, infiniteBase=True ) # 17
    inumToStr( '[25,78, 5,23,70,44]', 99) # 245245245245
    inumToStr( '0034NWOQBH', 36 )         # 245245245245
    inumToStr( '4JhA3Th'   , 62 )         # 245245245245
    ----------------------------------------------------
    --- Timings for N = 2**4096, base=36:
                                      standard: 0.0023
                                      infinite: 0.0017
                                      numpy   : 0.1277
                                      recursio; 0.0022
                                      oneliner: 0.0146
                For N = 2**8192:
                                      standard: 0.0075
                                      infinite: 0.0053
                                      numpy   : 0.1369
    max. recursion depth exceeded:    recursio/oneliner
    '''
    show = print
    if type(N) is str and ( infiniteBase is True or base > 62 ):
        lstN = eval(N)
        if verbose: show(' converting a non-standard infiniteBase bits string to Python integer')
        return sum( [ item*base**pow for pow, item in enumerate(lstN[::-1]) ] )
    if type(N) is str and base <= 36:
        if verbose: show('base <= 36. Returning Python int(N, base)')
        return int(N, base)
    if type(N) is str and base <= 62:
        if useGmpy:
            if verbose: show(' base <= 62, useGmpy=True, returning int(gmpy2.mpz(N,base))')
            return int(gmpy2.mpz(N,base))
        else:
            if verbose: show(' base <= 62, useGmpy=False, self-calculating return value)')
            lstStrOfDigits="0123456789"+ \
                "abcdefghijklmnopqrstuvwxyz".upper() + \
                "abcdefghijklmnopqrstuvwxyz"
            dictCharToPow = {}
            for index, char in enumerate(lstStrOfDigits):
                dictCharToPow.update({char : index})
            return sum( dictCharToPow[item]*base**pow for pow, item in enumerate(N[::-1]) )
        #:if
    #:if

    if useOneliner and base <= 36:
        if verbose: show(' base <= 36, useOneliner=True, running the Oneliner code')
        d="0123456789abcdefghijklmnopqrstuvwxyz"
        baseit = lambda a=N, b=base: (not a) and d[0]  or \
        baseit(a-a%b,b*base)+d[a%b%(base-1) or (a%b) and (base-1)]
        return baseit().rjust(width, d[0])[1:]

    if useRecursion and base <= 36:
        if verbose: show(' base <= 36, useRecursion=True, running recursion algorythm')
        BS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        def to_base(n, b):
            return "0" if not n else to_base(n//b, b).lstrip("0") + BS[n%b]
        return to_base(N, base).rjust(width,BS[0])

    if base > 62 or infiniteBase:
        if verbose: show(' base > 62 or infiniteBase=True, returning a non-standard digits string')
        # Allows arbitrary large base with 'width=...'
        # applied to each digit (useful also for bits )
        N, digit = divmod(N, base)
        strN = str(digit).rjust(width, ' ')+']'
        while N:
            N, digit = divmod(N, base)
            strN = str(digit).rjust(width, ' ') + ',' + strN
        return '[' + strN
    #:if

    if base == 2:
        if verbose: show(" base = 2, returning Python str(f'{N:0{width}b}')")
        return str(f'{N:0{width}b}')
    if base == 8:
        if verbose: show(" base = 8, returning Python str(f'{N:0{width}o}')")
        return str(f'{N:0{width}o}')
    if base == 16:
        if verbose: show(" base = 16, returning Python str(f'{N:0{width}X}')")
        return str(f'{N:0{width}X}')

    if base <= 36:
        if useNumpy:
            if verbose: show(" base <= 36, useNumpy=True, returning np.base_repr(N, base)")
            import numpy as np
            strN = np.base_repr(N, base)
            return strN.rjust(width, '0')
        else:
            if verbose: show(' base <= 36, useNumpy=False, self-calculating return value)')
            lstStrOfDigits="0123456789"+"abcdefghijklmnopqrstuvwxyz".upper()
            strN = lstStrOfDigits[N % base] # rightmost digit
            while N >= base:
                N //= base # consume already converted digit
                strN = lstStrOfDigits[N % base] + strN # add digits to the left
            #:while
            return strN.rjust(width, lstStrOfDigits[0])
        #:if
    #:if

    if base <= 62:
        if useGmpy:
            if verbose: show(" base <= 62, useGmpy=True, returning gmpy2.digits(N, base)")
            import gmpy2
            strN = gmpy2.digits(N, base)
            return strN.rjust(width, '0')
            # back to Python int from gmpy2.mpz with
            #     int(gmpy2.mpz('4JhA3Th',62))
        else:
            if verbose: show(' base <= 62, useGmpy=False, self-calculating return value)')
            lstStrOfDigits= "0123456789" + \
                "abcdefghijklmnopqrstuvwxyz".upper() + \
                "abcdefghijklmnopqrstuvwxyz"
            strN = lstStrOfDigits[N % base] # rightmost digit
            while N >= base:
                N //= base # consume already converted digit
                strN = lstStrOfDigits[N % base] + strN # add digits to the left
            #:while
            return strN.rjust(width, lstStrOfDigits[0])
        #:if
    #:if
#:def


来源: stackexchange

问:
How to make struct LazyList in SwiftUI?
I use ScrollView+LazyVStack+ForEach instead of standart List.

How to make wrapper around this?

```<code>struct ContentView: View {

    @State private var items = ["1", "2", "3"]
    var body: some View {
       LazyList(data: items) { item in

       }
    }
}
</code>```

I tried this code:

```<code>import SwiftUI

public struct LazyList<Data, ID, Content> where Data : RandomAccessCollection, ID : Hashable {

    public var data: Data
    public var content: (Data.Element) -> Content

    var body: some View {
        ScrollView {
            LazyVStack(spacing: 0) {
                ForEach(data, content: content)
            }
        }
    }
</code>```

Error:

```<code>Type of expression is ambiguous without more context
</code>```

答:
2021, SwiftUI 2

Apple lies in wwdc20-10031 when telling that List is lazy.

List IS NOT LAZY on MacOS.

(I don't know about iOS)

About the question. Your code is wrong. This must work:

```<code>public struct LazyList<Data, ID, Content> where Data : RandomAccessCollection, Data.Element: Identifiable, ID : Hashable, Content: View {

    public var data: Data
    public var content: (Data.Element) -> Content

    var body: some View {
        ScrollView {
            LazyVStack(spacing: 0) {
                ForEach(data, content: content)
            }
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to make struct LazyList in SwiftUI?

Body:
I use ScrollView+LazyVStack+ForEach instead of standart List.

How to make wrapper around this?

struct ContentView: View {

    @State private var items = ["1", "2", "3"]
    var body: some View {
       LazyList(data: items) { item in

       }
    }
}

I tried this code:

import SwiftUI

public struct LazyList<Data, ID, Content> where Data : RandomAccessCollection, ID : Hashable {

    public var data: Data
    public var content: (Data.Element) -> Content

    var body: some View {
        ScrollView {
            LazyVStack(spacing: 0) {
                ForEach(data, content: content)
            }
        }
    }

Error:

Type of expression is ambiguous without more context

Body:
2021, SwiftUI 2

Apple lies in wwdc20-10031 when telling that List is lazy.

List IS NOT LAZY on MacOS.

(I don't know about iOS)

About the question. Your code is wrong. This must work:

public struct LazyList<Data, ID, Content> where Data : RandomAccessCollection, Data.Element: Identifiable, ID : Hashable, Content: View {

    public var data: Data
    public var content: (Data.Element) -> Content

    var body: some View {
        ScrollView {
            LazyVStack(spacing: 0) {
                ForEach(data, content: content)
            }
        }
    }
}


问:
How to slow down sprite animation while maintaining 60 fps in pygame?
I'm trying to create a platformer game, and I want to maintain 60 FPS in it without having the sprite animations move really quickly. I've seen other answers on how to do so using the time module, but I don't really understand how to apply that.

Main Code:

```<code>import pygame
import os
import sys
import random
from pygame.locals import *
import spritesheet
import time

pygame.init()

clock = pygame.time.Clock()
FPS = 60
prev_time = time.time()

pygame.display.set_caption('Platformer')

BG_COLOR = (50, 50, 50)
BLACK = (0, 0, 0)

WIN_SIZE = (1920,1080)

WIN = pygame.display.set_mode(WIN_SIZE, 0, 32)

# CONFIGURING Animations

sprite_sheet_img_IDLE = pygame.image.load('Spritesheets/Outline/120x80_PNGSheets/_Idle.png')
sprite_sheet = spritesheet.SpriteSheet(sprite_sheet_img_IDLE)

IDLE_FRAMES = []
IDLE_STEPS = 9
IDLE_INDEX = 0
INDEX = 0
IDLE_ANIM_SPEED = 20

for x in range(IDLE_STEPS):
    newFRAME = sprite_sheet.get_image(x, 120, 80, 3.5, BLACK)
    IDLE_FRAMES.append(newFRAME)

while True:
    clock.tick(FPS)
    now = time.time()
    dt = now - prev_time
    prev_time = now
    WIN.fill(BG_COLOR)
    WIN.blit(IDLE_FRAMES[], (0, 0))

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    pygame.display.update()
    if IDLE_INDEX < 8:
        IDLE_INDEX += 1
    else:
        IDLE_INDEX = 0
    INDEX += 1
</code>```

Spritesheet Class:

```<code>import pygame

class SpriteSheet():
    def __init__(self, image):
        self.sheet = image

    def get_image(self, frame, width, height, scale, colour):
        image = pygame.Surface((width, height)).convert_alpha()
        image.blit(self.sheet, (0, 0), ((frame * width), 0, width, height))
        image = pygame.transform.scale(image, (width * scale, height * scale))
        image.set_colorkey(colour)

        return image
</code>```

Here is the spritesheet if anyone wants to replicate my situation:

答:
I'm 100% confident there is a better way to do it, but I would create a new variable called animation_tick and add one to it each iteration in the while loop. Only call the sprite change every n ticks to add delay between changes.

Example code with only necessary parts:

```<code>while True:
    if animation_tick == 20: #change 20 to how ever many ticks in between animation frames
        if IDLE_INDEX < 8:
            IDLE_INDEX += 1
        else:
            IDLE_INDEX = 0
        animation_tick = 0 #reset tick back to 0 after changing frame
    animation_tick += 1 #add 1 each iteration of the while loop

</code>```

It's practically just a for loop inside a while loop

Body:
I'm trying to create a platformer game, and I want to maintain 60 FPS in it without having the sprite animations move really quickly. I've seen other answers on how to do so using the time module, but I don't really understand how to apply that.

Main Code:

import pygame
import os
import sys
import random
from pygame.locals import *
import spritesheet
import time

pygame.init()

clock = pygame.time.Clock()
FPS = 60
prev_time = time.time()

pygame.display.set_caption('Platformer')

BG_COLOR = (50, 50, 50)
BLACK = (0, 0, 0)

WIN_SIZE = (1920,1080)

WIN = pygame.display.set_mode(WIN_SIZE, 0, 32)

# CONFIGURING Animations

sprite_sheet_img_IDLE = pygame.image.load('Spritesheets/Outline/120x80_PNGSheets/_Idle.png')
sprite_sheet = spritesheet.SpriteSheet(sprite_sheet_img_IDLE)

IDLE_FRAMES = []
IDLE_STEPS = 9
IDLE_INDEX = 0
INDEX = 0
IDLE_ANIM_SPEED = 20

for x in range(IDLE_STEPS):
    newFRAME = sprite_sheet.get_image(x, 120, 80, 3.5, BLACK)
    IDLE_FRAMES.append(newFRAME)

while True:
    clock.tick(FPS)
    now = time.time()
    dt = now - prev_time
    prev_time = now
    WIN.fill(BG_COLOR)
    WIN.blit(IDLE_FRAMES[], (0, 0))

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    pygame.display.update()
    if IDLE_INDEX < 8:
        IDLE_INDEX += 1
    else:
        IDLE_INDEX = 0
    INDEX += 1

Spritesheet Class:

import pygame

class SpriteSheet():
    def __init__(self, image):
        self.sheet = image

    def get_image(self, frame, width, height, scale, colour):
        image = pygame.Surface((width, height)).convert_alpha()
        image.blit(self.sheet, (0, 0), ((frame * width), 0, width, height))
        image = pygame.transform.scale(image, (width * scale, height * scale))
        image.set_colorkey(colour)

        return image

Here is the spritesheet if anyone wants to replicate my situation:

Body:
I'm 100% confident there is a better way to do it, but I would create a new variable called animation_tick and add one to it each iteration in the while loop. Only call the sprite change every n ticks to add delay between changes.

Example code with only necessary parts:

while True:
    if animation_tick == 20: #change 20 to how ever many ticks in between animation frames
        if IDLE_INDEX < 8:
            IDLE_INDEX += 1
        else:
            IDLE_INDEX = 0
        animation_tick = 0 #reset tick back to 0 after changing frame
    animation_tick += 1 #add 1 each iteration of the while loop

It's practically just a for loop inside a while loop


问:
Why do we need to create a channel.html on our server to use Facebook JS SDK?
I really don't understand why do we need to create channel.html file, as mentioned by FB docs. I also want to understand how it is used. In my logs I don't see this file being ever requested.</p>

答:
Hope this helps.

https://developers.facebook.com/docs/reference/javascript/FB.init/

From the doc:

This is an option that can help address three specific known issues. First, when auto playing audio/video is involved, the user may hear two streams of audio because the page has been loaded a second time in the background for cross domain communication. Second, if you have frame busting code, then you would see a blank page. Third, this will prevent inclusion of extra hits in your server-side logs. In these scenarios, you may provide the optional channelUrl parameter:

ContentLicense: CC BY-SA 3.0


问:
Iris.data.csv - ValueError: x and y must be the same size
I'm trying to run this code on Google colab, I got the ValueError: x and y must be the same size, I've tried multiple ways but none of them worked.</p>
```<code>from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
columns = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width','class']
df = pd.read_csv('Iris.data.csv', header=None, names=columns)
X = np.array(df.iloc[:, 0:4])
y = np.array(df['class'])
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30)

plt.scatter(X,y)
plt.show()
</code>```

答:
I think your problem might be that you haven't thought enough about what kind of scatter plot you are trying to make.  The X array contains 150 samples of 4 parameters.  The y array contains the classes of each data sample.  How were you expecting the scatter plot to look?  Remember that a scatter plot can only plot data in two dimensions, not 4!

I don't know what your 'Iris.data.csv' file contains but I used the copy of the iris data set from scikit-learn as shown in this example.

Usually, scatter plots of the Iris data set select two of the four dimensions and plot the points in these dimensions for each class using a different coloured point.

Something like this:

import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets

# Load data
iris = datasets.load_iris()
X = iris.data[:, :4]  # take the first 4 features
assert(X.shape == (150, 4))
y = iris.target
assert(y.shape == (150,))
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30)

classes = np.unique(y)
assert(classes.shape == (3, ))

# Select dimensions to plot
dim1 = X[:, 0]
dim2 = X[:, 1]

# Make a scatter plot
fig, ax = plt.subplots()
for c in classes:
    pts = (y == c)
    ax.scatter(dim1[pts], dim2[pts])

ax.grid()
plt.show()
```

Body:
I'm trying to run this code on Google colab, I got the ValueError: x and y must be the same size, I've tried multiple ways but none of them worked.

from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
columns = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width','class']
df = pd.read_csv('Iris.data.csv', header=None, names=columns)
X = np.array(df.iloc[:, 0:4])
y = np.array(df['class'])
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30)

plt.scatter(X,y)
plt.show()


问:
How do I POST JSON data with cURL?
I use Ubuntu and installed cURL on it. I want to test my Spring REST application with cURL. I wrote my POST code at the Java side. However, I want to test it with cURL. I am trying to post a JSON data. Example data is like this:

```<code>{"value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true}
</code>```

I use this command:

curl -i \
    -H "Accept: application/json" \
    -H "X-HTTP-Method-Override: PUT" \
    -X POST -d "value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true \
    http://localhost:8080/xx/xxx/xxxx
```
<p>It returns this error:</p>
<pre class="lang-none prettyprint-override"><code>HTTP/1.1 415 Unsupported Media Type
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 1051
Date: Wed, 24 Aug 2011 08:50:17 GMT
</code>```

The error description is this:

The server refused this request because the request entity is in a format not supported by the requested resource for the requested method ().

Tomcat log:
"POST /ui/webapp/conf/clear HTTP/1.1" 415 1051

What is the right format of the cURL command?

This is my Java side PUT code (I have tested GET and DELETE and they work):

```<code>@RequestMapping(method = RequestMethod.PUT)
public Configuration updateConfiguration(HttpServletResponse response, @RequestBody Configuration configuration) { //consider @Valid tag
    configuration.setName("PUT worked");
    //todo If error occurs response.sendError(HttpServletResponse.SC_NOT_FOUND);
    return configuration;
}
</code>```

答:
TL;DR:

Use the holy trinity, jo + curl + jq (or fx):

jo value=30 type="Tip 3" targetModule="Target 3" configurationGroup=null name="Configuration Deneme 3" description=null identity="Configuration Deneme 3" | \
curl --json @- \
    -X POST \
    http://localhost:8080/xx/xxx/xxxx | \
jq
```
<p>This will cover necessary headers that were missing: no need to explicitly define the <code>Content-Type</code> and <code>Accept</code> headers.</p>
<h1>The new curl way with --json</h1>
<p>Early March 2022, <code>curl</code> released a new command line parameter <code>--json</code> with version 7.82.0. This allows for a shortcut to send through JSON and eliminating the need to define the <code>Content-Type</code> <strong>that you had missing</strong> and <code>Accept</code> headers as these are automatically assumed, hence reducing risk of mistakes:</p>
<pre class="lang-none prettyprint-override"><code>curl --json '{"tool": "curl"}' https://example.com/
</code>```

But wait... there is more. Instead of defining the json parameter as a string to the curl command line, use the nifty jo CLI tool to define JSON as series of key value pairs and pipe the output through curl. Using jo only to define your JSON, it works this way:

 > jo -p value=30 type="Tip 3" targetModule="Target 3" configurationGroup=null name="Configuration Deneme 3" description=null identity="Configuration Deneme 3"
version=0 systemId=3 active=true
{
   "value": 30,
   "type": "Tip 3",
   "targetModule": "Target 3",
   "configurationGroup": null,
   "name": "Configuration Deneme 3",
   "description": null,
   "identity": "Configuration Deneme 3",
   "version": 0,
   "systemId": 3,
   "active": true
}
```
<p>Let's showcase this now with a similar <code>curl</code> command of yours but without extra headers and using <code>jo</code> + <code>jq</code> for nice output:</p>
<pre class="lang-none prettyprint-override"><code>jo value=30 type="Tip 3" targetModule="Target 3" configurationGroup=null name="Configuration Deneme 3" description=null identity="Configuration Deneme 3" | \
curl --json @- \
    -X POST \
    http://localhost:8080/xx/xxx/xxxx | \
jq
</code>```

Example with a free API

Using a free mock API for demonstration:

> jo title="Blog Post" body="lorem ipsum" userId=33 | \
curl --json @- \
    -X POST \
    https://jsonplaceholder.typicode.com/posts | \
jq
```
<p>The output has a pretty format thanks to <code>jq</code>:</p>
<pre class="lang-none prettyprint-override"><code>{
  "title": "Blog Post",
  "body": "lorem ipsum",
  "userId": 33,
  "id": 101
}
</code>```

Title: How do I POST JSON data with cURL?

Body:
I use Ubuntu and installed cURL on it. I want to test my Spring REST application with cURL. I wrote my POST code at the Java side. However, I want to test it with cURL. I am trying to post a JSON data. Example data is like this:

{"value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true}

I use this command:

curl -i \
    -H "Accept: application/json" \
    -H "X-HTTP-Method-Override: PUT" \
    -X POST -d "value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true \
    http://localhost:8080/xx/xxx/xxxx

It returns this error:

HTTP/1.1 415 Unsupported Media Type
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 1051
Date: Wed, 24 Aug 2011 08:50:17 GMT

The error description is this:

The server refused this request because the request entity is in a format not supported by the requested resource for the requested method ().

Tomcat log:
"POST /ui/webapp/conf/clear HTTP/1.1" 415 1051

What is the right format of the cURL command?

This is my Java side PUT code (I have tested GET and DELETE and they work):

@RequestMapping(method = RequestMethod.PUT)
public Configuration updateConfiguration(HttpServletResponse response, @RequestBody Configuration configuration) { //consider @Valid tag
    configuration.setName("PUT worked");
    //todo If error occurs response.sendError(HttpServletResponse.SC_NOT_FOUND);
    return configuration;
}

Body:
TL;DR:

Use the holy trinity, jo + curl + jq (or fx):

jo value=30 type="Tip 3" targetModule="Target 3" configurationGroup=null name="Configuration Deneme 3" description=null identity="Configuration Deneme 3" | \
curl --json @- \
    -X POST \
    http://localhost:8080/xx/xxx/xxxx | \
jq

This will cover necessary headers that were missing: no need to explicitly define the Content-Type and Accept headers.

The new curl way with --json

Early March 2022, curl released a new command line parameter --json with version 7.82.0. This allows for a shortcut to send through JSON and eliminating the need to define the Content-Type that you had missing and Accept headers as these are automatically assumed, hence reducing risk of mistakes:

curl --json '{"tool": "curl"}' https://example.com/

But wait... there is more. Instead of defining the json parameter as a string to the curl command line, use the nifty jo CLI tool to define JSON as series of key value pairs and pipe the output through curl. Using jo only to define your JSON, it works this way:

 > jo -p value=30 type="Tip 3" targetModule="Target 3" configurationGroup=null name="Configuration Deneme 3" description=null identity="Configuration Deneme 3"
version=0 systemId=3 active=true
{
   "value": 30,
   "type": "Tip 3",
   "targetModule": "Target 3",
   "configurationGroup": null,
   "name": "Configuration Deneme 3",
   "description": null,
   "identity": "Configuration Deneme 3",
   "version": 0,
   "systemId": 3,
   "active": true
}

Let's showcase this now with a similar curl command of yours but without extra headers and using jo + jq for nice output:

jo value=30 type="Tip 3" targetModule="Target 3" configurationGroup=null name="Configuration Deneme 3" description=null identity="Configuration Deneme 3" | \
curl --json @- \
    -X POST \
    http://localhost:8080/xx/xxx/xxxx | \
jq

Example with a free API

Using a free mock API for demonstration:

> jo title="Blog Post" body="lorem ipsum" userId=33 | \
curl --json @- \
    -X POST \
    https://jsonplaceholder.typicode.com/posts | \
jq

The output has a pretty format thanks to jq:

{
  "title": "Blog Post",
  "body": "lorem ipsum",
  "userId": 33,
  "id": 101
}


问:
I need to covernt 5'11" to CM with python code
I am working on a homework assignment that I need to take the heightfield in an attribute table and have it be converted to CM in another field. Right now I have:

```<code> with arcpy.da.SearchCursor(position + ".shp", "height") as cursor:
    for row in cursor: heightcm = row[0]
    height = heightcm.split("' ")
    feet = int(height[0])
    inches = int(height[1])
    cm = (12*feet + inches)* 2.54
    print(cm)
</code>```

I know the format of 5'11" is messing up my split, but I am unsure how to fix this. Could anyone please help me.

I am getting a ValueError: invalid literal for int() with base 10: ' 1"'

答:
To convert you could do this</p>
```<code>for row in cursor:
    heightcm = row[0]
    height = heightcm.split("'")
    feet = int(height[0])
    inches = int(height[1][:-2])
    cm = (12*feet + inches)* 2.54
    print(cm)
</code>```

Body:
I am working on a homework assignment that I need to take the heightfield in an attribute table and have it be converted to CM in another field. Right now I have:

 with arcpy.da.SearchCursor(position + ".shp", "height") as cursor:
    for row in cursor: heightcm = row[0]
    height = heightcm.split("' ")
    feet = int(height[0])
    inches = int(height[1])
    cm = (12*feet + inches)* 2.54
    print(cm)

I know the format of 5'11" is messing up my split, but I am unsure how to fix this. Could anyone please help me.

I am getting a ValueError: invalid literal for int() with base 10: ' 1"'

Body:
To convert you could do this

for row in cursor:
    heightcm = row[0]
    height = heightcm.split("'")
    feet = int(height[0])
    inches = int(height[1][:-2])
    cm = (12*feet + inches)* 2.54
    print(cm)


问:
Ionic/Angular/Firestore: Strategy for field refresh without page refresh
TL;DR  Using AngularFirestore with Ionic/Angular.  I want to synchronize data between user devices (e.g. check boxes on a form) WITHOUT causing a full page refresh for all users.

I am a happy user of Ionic/Angular for an app I use to facilitate work in a coffee shop I manage.  I have an existing checklist capability in the app as it stands.

The app is implemented using FireStore as the back end and I'm using the AngularFirestore APIs.

I have several tablets running the app in the Cafe and as people complete the tasks, they can check them off.  So far, so good.

Now what the staff is asking is that I synchronize the checklists so that if someone marks an item as complete on one tablet, all of the tablets get the update.  The obvious solution is to simply use 2-way binding and the AngularFirestore APIs.  When one user checks a box, and then tablet is always in sync because the app is subscribed to valueChanges().

But there is a problem.  When the Firestore is updated by one user, all of the other users experience a page refresh.  In their workflow, they have to re-scroll to wherever in the checklist they were working before one of their co-workers updated the FireStore database.  It's anoying.

I suspect there is a basic AngularFirestore or Ionic/Angular idea that I'm missing.  I want to update fields on a page without refreshing the whole page.

Here is a typical implmentation:

module.ts

```<code>this.notesCollection = this.afs.collection('notes', (ref) =>
  ref.orderBy('deleted').orderBy('notes').where('deleted', '!=', 'true')
);

this.notesInfo = this.notesCollection.snapshotChanges();

this.notesInfo.subscribe((notes) => {
  this.notesElements = notes.map((note) => ({
    id: note.payload.doc.id,
    ...note.payload.doc.data(),
    expanded: false,
  }));
});
</code>```

html

```<code>  <ion-list>
    <div *ngFor="let note of notesElements">
      <div *ngIf="!note.deleted">
        <ion-item>
      <ion-grid>
        <ion-row width="100%">
          <ion-col size="11">{{note.notes}}</ion-col>
          <ion-col size="1">
            <ion-buttons>
              <ion-button
                slot="end"
                (click)="expandItem($event, false, note)"
                ><div>Edit</div>
              </ion-button>
            </ion-buttons>
          </ion-col>
        </ion-row>

...
</code>```

答:
I solved this problem using a FormArray.  Here's what I did:

Define a firestore collection, Subscribe to the snapShotChanges() service.

In ngOnInit, write contents to the FormArray.

Each time the service fired, I checked to see which element changed and then I only updated the required element of the FormArray using .patchValue({tag: value})

Body:
TL;DR  Using AngularFirestore with Ionic/Angular.  I want to synchronize data between user devices (e.g. check boxes on a form) WITHOUT causing a full page refresh for all users.

I am a happy user of Ionic/Angular for an app I use to facilitate work in a coffee shop I manage.  I have an existing checklist capability in the app as it stands.

The app is implemented using FireStore as the back end and I'm using the AngularFirestore APIs.

I have several tablets running the app in the Cafe and as people complete the tasks, they can check them off.  So far, so good.

Now what the staff is asking is that I synchronize the checklists so that if someone marks an item as complete on one tablet, all of the tablets get the update.  The obvious solution is to simply use 2-way binding and the AngularFirestore APIs.  When one user checks a box, and then tablet is always in sync because the app is subscribed to valueChanges().

But there is a problem.  When the Firestore is updated by one user, all of the other users experience a page refresh.  In their workflow, they have to re-scroll to wherever in the checklist they were working before one of their co-workers updated the FireStore database.  It's anoying.

I suspect there is a basic AngularFirestore or Ionic/Angular idea that I'm missing.  I want to update fields on a page without refreshing the whole page.

Here is a typical implmentation:

module.ts

this.notesCollection = this.afs.collection('notes', (ref) =>
  ref.orderBy('deleted').orderBy('notes').where('deleted', '!=', 'true')
);

this.notesInfo = this.notesCollection.snapshotChanges();

this.notesInfo.subscribe((notes) => {
  this.notesElements = notes.map((note) => ({
    id: note.payload.doc.id,
    ...note.payload.doc.data(),
    expanded: false,
  }));
});

html

  <ion-list>

        <ion-item>
      <ion-grid>
        <ion-row width="100%">
          <ion-col size="11">{{note.notes}}</ion-col>
          <ion-col size="1">
            <ion-buttons>
              <ion-button
                slot="end"
                (click)="expandItem($event, false, note)"
                >
Edit

              </ion-button>
            </ion-buttons>
          </ion-col>
        </ion-row>

...


问:
How to check if two table include the same information in Big Query?
Assume we have a table table_a with two string and one int fields:

```<code>CREATE TABLE `YOUR_DATABASE.table_a` (
  `A1` STRING,
  `A2` INT64,
  `A3` STRING,
);
</code>```

table_a includes some data:

```<code>INSERT `YOUR_DATABASE.table_a` (A1, A2, A3)
VALUES("X111", 10, "2022-02-07 08:19:00"),
      ("Y222", 15, "2017-05-08 10:19:00"),
      ("X111", 0,"2011-08-02 02:30:00"),
      ("X111", 12, "2019-12-20 11:25:00"),
      ("Y222", 258, "2001-10-14 07:00:00"),
      ("Z333", 4, "2015-03-08 03:25:12")
</code>```

We have another table, table_b, which is kind of identical to table_a. In fact, table_b has the exact same fields and values as in table_a and it also has an extra DATETIME field. This extra DATETIME field, B4, is essentially same as A3 but converted to a standard DATETIME format.

```<code>CREATE TABLE `YOUR_DATABASE.table_b` (
  `B1` STRING,
  `B2` INT64,
  `B3` STRING,
  `B4` DATETIME,
);
</code>```

And the values in table_b are:

```<code>INSERT `YOUR_DATABASE.table_b` (B1, B2, B3, B4)
VALUES("X111", 10, "2022-02-07 08:19:00", DATETIME(PARSE_TIMESTAMP("%Y-%m-%y %H:%M:%S","2022-02-07 08:19:00"),"America/Los_Angeles")),
      ("Y222", 15, "2017-05-08 10:19:00", DATETIME(PARSE_TIMESTAMP("%Y-%m-%y %H:%M:%S","2017-05-08 10:19:00"),"America/Los_Angeles")),
      ("X111", 0, "2011-08-02 02:30:00", DATETIME(PARSE_TIMESTAMP("%Y-%m-%y %H:%M:%S","2011-08-02 02:30:00"),"America/Los_Angeles")),
      ("X111", 12, "2019-12-20 11:25:00", DATETIME(PARSE_TIMESTAMP("%Y-%m-%y %H:%M:%S","2019-12-20 11:25:00"),"America/Los_Angeles")),
      ("Y222", 258, "2001-10-14 07:00:00", DATETIME(PARSE_TIMESTAMP("%Y-%m-%y %H:%M:%S","2001-10-14 07:00:00"),"America/Los_Angeles")),
      ("Z333", 4, "2015-03-08 03:25:12", DATETIME(PARSE_TIMESTAMP("%Y-%m-%y %H:%M:%S","2015-03-08 03:25:12"),"America/Los_Angeles"))
</code>```

Note, table_a and table_b may or may not have a primary key. How can I check if table_a and table_b include the same information? I have a couple of table_a in my database and I have created equivalent table_b for each of them; now I want to double check and make sure the tables include same information.

答:
If you only want to know whether the tables contain the same data, then you can use CHECKSUM(). This basically calculates the cumulative hash for all values in the column and generates a value. If both values are the same, your tables have the same data in those columns.

SELECT
    CHECKSUM(A1), CHECKSUM(A2), CHECKSUM(A3)
FROM
    YOUR_DATABASE.table_a

SELECT
    CHECKSUM(A1), CHECKSUM(A2), CHECKSUM(A3)
FROM
    YOUR_DATABASE.table_b
```
<p>More on <code>CHECKSUM()</code> here.</p>
<p>Bear in mind that if you want to check which columns are not equal, you are better off with a <code>LEFT OUTER JOIN</code> as mentioned by @Daniel Zagales.</p>
<p><strong>Edit</strong>:
<code>CHECKSUM()</code> isn't supported in Google BigQuery, but you can use <code>FARM_FINGERPRINT()</code> instead of <code>CHECKSUM()</code> instead. So this is what your code would look like:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT
    FARM_FINGERPRINT(A1), FARM_FINGERPRINT(A2), FARM_FINGERPRINT(A3)
FROM
    YOUR_DATABASE.table_a

SELECT
    FARM_FINGERPRINT(A1), FARM_FINGERPRINT(A2), FARM_FINGERPRINT(A3)
FROM
    YOUR_DATABASE.table_b
</code>```

More info on hash functions in Google BigQuery can be found here.

Body:
Assume we have a table table_a with two string and one int fields:

CREATE TABLE `YOUR_DATABASE.table_a` (
  `A1` STRING,
  `A2` INT64,
  `A3` STRING,
);

table_a includes some data:

INSERT `YOUR_DATABASE.table_a` (A1, A2, A3)
VALUES("X111", 10, "2022-02-07 08:19:00"),
      ("Y222", 15, "2017-05-08 10:19:00"),
      ("X111", 0,"2011-08-02 02:30:00"),
      ("X111", 12, "2019-12-20 11:25:00"),
      ("Y222", 258, "2001-10-14 07:00:00"),
      ("Z333", 4, "2015-03-08 03:25:12")

We have another table, table_b, which is kind of identical to table_a. In fact, table_b has the exact same fields and values as in table_a and it also has an extra DATETIME field. This extra DATETIME field, B4, is essentially same as A3 but converted to a standard DATETIME format.

CREATE TABLE `YOUR_DATABASE.table_b` (
  `B1` STRING,
  `B2` INT64,
  `B3` STRING,
  `B4` DATETIME,
);

And the values in table_b are:

INSERT `YOUR_DATABASE.table_b` (B1, B2, B3, B4)
VALUES("X111", 10, "2022-02-07 08:19:00", DATETIME(PARSE_TIMESTAMP("%Y-%m-%y %H:%M:%S","2022-02-07 08:19:00"),"America/Los_Angeles")),
      ("Y222", 15, "2017-05-08 10:19:00", DATETIME(PARSE_TIMESTAMP("%Y-%m-%y %H:%M:%S","2017-05-08 10:19:00"),"America/Los_Angeles")),
      ("X111", 0, "2011-08-02 02:30:00", DATETIME(PARSE_TIMESTAMP("%Y-%m-%y %H:%M:%S","2011-08-02 02:30:00"),"America/Los_Angeles")),
      ("X111", 12, "2019-12-20 11:25:00", DATETIME(PARSE_TIMESTAMP("%Y-%m-%y %H:%M:%S","2019-12-20 11:25:00"),"America/Los_Angeles")),
      ("Y222", 258, "2001-10-14 07:00:00", DATETIME(PARSE_TIMESTAMP("%Y-%m-%y %H:%M:%S","2001-10-14 07:00:00"),"America/Los_Angeles")),
      ("Z333", 4, "2015-03-08 03:25:12", DATETIME(PARSE_TIMESTAMP("%Y-%m-%y %H:%M:%S","2015-03-08 03:25:12"),"America/Los_Angeles"))

Note, table_a and table_b may or may not have a primary key. How can I check if table_a and table_b include the same information? I have a couple of table_a in my database and I have created equivalent table_b for each of them; now I want to double check and make sure the tables include same information.

Body:
If you only want to know whether the tables contain the same data, then you can use CHECKSUM(). This basically calculates the cumulative hash for all values in the column and generates a value. If both values are the same, your tables have the same data in those columns.

SELECT
    CHECKSUM(A1), CHECKSUM(A2), CHECKSUM(A3)
FROM
    YOUR_DATABASE.table_a

SELECT
    CHECKSUM(A1), CHECKSUM(A2), CHECKSUM(A3)
FROM
    YOUR_DATABASE.table_b

More on CHECKSUM() here.

Bear in mind that if you want to check which columns are not equal, you are better off with a LEFT OUTER JOIN as mentioned by @Daniel Zagales.

Edit:
CHECKSUM() isn't supported in Google BigQuery, but you can use FARM_FINGERPRINT() instead of CHECKSUM() instead. So this is what your code would look like:

SELECT
    FARM_FINGERPRINT(A1), FARM_FINGERPRINT(A2), FARM_FINGERPRINT(A3)
FROM
    YOUR_DATABASE.table_a

SELECT
    FARM_FINGERPRINT(A1), FARM_FINGERPRINT(A2), FARM_FINGERPRINT(A3)
FROM
    YOUR_DATABASE.table_b

More info on hash functions in Google BigQuery can be found here.


问:
Difference between [[NSDate date] retain] and [[NSDate alloc] init]
As both of the following serves the same purpose,

```<code>today = [[NSDate date] retain];
</code>```

and

```<code>today = [[NSDate alloc] init];
</code>```

Then what's the difference between them?

Does anything here is related to memory allocation methods or something else is the reason for using them accordingly.

答:
There is essentially no difference, except that the former puts the object in the autorelease pool unnecessarily.

If I want to retain the object after creating it, and an -init style method is available for the class, I almost always choose that over the convenience constructor plus -retain.

Body:
As both of the following serves the same purpose,

today = [[NSDate date] retain];

and

today = [[NSDate alloc] init];

Then what's the difference between them?

Does anything here is related to memory allocation methods or something else is the reason for using them accordingly.


问:
How to set a NavLink as active using react-router-dom
I am using react-router-dom, and I need to make red a link when the url match, in my up I have two urls / => home and /map.

With the current code, I am able to route to different page but the NavLink is not being highlighted when the url is changed in the browser. Any ideas how to fix it.

```<code>import React from 'react'
import { NavLink, Route } from 'react-router-dom'

const Navigation = ({ onClick, id, title, tooltip, url }) => {
  return (
    <div onClick={onClick} alt={tooltip}>
      { <Route path={url} exact children={({ match }) => (

        <div style={match ? {color: 'red'} : {}}>
          {match ? '> ' : ''}<NavLink to={url}>{title}</NavLink>
        </div>
  )} />}
    </div >
  )
}

export default Navigation

const Root = ({ store }) => (
      <Provider store={store}>
        <Router>
          <Switch>
            <Route exact path='/' component={Forecast} />
            <Route exact path='/map' component={Map} />
          </Switch>
        </Router>
      </Provider>
    )
</code>```

答:
This works for this common errors:

'isActive' is not defined  no-undef

activeClassName is not working in NavLink

In React Router v6, activeClassName will be removed and you should use the function className to apply classnames to either active or inactive NavLink components.

Reference is here.

Use normally the imports like:

```<code>import { NavLink, Route } from 'react-router-dom'
</code>```

and in NavLinks use:

```<code><NavLink
  to="/text"
  className={({ isActive }) => (isActive ? 'active' : 'inactive')}
>
  Text
</NavLink>
</code>```

Body:
I am using react-router-dom, and I need to make red a link when the url match, in my up I have two urls / => home and /map.

With the current code, I am able to route to different page but the NavLink is not being highlighted when the url is changed in the browser. Any ideas how to fix it.

import React from 'react'
import { NavLink, Route } from 'react-router-dom'

const Navigation = ({ onClick, id, title, tooltip, url }) => {
  return (

      { <Route path={url} exact children={({ match }) => (

          {match ? '> ' : ''}<NavLink to={url}>{title}</NavLink>

  )} />}

  )
}

export default Navigation

const Root = ({ store }) => (
      <Provider store={store}>
        <Router>
          <Switch>
            <Route exact path='/' component={Forecast} />
            <Route exact path='/map' component={Map} />
          </Switch>
        </Router>
      </Provider>
    )

Body:
This works for this common errors:

'isActive' is not defined  no-undef

activeClassName is not working in NavLink

In React Router v6, activeClassName will be removed and you should use the function className to apply classnames to either active or inactive NavLink components.

Reference is here.

Use normally the imports like:

import { NavLink, Route } from 'react-router-dom'

and in NavLinks use:

<NavLink
  to="/text"
  className={({ isActive }) => (isActive ? 'active' : 'inactive')}
>
  Text
</NavLink>


问:
Using xarray interp to reproject a dataarray?
I have looked a lot at the xarray documentation of the interp function and I cannot really make sense of it. I see it is a reprojection but it doesn't really fit a real case example.
Is their someone that could make sense of it for example by reprojecting this dataset on a webmercator datum?

Something like the example:

import xarray as xr
from pyproj import Transformer

ds = xr.tutorial.open_dataset("air_temperature").isel(time=0)
fig, axes = plt.subplots(ncols=2, figsize=(10, 4))
lon, lat = np.meshgrid(ds.lon, ds.lat)
shp = lon.shape
# reproject the grid
gcs_to_3857 = Transformer.from_crs(4326, 3857, always_xy=True)
x, y = gcs_to_3857.transform(lon.ravel(), lat.ravel())
# future index for a regular raster
X= np.linspace(x.min(), x.max(), shp[1])
Y= np.linspace(y.min(), y.max(), shp[0])
data["x"] = xr.DataArray(np.reshape(x, shp), dims=("lat", "lon"))
data["y"] = xr.DataArray(np.reshape(y, shp), dims=("lat", "lon"))

```

And here, I am stuck

Should be something like ds.interp(x=X,y=Y) but the array is indexed on lat lon

It is all a bit confusing to me...

答:
I think the idea is something like this:

In [1]: import xarray as xr
   ...: import numpy as np
   ...: from pyproj import Transformer
   ...:
   ...: ds = xr.tutorial.open_dataset("air_temperature").isel(time=0)
```
<p>design a target grid <em>in transformed space</em>:</p>
<pre class="lang-py prettyprint-override"><code>In [2]: # find the new bounds in mercator space
   ...: gcs_to_3857 = Transformer.from_crs(4326, 3857, always_xy=True)
   ...: x, y = gcs_to_3857.transform(
   ...:     [ds.lon.min(), ds.lon.max()],
   ...:     [ds.lat.min(), ds.lat.max()],
   ...: )

In [3]: # design a target grid for the re-projected data - can be any dims you want
   ...: X = np.linspace(x[0], x[1], 500)
   ...: Y = np.linspace(y[0], y[1], 600)
   ...: XX, YY = np.meshgrid(X, Y)
</code>```

Transform this grid back into lat/lon

In [4]: # build a reverse transformer from Mercator back to lat/lons
   ...: merc_to_latlng = Transformer.from_crs(3857, 4326, always_xy=True)
   ...: new_lons, new_lats = merc_to_latlng.transform(XX.ravel(), YY.ravel())
   ...: new_lons = new_lons.reshape(XX.shape)
   ...: new_lats = new_lats.reshape(YY.shape)
```
<p>Create new DataArrays to index the lat/lon values corresponding to the grid points on the target grid (indexed by x and y in Mercator space):</p>
<pre class="lang-py prettyprint-override"><code>In [5]: # create arrays indexed by (x, y); also convert lons back to (0, 360)
   ...: new_lons_da = xr.DataArray((new_lons % 360), dims=["y", "x"], coords=[Y, X])
   ...: new_lats_da = xr.DataArray(new_lats, dims=["y", "x"], coords=[Y, X])
</code>```

Use xarray's advanced indexing to interpolate the data to the new points while re-indexing onto the new grid

In [6]: ds_mercator = ds.interp(lon=new_lons_da, lat=new_lats_da, method="linear")
```
<p>Now the data is indexed by x and y, with points equally spaced <em>in Mercator space</em>:</p>
<pre class="lang-py prettyprint-override"><code>In [7]: ds_mercator
Out[7]:
<xarray.Dataset>
Dimensions:  (y: 600, x: 500)
Coordinates:
    time     datetime64[ns] 2013-01-01
    lon      (y, x) float64 200.0 200.3 200.5 200.8 ... 329.2 329.5 329.7 330.0
    lat      (y, x) float64 15.0 15.0 15.0 15.0 15.0 ... 75.0 75.0 75.0 75.0
  * y        (y) float64 1.689e+06 1.708e+06 1.727e+06 ... 1.291e+07 1.293e+07
  * x        (x) float64 -1.781e+07 -1.778e+07 ... -3.369e+06 -3.34e+06
Data variables:
    air      (y, x) float64 nan nan nan nan nan ... 237.3 237.6 238.0 238.3 nan
Attributes:
    Conventions:  COARDS
    title:        4x daily NMC reanalysis (1948)
    description:  Data is from NMC initialized reanalysis\n(4x/day).  These a...
    platform:     Model
    references:   http://www.esrl.noaa.gov/psd/data/gridded/data.ncep.reanaly...
</code>```

The new projection can be seen in the axes (and distortion) of the transformed (right) as compared to the original (left) datasets:

In [8]: fig, axes = plt.subplots(1, 2, figsize=(14, 5))
   ...: ds.air.plot(ax=axes[0])
   ...: ds_mercator.air.plot(ax=axes[1])
Out[8]: <matplotlib.collections.QuadMesh at 0x2b3b94be0
```

Body:
I have looked a lot at the xarray documentation of the interp function and I cannot really make sense of it. I see it is a reprojection but it doesn't really fit a real case example.
Is their someone that could make sense of it for example by reprojecting this dataset on a webmercator datum?

Something like the example:

import xarray as xr
from pyproj import Transformer

ds = xr.tutorial.open_dataset("air_temperature").isel(time=0)
fig, axes = plt.subplots(ncols=2, figsize=(10, 4))
lon, lat = np.meshgrid(ds.lon, ds.lat)
shp = lon.shape
# reproject the grid
gcs_to_3857 = Transformer.from_crs(4326, 3857, always_xy=True)
x, y = gcs_to_3857.transform(lon.ravel(), lat.ravel())
# future index for a regular raster
X= np.linspace(x.min(), x.max(), shp[1])
Y= np.linspace(y.min(), y.max(), shp[0])
data["x"] = xr.DataArray(np.reshape(x, shp), dims=("lat", "lon"))
data["y"] = xr.DataArray(np.reshape(y, shp), dims=("lat", "lon"))

And here, I am stuck

Should be something like ds.interp(x=X,y=Y) but the array is indexed on lat lon

It is all a bit confusing to me...

Body:
I think the idea is something like this:

In [1]: import xarray as xr
   ...: import numpy as np
   ...: from pyproj import Transformer
   ...:
   ...: ds = xr.tutorial.open_dataset("air_temperature").isel(time=0)

design a target grid in transformed space:

In [2]: # find the new bounds in mercator space
   ...: gcs_to_3857 = Transformer.from_crs(4326, 3857, always_xy=True)
   ...: x, y = gcs_to_3857.transform(
   ...:     [ds.lon.min(), ds.lon.max()],
   ...:     [ds.lat.min(), ds.lat.max()],
   ...: )

In [3]: # design a target grid for the re-projected data - can be any dims you want
   ...: X = np.linspace(x[0], x[1], 500)
   ...: Y = np.linspace(y[0], y[1], 600)
   ...: XX, YY = np.meshgrid(X, Y)

Transform this grid back into lat/lon

In [4]: # build a reverse transformer from Mercator back to lat/lons
   ...: merc_to_latlng = Transformer.from_crs(3857, 4326, always_xy=True)
   ...: new_lons, new_lats = merc_to_latlng.transform(XX.ravel(), YY.ravel())
   ...: new_lons = new_lons.reshape(XX.shape)
   ...: new_lats = new_lats.reshape(YY.shape)

Create new DataArrays to index the lat/lon values corresponding to the grid points on the target grid (indexed by x and y in Mercator space):

In [5]: # create arrays indexed by (x, y); also convert lons back to (0, 360)
   ...: new_lons_da = xr.DataArray((new_lons % 360), dims=["y", "x"], coords=[Y, X])
   ...: new_lats_da = xr.DataArray(new_lats, dims=["y", "x"], coords=[Y, X])

Use xarray's advanced indexing to interpolate the data to the new points while re-indexing onto the new grid

In [6]: ds_mercator = ds.interp(lon=new_lons_da, lat=new_lats_da, method="linear")

Now the data is indexed by x and y, with points equally spaced in Mercator space:

In [7]: ds_mercator
Out[7]:
<xarray.Dataset>
Dimensions:  (y: 600, x: 500)
Coordinates:
    time     datetime64[ns] 2013-01-01
    lon      (y, x) float64 200.0 200.3 200.5 200.8 ... 329.2 329.5 329.7 330.0
    lat      (y, x) float64 15.0 15.0 15.0 15.0 15.0 ... 75.0 75.0 75.0 75.0
  * y        (y) float64 1.689e+06 1.708e+06 1.727e+06 ... 1.291e+07 1.293e+07
  * x        (x) float64 -1.781e+07 -1.778e+07 ... -3.369e+06 -3.34e+06
Data variables:
    air      (y, x) float64 nan nan nan nan nan ... 237.3 237.6 238.0 238.3 nan
Attributes:
    Conventions:  COARDS
    title:        4x daily NMC reanalysis (1948)
    description:  Data is from NMC initialized reanalysis\n(4x/day).  These a...
    platform:     Model
    references:   http://www.esrl.noaa.gov/psd/data/gridded/data.ncep.reanaly...

The new projection can be seen in the axes (and distortion) of the transformed (right) as compared to the original (left) datasets:

In [8]: fig, axes = plt.subplots(1, 2, figsize=(14, 5))
   ...: ds.air.plot(ax=axes[0])
   ...: ds_mercator.air.plot(ax=axes[1])
Out[8]: <matplotlib.collections.QuadMesh at 0x2b3b94be0


问:
Python requests WWW-Authenticate missing in headers
I'm trying to access the WWW-Authenticate header after a GET request using Python's requests library. When I do this in Postman it returns it but in Python it doesn't.

Python:

import requests
from requests.auth import HTTPBasicAuth

headers = {
    # "Python-Token": "<calculated when request is sent>",
    # "Host": "<calculated when request is sent>",
    "Accept": "application/json, */*",
    "User-Agent": "PythonRuntime/3.9.7",
    # "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36",
    "Accept-Encoding": "gzip, deflate, br",
    "Connection": "keep-alive",
    "Access-Control-Expose-Headers": "x-WWW-Authenticate",
    'x-requested-with': 'XMLHttpRequest',
    'sec-fetch-site': 'same-origin',
    'sec-fetch-mode': 'cors',
    "Authorization": "Bearer"
}
site = "https://YourSPOSiteURL/_vti_bin/client.svc/"
auth = HTTPBasicAuth('something@email.com', 'somepasswordhere')
headers = dict( requests.get(f"{site}/_vti_bin/client.svc/", auth=auth).headers )
```
<p><code>headers</code>:</p>
```{'Cache-Control': 'private, max-age=0',
 'Content-Length': '0',
 'Content-Security-Policy': "frame-ancestors 'self' teams.microsoft.com "
                            '*.teams.microsoft.com *.skype.com '
                            '*.teams.microsoft.us local.teams.office.com '
                            '*.powerapps.com *.yammer.com '
                            '*.officeapps.live.com *.office.com '
                            '*.stream.azure-test.net *.microsoftstream.com '
                            '*.dynamics.com;',
 'Date': 'Fri, 04 Feb 2022 14:53:16 GMT',
 'Expires': 'Thu, 20 Jan 2022 14:53:16 GMT',
 'Last-Modified': 'Fri, 04 Feb 2022 14:53:16 GMT',
 'MS-CV': 'xxxxxxxxxxxxx.0',
 'MicrosoftSharePointTeamServices': 'xx.x.x.xxxxx',
 'P3P': 'CP="ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR '
        'SAMo CNT COM INT NAV ONL PHY PRE PUR UNI"',
 'SPRequestGuid': '697da8340-a0d3-30123-9fc9-98c88419387426',
 'Server': 'Microsoft-IIS/10.0',
 'Strict-Transport-Security': 'max-age=31536000',
 'Vary': 'Origin',
 'X-AspNet-Version': '4.0.xxxxx',
 'X-Content-Type-Options': 'nosniff',
 'X-FRAME-OPTIONS': 'SAMEORIGIN',
 'X-MS-InvokeApp': '1; RequireReadOnly',
 'X-Powered-By': 'ASP.NET',
 'X-SharePointHealthScore': '2',
 'request-id': '697da8340-a0d3-30123-9fc9-98c88419387426'}
```

Postman:

I've tried every headers param I can find but can't seem to return the WWW-Authenticate response header which I need...any help would be much appreciated.

Edit:

Within Postman, it looks to be the Host key in the headers get request that's generating the WWW-Authenticate in the response headers. When I remove it (in Postman) I get only a handful of headers in the response headers. But how would I replicate this in Python's requests library?

This is what it says when hovering over the Host header in GET:

答:
Pass the request headers to the server:

# requests.get(f"{site}/_vti_bin/client.svc/", auth=auth)
requests.get(f"{site}/_vti_bin/client.svc/", headers=headers, auth=auth)
```

Body:
I'm trying to access the WWW-Authenticate header after a GET request using Python's requests library. When I do this in Postman it returns it but in Python it doesn't.

Python:

import requests
from requests.auth import HTTPBasicAuth

headers = {
    # "Python-Token": "<calculated when request is sent>",
    # "Host": "<calculated when request is sent>",
    "Accept": "application/json, */*",
    "User-Agent": "PythonRuntime/3.9.7",
    # "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36",
    "Accept-Encoding": "gzip, deflate, br",
    "Connection": "keep-alive",
    "Access-Control-Expose-Headers": "x-WWW-Authenticate",
    'x-requested-with': 'XMLHttpRequest',
    'sec-fetch-site': 'same-origin',
    'sec-fetch-mode': 'cors',
    "Authorization": "Bearer"
}
site = "https://YourSPOSiteURL/_vti_bin/client.svc/"
auth = HTTPBasicAuth('something@email.com', 'somepasswordhere')
headers = dict( requests.get(f"{site}/_vti_bin/client.svc/", auth=auth).headers )

headers:

{'Cache-Control': 'private, max-age=0',
 'Content-Length': '0',
 'Content-Security-Policy': "frame-ancestors 'self' teams.microsoft.com "
                            '*.teams.microsoft.com *.skype.com '
                            '*.teams.microsoft.us local.teams.office.com '
                            '*.powerapps.com *.yammer.com '
                            '*.officeapps.live.com *.office.com '
                            '*.stream.azure-test.net *.microsoftstream.com '
                            '*.dynamics.com;',
 'Date': 'Fri, 04 Feb 2022 14:53:16 GMT',
 'Expires': 'Thu, 20 Jan 2022 14:53:16 GMT',
 'Last-Modified': 'Fri, 04 Feb 2022 14:53:16 GMT',
 'MS-CV': 'xxxxxxxxxxxxx.0',
 'MicrosoftSharePointTeamServices': 'xx.x.x.xxxxx',
 'P3P': 'CP="ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR '
        'SAMo CNT COM INT NAV ONL PHY PRE PUR UNI"',
 'SPRequestGuid': '697da8340-a0d3-30123-9fc9-98c88419387426',
 'Server': 'Microsoft-IIS/10.0',
 'Strict-Transport-Security': 'max-age=31536000',
 'Vary': 'Origin',
 'X-AspNet-Version': '4.0.xxxxx',
 'X-Content-Type-Options': 'nosniff',
 'X-FRAME-OPTIONS': 'SAMEORIGIN',
 'X-MS-InvokeApp': '1; RequireReadOnly',
 'X-Powered-By': 'ASP.NET',
 'X-SharePointHealthScore': '2',
 'request-id': '697da8340-a0d3-30123-9fc9-98c88419387426'}

Postman:

I've tried every headers param I can find but can't seem to return the WWW-Authenticate response header which I need...any help would be much appreciated.

Edit:

Within Postman, it looks to be the Host key in the headers get request that's generating the WWW-Authenticate in the response headers. When I remove it (in Postman) I get only a handful of headers in the response headers. But how would I replicate this in Python's requests library?

This is what it says when hovering over the Host header in GET:


问:
Vim line numbers get garbled in tmux
Running tmux on WSL Ubuntu 20, vim line numbers occasionally get fouled up. For example, in the below screenshot, line numbering is somehow disabled at line 4, and the corresponding text is left-shifted:

答: One workaround is to issue a redraw command (e.g., CTRL-L).

Title: Vim line numbers get garbled in tmux


问:
C++ Struct Members not Updating in Funtion
Firstly, while not new to programming, I am very new to C++, so please bear with me.
I am using the Raylib library to attempt making a particle system for a game.

This consists of a struct with a few private members and public functions:

struct Particle {

Particle() {
    mPosVector = {(float)GetMouseX(), (float)GetMouseY()};
    mVelVector = {(float)GetRandomValue(15, 70)/100, (float)GetRandomValue(15, 70)/100};
    mSize = GetRandomValue(5, 15);
}

void update(double deltaTime) {
    mPosVector.x += mVelVector.x;
    mPosVector.y += mVelVector.y;
}

void draw() {
    DrawRectangleV(mPosVector, {(float)mSize, (float)mSize}, WHITE);
}

private:
    Vector2 mPosVector;
    Vector2 mVelVector;
    int mSize;
};
```
<p>The Vector2 type is defined by Raylib:</p>
<pre class="lang-cpp prettyprint-override"><code>struct Vector2 {
    float x;
    float y;
};
</code>```

In my main function I have an std::vector storing Particles. A particle gets added when the left mouse button is pressed. I loop through the Particles vector twice, once for updating position based on velocity and once for drawing. I was originally doing these both in one loop, but was still getting the problem that I will get onto, so tried it this way.
This is the current code:

std::vector<Particle> particles = {Particle()};

while (!WindowShouldClose()) {

    deltaTime = GetFrameTime();

    if (IsMouseButtonDown(0)) {
        particles.push_back(Particle());
    }

    for (Particle part : particles) {
        part.update(deltaTime);
    }

    BeginDrawing();

        ClearBackground(BLACK);

        DrawFPS(10, 10);

        DrawText((numToString<double>(deltaTime*1000).substr(0, 5) + "ms").c_str(), 10, 40, 20, WHITE);

        for (Particle part : particles) {
            part.draw();
        }

    EndDrawing();
```

So, my problem: While particles are being instantiated as expected while pressing the left mouse button and being drawn, for some reason their positions are not being updated by their velocity. I have tried printing debug information to the console, such as the velocity, and it is as expected, but for some unknown reason to me (probably just me being stupid) their positions aren't being updated.

Any help would be greatly appreciated.

答:
```<code>   for (Particle part : particles) {
        part.update(deltaTime);
    }
</code>```

this is making a copy of each entry , you need

```<code>   for (Particle &part : particles) {
        part.update(deltaTime);
    }
</code>```

to get a reference to the object in the vector to update it in place

To understand, think that the ranged for is just short hand for this

```<code>for(int i = 0; i < particles.size(); i++)
{
     // this line copies the value
     particle p = particles[i];
}
</code>```

whereas the one with & in it does

```<code>for(int i = 0; i < particles.size9); i++)
{
     // this line gets a reference to the ith entry
     particle &p = particles[i];
}
</code>```

Its nothing special to do with the ranged for loop.

Body:
Firstly, while not new to programming, I am very new to C++, so please bear with me.
I am using the Raylib library to attempt making a particle system for a game.

This consists of a struct with a few private members and public functions:

struct Particle {

Particle() {
    mPosVector = {(float)GetMouseX(), (float)GetMouseY()};
    mVelVector = {(float)GetRandomValue(15, 70)/100, (float)GetRandomValue(15, 70)/100};
    mSize = GetRandomValue(5, 15);
}

void update(double deltaTime) {
    mPosVector.x += mVelVector.x;
    mPosVector.y += mVelVector.y;
}

void draw() {
    DrawRectangleV(mPosVector, {(float)mSize, (float)mSize}, WHITE);
}

private:
    Vector2 mPosVector;
    Vector2 mVelVector;
    int mSize;
};

The Vector2 type is defined by Raylib:

struct Vector2 {
    float x;
    float y;
};

In my main function I have an std::vector storing Particles. A particle gets added when the left mouse button is pressed. I loop through the Particles vector twice, once for updating position based on velocity and once for drawing. I was originally doing these both in one loop, but was still getting the problem that I will get onto, so tried it this way.
This is the current code:

std::vector<Particle> particles = {Particle()};

while (!WindowShouldClose()) {

    deltaTime = GetFrameTime();

    if (IsMouseButtonDown(0)) {
        particles.push_back(Particle());
    }

    for (Particle part : particles) {
        part.update(deltaTime);
    }

    BeginDrawing();

        ClearBackground(BLACK);

        DrawFPS(10, 10);

        DrawText((numToString<double>(deltaTime*1000).substr(0, 5) + "ms").c_str(), 10, 40, 20, WHITE);

        for (Particle part : particles) {
            part.draw();
        }

    EndDrawing();

So, my problem: While particles are being instantiated as expected while pressing the left mouse button and being drawn, for some reason their positions are not being updated by their velocity. I have tried printing debug information to the console, such as the velocity, and it is as expected, but for some unknown reason to me (probably just me being stupid) their positions aren't being updated.

Any help would be greatly appreciated.

Body:
   for (Particle part : particles) {
        part.update(deltaTime);
    }

this is making a copy of each entry , you need

   for (Particle &part : particles) {
        part.update(deltaTime);
    }

to get a reference to the object in the vector to update it in place

To understand, think that the ranged for is just short hand for this

for(int i = 0; i < particles.size(); i++)
{
     // this line copies the value
     particle p = particles[i];
}

whereas the one with & in it does

for(int i = 0; i < particles.size9); i++)
{
     // this line gets a reference to the ith entry
     particle &p = particles[i];
}

Its nothing special to do with the ranged for loop.


问:
Plotly Sankey Diagram, problem with broken edge
I am using Sankey plot, from plotly, and for some reason I keep getting a weird shape on the edges of my graph, as seen on the image:

I expected that the green line should flow directly to from one edge to another, instead of doing this weird loop.

To reproduce the error, you can run the code below:

import plotly.graph_objects as go

fig = go.Figure(go.Sankey(
    arrangement = "snap",
    node = {
        "label": ["A", "B", "C", "D", "E", "F"],
        "x": [0, 0.1, 0.5, 0.2, 0.3, 0.5],
        "y": [0, 0.5, 0.2, 0.4, 0.2, 0.3],
        'pad':10},  # 10 Pixels
    link = {
        "source": [0, 0, 1, 2, 5, 4, 3, 5],
        "target": [5, 3, 4, 3, 0, 2, 2, 3],
        "value": [1, 2, 1, 1, 1, 1, 1, 2]}))
fig.show()
```

you should get this result:

The problem is the edge:

Does anybody know how I can fix it?

Thanks.

答:
Not a solution, unfortunately, but a more complete problem statement. The problem is not limited to graphs when node positions are specified manually.  It depends on the graph topology.

I developed the following minimal example containing five links among 4 nodes. if any of the link values below are set to 0, the problem goes away:

```<code>import plotly.graph_objects as go
nodes = {'label': ['node 0', 'node 1', 'node 2', 'node 3']}
links = {'source': [0, 1, 2, 2, 3], 'target': [3, 0, 0, 3, 2], 'value': [1, 1, 1, 1, 1]}
go.Figure(go.Sankey(node=nodes, link=links)).show()
</code>```

I opened another bug: https://github.com/plotly/plotly.py/issues/3587

Body:
I am using Sankey plot, from plotly, and for some reason I keep getting a weird shape on the edges of my graph, as seen on the image:

I expected that the green line should flow directly to from one edge to another, instead of doing this weird loop.

To reproduce the error, you can run the code below:

import plotly.graph_objects as go

fig = go.Figure(go.Sankey(
    arrangement = "snap",
    node = {
        "label": ["A", "B", "C", "D", "E", "F"],
        "x": [0, 0.1, 0.5, 0.2, 0.3, 0.5],
        "y": [0, 0.5, 0.2, 0.4, 0.2, 0.3],
        'pad':10},  # 10 Pixels
    link = {
        "source": [0, 0, 1, 2, 5, 4, 3, 5],
        "target": [5, 3, 4, 3, 0, 2, 2, 3],
        "value": [1, 2, 1, 1, 1, 1, 1, 2]}))
fig.show()

you should get this result:

The problem is the edge:

Does anybody know how I can fix it?

Thanks.

Body:
Not a solution, unfortunately, but a more complete problem statement. The problem is not limited to graphs when node positions are specified manually.  It depends on the graph topology.

I developed the following minimal example containing five links among 4 nodes. if any of the link values below are set to 0, the problem goes away:

import plotly.graph_objects as go
nodes = {'label': ['node 0', 'node 1', 'node 2', 'node 3']}
links = {'source': [0, 1, 2, 2, 3], 'target': [3, 0, 0, 3, 2], 'value': [1, 1, 1, 1, 1]}
go.Figure(go.Sankey(node=nodes, link=links)).show()

I opened another bug: https://github.com/plotly/plotly.py/issues/3587


问:
Optimize Union Find (Disjoint Set Union) implementation
I have implemented a Disjoint Set Union in C++ for a Kattis problem. However, my solution is inefficient, as I get TLA (Time Limit Exceeded) for the first hidden test case. Can anyone spot an inefficiency with my code?

I have based my implementation on this article. In particular, I set the parent of the parent of the smaller set to the parent of the bigger set (when making an union of the sets). According to the mentioned article, this should be as efficient as using the rank:

Both optimizations are equivalent in terms of time and space complexity. So in practice you can use any of them.

#include <bits/stdc++.h>

using namespace std;

typedef vector<int> vi;

class UnionFind {
private:
  vi p;
  vi size;

public:
  UnionFind(int N) {
    p.assign(N, 0);
    for (int i = 0; i != N; ++i)
      p[i] = i;
    size.assign(N, 1);
  }

  int findSet(int i) { return (p[i] == i) ? i : (p[i] = findSet(p[i])); }

  bool isSameSet(int i, int j) { return findSet(i) == findSet(j); }

  void unionSet(int i, int j) {
    int x = findSet(i);
    int y = findSet(j);
    if (x == y)
      return;
    if (size[x] < size[y])
      swap(x, y);
    p[y] = x;
    size[x] += size[y];
  }
};

int main() {
  int n;
  int q;
  cin >> n >> q;
  auto set = UnionFind(n);
  while (q--) {
    char ch;
    cin >> ch;
    int x;
    int y;
    cin >> x >> y;
    if (ch == '=') {
      set.unionSet(x, y);
    } else if (ch == '?') {
      if (set.isSameSet(x, y))
        cout << "yes" << endl;
      else
        cout << "no" << endl;
    }
  }
}
```

答:
This seems to be a Kattis-specific IO problem. Adding ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); to the start of main, and changing both occurrences of endl to '\n' causes it to pass in .2 seconds.

I'll also mention that including <bits/stdc++.h> is frowned upon here, but the only cause of your error was the IO. Your implementation of Union Find is correct and runs in the standard inverse Ackermann time bounds.


问:
Boost stack-trace not showing function names and line numbers
I was exploring the boost::stacktrace by trying a simple example to print the call stack of a recursive function.

```<code>#include "boost/stacktrace.hpp"

int factorial(int x){
    if (x < 2) {
        std::cout << boost::stacktrace::stacktrace();
        return 1;
    }
    return x * factorial(x - 1);
}

int main(int ac, char *av[]) {
    std::cout << factorial(4);
}
</code>```

However the output of the code does not include any information about the function name and line number:

```<code> 0# 0x000055A6F6B57C0F in /home/user/myapp
 1# 0x000055A6F6B57C42 in /home/user/myapp
 2# 0x000055A6F6B57C42 in /home/user/myapp
 3# 0x000055A6F6B57C42 in /home/user/myapp
 4# 0x000055A6F6B57C9D in /home/user/myapp
 5# __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6
 6# 0x000055A6F6B57AEA in /home/user/myapp
</code>```

This is in contrast with the sample output from the boost website:
(copied from https://www.boost.org/doc/libs/1_68_0/doc/html/stacktrace/getting_started.html#stacktrace.getting_started.how_to_print_current_call_stack)

```<code>0# bar(int) at /path/to/source/file.cpp:70
1# bar(int) at /path/to/source/file.cpp:70
2# bar(int) at /path/to/source/file.cpp:70
3# bar(int) at /path/to/source/file.cpp:70
4# main at /path/to/main.cpp:93
5# __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6
6# _start
</code>```

Why don't I see the source line numbers and function names in the stack-trace output?

I have enabled debugging information in my project-level CMakeList.txt:

```<code>set(CMAKE_BUILD_TYPE Debug)
</code>```

I can also see the symbols are present when demangling the binary file:

```<code>nm -an myapp | c++filt | grep factorial

0000000000000f40 t _GLOBAL__sub_I__Z9factoriali
00000000000010f0 T factorial(int)
</code>```

答:
This worked for me:

```<code>g++ -g backtrace.cpp -o bb -lboost_stacktrace_backtrace -D BOOST_STACKTRACE_LINK
</code>```

-D BOOST_STACKTRACE_LINK was the missing option that solved the problem for me.

Body:
I was exploring the boost::stacktrace by trying a simple example to print the call stack of a recursive function.

#include "boost/stacktrace.hpp"

int factorial(int x){
    if (x < 2) {
        std::cout << boost::stacktrace::stacktrace();
        return 1;
    }
    return x * factorial(x - 1);
}

int main(int ac, char *av[]) {
    std::cout << factorial(4);
}

However the output of the code does not include any information about the function name and line number:

 0# 0x000055A6F6B57C0F in /home/user/myapp
 1# 0x000055A6F6B57C42 in /home/user/myapp
 2# 0x000055A6F6B57C42 in /home/user/myapp
 3# 0x000055A6F6B57C42 in /home/user/myapp
 4# 0x000055A6F6B57C9D in /home/user/myapp
 5# __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6
 6# 0x000055A6F6B57AEA in /home/user/myapp

This is in contrast with the sample output from the boost website:
(copied from https://www.boost.org/doc/libs/1_68_0/doc/html/stacktrace/getting_started.html#stacktrace.getting_started.how_to_print_current_call_stack)

0# bar(int) at /path/to/source/file.cpp:70
1# bar(int) at /path/to/source/file.cpp:70
2# bar(int) at /path/to/source/file.cpp:70
3# bar(int) at /path/to/source/file.cpp:70
4# main at /path/to/main.cpp:93
5# __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6
6# _start

Why don't I see the source line numbers and function names in the stack-trace output?

I have enabled debugging information in my project-level CMakeList.txt:

set(CMAKE_BUILD_TYPE Debug)

I can also see the symbols are present when demangling the binary file:

nm -an myapp | c++filt | grep factorial

0000000000000f40 t _GLOBAL__sub_I__Z9factoriali
00000000000010f0 T factorial(int)

Body:
This worked for me:

g++ -g backtrace.cpp -o bb -lboost_stacktrace_backtrace -D BOOST_STACKTRACE_LINK

-D BOOST_STACKTRACE_LINK was the missing option that solved the problem for me.


问:
Problems with constructor resolution order
Consider the following constructors for T:

```<code>struct T {
    T(const bool) { std::cout << "T(const bool)" << endl; }
    T(const std::string&) { std::cout << "T(const std::string&)" << endl; }
};

T t("");
</code>```

Why does T(const bool) take precedence over T(const std::string&) when constructing t?

Since the above precedence might cause confusion to users expecting T(const std::string&) to be called, what can I do to have T(const std::string&) implicitly called when passing string literals to the constructor of T. For now the only work around I have found is to add another constructor, which takes the highest precedence:

```<code>T(const char* s)
{
    std::cout << "T(const char*)" << endl;
    *this = std::string(s);
}
</code>```

Apart from the above solution, declaring explicit T(const bool) to avoid confusion does not solve the above problem: in this case, although T t = "" is now prohibited, why is the form T t("") is still allowed and does call T(const bool) ?

答:
Why does T(const bool) take precedence over T(const std::string&) when constructing t?

"" is of type char[1]; this is implicitly convertible to char const* via the array-to-pointer conversion.  A pointer is implicitly convertible to bool, with all non-null pointers becoming true and all null pointers becoming false.  These are both "built-in" standard conversions.

The char const* -> std::string conversion is a user-declared conversion:  it utilizes a converting constructor of std::string that takes a char const*.

The standard ("built-in") conversions are preferred over user-declared conversions during overload resolution, so the constructor taking bool is a better match here than the one taking std::string.

For now the only work around I have found is to add another constructor

That sounds like a reasonable solution; certainly the most straightforward solution for the simple scenario you describe.  Your use of assignment to *this is a bit clumsy, though; it would be better either to have both constructors delegate to some initialization function.

Alternatively, you could use a template with enable_if for any constructors for which you would like to disallow conversions:

```<code>template <typename U>
T(U, std::enable_if<std::is_same<U, bool>::value>::type* = 0) { }
</code>```

This constructor will only be callable with a bool argument and nothing else.  You can find enable_if and is_same in Boost, C++ TR1, or C++0x.  You could also use !is_pointer, is_integral, or some other combination of type traits to allow for some other argument types but not char const*.

Or, as another alternative, you might eschew bool altogether and use your own enumeration with enumerators corresponding to true and false for the constructor.  Whether this makes sense depends on your use case.

Declaring explicit T(const bool) to avoid does not solve the above problem...why is the form T t("") is still allowed and does call T(const bool)?

explicit only disallows implicit conversions to T.  T t(""); has no conversions to T at all; it directly initializes the object t by constructing it with the argument "" passed to whichever constructor matches best.

Body:
Consider the following constructors for T:

struct T {
    T(const bool) { std::cout << "T(const bool)" << endl; }
    T(const std::string&) { std::cout << "T(const std::string&)" << endl; }
};

T t("");

Why does T(const bool) take precedence over T(const std::string&) when constructing t?

Since the above precedence might cause confusion to users expecting T(const std::string&) to be called, what can I do to have T(const std::string&) implicitly called when passing string literals to the constructor of T. For now the only work around I have found is to add another constructor, which takes the highest precedence:

T(const char* s)
{
    std::cout << "T(const char*)" << endl;
    *this = std::string(s);
}

Apart from the above solution, declaring explicit T(const bool) to avoid confusion does not solve the above problem: in this case, although T t = "" is now prohibited, why is the form T t("") is still allowed and does call T(const bool) ?

Body:
Why does T(const bool) take precedence over T(const std::string&) when constructing t?

"" is of type char[1]; this is implicitly convertible to char const* via the array-to-pointer conversion.  A pointer is implicitly convertible to bool, with all non-null pointers becoming true and all null pointers becoming false.  These are both "built-in" standard conversions.

The char const* -> std::string conversion is a user-declared conversion:  it utilizes a converting constructor of std::string that takes a char const*.

The standard ("built-in") conversions are preferred over user-declared conversions during overload resolution, so the constructor taking bool is a better match here than the one taking std::string.

For now the only work around I have found is to add another constructor

That sounds like a reasonable solution; certainly the most straightforward solution for the simple scenario you describe.  Your use of assignment to *this is a bit clumsy, though; it would be better either to have both constructors delegate to some initialization function.

Alternatively, you could use a template with enable_if for any constructors for which you would like to disallow conversions:

template <typename U>
T(U, std::enable_if<std::is_same<U, bool>::value>::type* = 0) { }

This constructor will only be callable with a bool argument and nothing else.  You can find enable_if and is_same in Boost, C++ TR1, or C++0x.  You could also use !is_pointer, is_integral, or some other combination of type traits to allow for some other argument types but not char const*.

Or, as another alternative, you might eschew bool altogether and use your own enumeration with enumerators corresponding to true and false for the constructor.  Whether this makes sense depends on your use case.

Declaring explicit T(const bool) to avoid does not solve the above problem...why is the form T t("") is still allowed and does call T(const bool)?

explicit only disallows implicit conversions to T.  T t(""); has no conversions to T at all; it directly initializes the object t by constructing it with the argument "" passed to whichever constructor matches best.


问:
How to load an external html and it´s css files with XMLHttpRequest?
I want to load an html and it`s css files into other html with XMLHttpRequest()
The problem is that the html file is loaded but not it´s css file.

it is possible to load the file so that it looks the same as the original?

I have achieved this by loading it into a full screen iframe but would like to achieve this without the use of an iframe.

```<code>var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == XMLHttpRequest.DONE) {   // XMLHttpRequest.DONE == 4
        document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
    }
};

xmlhttp.open("GET", "myHtmlWithCss.html", true);
xmlhttp.send();
</code>```

答:
Try next

```<code><object type="text/html" data="your-file.html" width="100%" height="100%" />
</code>```

Maybe you need to assign "height: 100vh;" with extra css.

Body:
I want to load an html and it`s css files into other html with XMLHttpRequest()
The problem is that the html file is loaded but not it´s css file.

it is possible to load the file so that it looks the same as the original?

I have achieved this by loading it into a full screen iframe but would like to achieve this without the use of an iframe.

var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == XMLHttpRequest.DONE) {   // XMLHttpRequest.DONE == 4
        document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
    }
};

xmlhttp.open("GET", "myHtmlWithCss.html", true);
xmlhttp.send();

Body:
Try next

<object type="text/html" data="your-file.html" width="100%" height="100%" />

Maybe you need to assign "height: 100vh;" with extra css.