问:
Pass Reference in Class
I am totally confused. In this example which is part of my class, I have:

```<code>public:
        typedef DoubleLinkedNode<DataType> Node;
private:
            const DataType* fValue;
            Node* fNext;
            Node* fPrevious;
            DoubleLinkedNode(): fValue((const DataType*)0){
                fNext = (Node*)0;
                fPrevious = (Node*)0;
            }
</code>```

Which means fValue is a const DataType* , now I want to apply/define data type like string or int to fValue by this part:

```<code>    DoubleLinkedNode( const DataType& aValue ){

        std::cout << "  --  "  << aValue << std::endl;
    }
</code>```

I am confused , what exactly I must write there and why? How can I define aValue to my fValue ?!
(note: The std::cout << "  --  "  << aValue << std::endl; is just for test)

答:
If fValue is a pointer, it needs to point at some variable created elsewhere.  So what code is responsible for the lifetime of the pointed-at value *fValue?

If the class needs to create the value itself and fValue really needs to be a pointer, it can use new and delete:

```<code>template <typename DataType>
DoubleLinkedNode<DataType>::DoubleLinkedNode( const DataType& aValue )
  : fValue( new DataType(aValue) ), fNext(0), fPrevious(0)
{}
template <typename DataType>
DoubleLinkedNode<DataType>::~DoubleLinkedNode() {
    delete fValue;
}
</code>```

But I suspect the design might work out better if fValue were not a pointer in the first place:

```<code>private:
    const DataType fValue;

// Requires a default constructor for DataType.
template <typename DataType>
DoubleLinkedNode<DataType>::DoubleLinkedNode()
  : fValue(), fNext(0), fPrevious(0)
{}
template <typename DataType>
DoubleLinkedNode<DataType>::DoubleLinkedNode( const DataType& aValue )
  : fValue(aValue), fNext(0), fPrevious(0)
{}
</code>```

Title: Pass Reference in Class

Body:
I am totally confused. In this example which is part of my class, I have:

public:
        typedef DoubleLinkedNode<DataType> Node;
private:
            const DataType* fValue;
            Node* fNext;
            Node* fPrevious;
            DoubleLinkedNode(): fValue((const DataType*)0){
                fNext = (Node*)0;
                fPrevious = (Node*)0;
            }

Which means fValue is a const DataType* , now I want to apply/define data type like string or int to fValue by this part:

    DoubleLinkedNode( const DataType& aValue ){

        std::cout << "  --  "  << aValue << std::endl;
    }

I am confused , what exactly I must write there and why? How can I define aValue to my fValue ?!
(note: The std::cout << "  --  "  << aValue << std::endl; is just for test)

Body:
If fValue is a pointer, it needs to point at some variable created elsewhere.  So what code is responsible for the lifetime of the pointed-at value *fValue?

If the class needs to create the value itself and fValue really needs to be a pointer, it can use new and delete:

template <typename DataType>
DoubleLinkedNode<DataType>::DoubleLinkedNode( const DataType& aValue )
  : fValue( new DataType(aValue) ), fNext(0), fPrevious(0)
{}
template <typename DataType>
DoubleLinkedNode<DataType>::~DoubleLinkedNode() {
    delete fValue;
}

But I suspect the design might work out better if fValue were not a pointer in the first place:

private:
    const DataType fValue;

// Requires a default constructor for DataType.
template <typename DataType>
DoubleLinkedNode<DataType>::DoubleLinkedNode()
  : fValue(), fNext(0), fPrevious(0)
{}
template <typename DataType>
DoubleLinkedNode<DataType>::DoubleLinkedNode( const DataType& aValue )
  : fValue(aValue), fNext(0), fPrevious(0)
{}


来源: stackexchange

问:
Flutter: Unable to get error code from Firebase Authentication?
I'm trying to use Google's Firebase Authentication in my flutter application. However, when handling user's login, I cannot seem to find a "code" to differentiate the types of exceptions for me to handle.

Loginhandler.dart:

```<code>class LoginHandler {
  String signup(_username, _password) async {
    bool _valid = false;
    final prefs = await SharedPreferences.getInstance();
    FirebaseAuth.instance.createUserWithEmailAndPassword(
          email: _username, password: _password)
          .catchError((e) {
            print(e);
            print(e.message);
            print(e.code);
            print(e.details);
          });
...
</code>```

Error outputs:

```<code>W/BiChannelGoogleApi(26738): [FirebaseAuth: ] getGoogleApiForMethod() returned Gms: com.google.firebase.auth.api.internal.zzal@4e727e7
W/IInputConnectionWrapper(26738): getCursorCapsMode on inactive InputConnection
I/flutter (26738): PlatformException(exception, The email address is already in use by another account., null)
I/flutter (26738): The email address is already in use by another account.
I/flutter (26738): exception
I/flutter (26738): null

I/flutter (26738): PlatformException(exception, The given password is invalid. [ Password should be at least 6 characters ], null)
I/flutter (26738): The given password is invalid. [ Password should be at least 6 characters ]
I/flutter (26738): exception
I/flutter (26738): null
</code>```

I have followed this Stack Overflow thread which highlights I can use a switch statement, but the above error output have no error "codes" for me to work with.

答:
I'm able to access the "code" property of the error on Android.</p>

```<code>      try {
          // login logic
      } catch (e) {
        print('Error: $e');
        setState(() {
          _isLoading = false;
          if (_isIos) {
            _errorMessage = e.details;
          } else
            _errorMessage = e.message;
          print(e.code); // can access the code here
        });
      }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to use Google's Firebase Authentication in my flutter application. However, when handling user's login, I cannot seem to find a "code" to differentiate the types of exceptions for me to handle.

Loginhandler.dart:

class LoginHandler {
  String signup(_username, _password) async {
    bool _valid = false;
    final prefs = await SharedPreferences.getInstance();
    FirebaseAuth.instance.createUserWithEmailAndPassword(
          email: _username, password: _password)
          .catchError((e) {
            print(e);
            print(e.message);
            print(e.code);
            print(e.details);
          });
...

Error outputs:

W/BiChannelGoogleApi(26738): [FirebaseAuth: ] getGoogleApiForMethod() returned Gms: com.google.firebase.auth.api.internal.zzal@4e727e7
W/IInputConnectionWrapper(26738): getCursorCapsMode on inactive InputConnection
I/flutter (26738): PlatformException(exception, The email address is already in use by another account., null)
I/flutter (26738): The email address is already in use by another account.
I/flutter (26738): exception
I/flutter (26738): null

I/flutter (26738): PlatformException(exception, The given password is invalid. [ Password should be at least 6 characters ], null)
I/flutter (26738): The given password is invalid. [ Password should be at least 6 characters ]
I/flutter (26738): exception
I/flutter (26738): null

I have followed this Stack Overflow thread which highlights I can use a switch statement, but the above error output have no error "codes" for me to work with.

Body:
I'm able to access the "code" property of the error on Android.

      try {
          // login logic
      } catch (e) {
        print('Error: $e');
        setState(() {
          _isLoading = false;
          if (_isIos) {
            _errorMessage = e.details;
          } else
            _errorMessage = e.message;
          print(e.code); // can access the code here
        });
      }


问:
Extracting Files between two dates which has been saved with dates
I have saved all the daily sales reports in a common folder. each file is named with the corresponding date. eg: 01-01-2019-Sales.csv, 02-01-2019-Sales.csv, etc. all the files are saved in the "C:\Desktop\Sales" folder path. now i want to extract &  combine all the files which are between 05-01-2019 to 04-02-2019.

I know I can extract all the files with pandas using the below code

```<code>import pandas as pd
import glob
import os

file_path = r'C:\Desktop\Sales'
all_files = glob.glob(os.path.join(file_path,'*.csv'))
df = pd.concat([pd.read_csv(f) for f in all_files], sort=False)
</code>```

But, my question is how can i extract files between 2 given specific dates using pandas/python. (using the file names which has been saved with the date) eg ; extract only the files between 05-01-2019 to 04-02-2019.

答:
I think that this piece of code will help you</p>

```<code>import datetime

d1 = datetime.date(2019,1,1)
d2 = datetime.date(2019,2,1)

d3 = datetime.date(2019,1,20)
d4 = datetime.date(2019,2,20)

print(d1<d3<d2)
# True
print(d1<d4<d2)
# False
</code>```

Body:
I have saved all the daily sales reports in a common folder. each file is named with the corresponding date. eg: 01-01-2019-Sales.csv, 02-01-2019-Sales.csv, etc. all the files are saved in the "C:\Desktop\Sales" folder path. now i want to extract &  combine all the files which are between 05-01-2019 to 04-02-2019.

I know I can extract all the files with pandas using the below code

import pandas as pd
import glob
import os

file_path = r'C:\Desktop\Sales'
all_files = glob.glob(os.path.join(file_path,'*.csv'))
df = pd.concat([pd.read_csv(f) for f in all_files], sort=False)

But, my question is how can i extract files between 2 given specific dates using pandas/python. (using the file names which has been saved with the date) eg ; extract only the files between 05-01-2019 to 04-02-2019.

Body:
I think that this piece of code will help you

import datetime

d1 = datetime.date(2019,1,1)
d2 = datetime.date(2019,2,1)

d3 = datetime.date(2019,1,20)
d4 = datetime.date(2019,2,20)

print(d1<d3<d2)
# True
print(d1<d4<d2)
# False


问:
Convert a CGImage to MTLTexture without premultiplication
I have a UIImage which I've previously created from a png file:

```<code>let strokeUIImage = UIImage(data: pngData)
</code>```

I want to convert strokeImage (which has opacity) to an MTLTexture for display in an MTKView, but doing the conversion seems to perform an unwanted premultiplication, which darkens all the semitransparent edges.

My blending settings are as follows:

```<code>pipelineDescriptor.colorAttachments[0].isBlendingEnabled = true
pipelineDescriptor.colorAttachments[0].rgbBlendOperation = .add
pipelineDescriptor.colorAttachments[0].alphaBlendOperation = .add
pipelineDescriptor.colorAttachments[0].sourceRGBBlendFactor = .one
pipelineDescriptor.colorAttachments[0].sourceAlphaBlendFactor = .one
pipelineDescriptor.colorAttachments[0].destinationRGBBlendFactor = .oneMinusSourceAlpha
pipelineDescriptor.colorAttachments[0].destinationAlphaBlendFactor = .oneMinusSourceAlpha
</code>```

I've tried two methods of conversion:

```<code>let stampTexture = try! MTKTextureLoader(device: self.device!).newTexture(cgImage: strokeUIImage.cgImage!, options: nil)
</code>```

and the more elaborate dataProvider-driven method:

```<code>let image = strokeUIImage.cgImage!
    let imageWidth = image.width
    let imageHeight = image.height
    let bytesPerPixel:Int! = 4
    let rowBytes = imageWidth * bytesPerPixel

    let texDescriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .rgba8Unorm_srgb,
                                                              width: imageWidth,
                                                              height: imageHeight,
                                                              mipmapped: false)

    guard let stampTexture = device!.makeTexture(descriptor: texDescriptor) else { return }

    let srcData: CFData! = image.dataProvider?.data
    let pixelData = CFDataGetBytePtr(srcData)

    let region = MTLRegionMake2D(0, 0, imageWidth, imageHeight)
    stampTexture.replace(region: region, mipmapLevel: 0, withBytes: pixelData!, bytesPerRow: Int(rowBytes))
</code>```

both of which yield the same unwanted premultiplied result.

The latter I tried, as there were some posts suggesting that the old swift3 method CGDataProviderCopyData() extracts raw pixel data from the image which is not premultiplied.  Sadly, the equivalent:

```<code>let srcData: CFData! = image.dataProvider?.data
</code>```

does not seem to do the trick. Am I missing something?

Any pointers would be appreciated.

答:
After much experimenting, I've come to a solution which addresses the pre-multiplication issue inherent in CoreGraphics images.  Thanks to Warren's tip regarding using an Accelerate function (vImageUnpremultiplyData_ARGB8888 in particular), I thought, why not build a CGImage using vImage_CGImageFormat which will allow me to play with the bitmapInfo setting that specifies how to interpret alpha...The result is not perfect, as demonstrated by the image attachment below:

Somehow, in the translation the alpha values are getting punched up slightly, (possibly the rgb as well, but not significantly).  By the way, I should point out that the png pixel format is sRGB, and the MTKView I'm using is set to MTLPixelFormat.rgba16Float (app requirement)

Below is the full metalDrawStrokeUIImage routine I implemented. Of particular note is the line:

```<code>bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.last.rawValue)
</code>```

which essentially unassociates the alpha (I think) without calling vImageUnpremultiplyData_ARGB8888.  Looking at the resulting image certainly looks like an un-premultiplied image...

Lastly, to get back a premultiplied texture on the MTKView side, I let the fragment shader handle the pre-multiplication:

```<code>fragment float4 premult_fragment(VertexOut interpolated [[stage_in]],
                                 texture2d<float> texture [[texture(0)]],
                                 sampler sampler2D [[sampler(0)]]) {
  float4 sampled = texture.sample(sampler2D, interpolated.texCoord);

  // this fragment shader premultiplies incoming rgb with texture's alpha

  return float4(sampled.r * sampled.a,
                sampled.g * sampled.a,
                sampled.b * sampled.a,
                sampled.a );

} // end of premult_fragment
</code>```

The result is pretty close to the input source, but the image is maybe 5% more opaque than the incoming png.  Again, png pixel format is sRGB, and the MTKView I'm using to display is set to MTLPixelFormat.rgba16Float .  So, I'm sure something is getting mushed somewhere.  If anyone has any pointers, I'd sure appreciate it.

Below is the rest of the relevant code:

```<code>func metalDrawStrokeUIImage (strokeUIImage: UIImage, strokeBbox: CGRect) {

self.metalSetupRenderPipeline(compStyle: compMode.strokeCopy) // needed so stampTexture is not modified by fragmentFunction

let bytesPerPixel = 4
let bitsPerComponent = 8

let width = Int(strokeUIImage.size.width)
let height = Int(strokeUIImage.size.height)

let rowBytes = width * bytesPerPixel
//
let texDescriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .rgba8Unorm_srgb,
                                                             width: width,
                                                             height: height,
                                                             mipmapped: false)
guard let stampTexture = device!.makeTexture(descriptor: texDescriptor) else { return }

//let cgImage: CGImage = strokeUIImage.cgImage!
//let sourceColorSpace = cgImage.colorSpace else {
guard
  let cgImage = strokeUIImage.cgImage,
  let sourceColorSpace = cgImage.colorSpace else {
    print("Unable to initialize cgImage or colorSpace.")
    return
}

var format = vImage_CGImageFormat(
  bitsPerComponent: UInt32(cgImage.bitsPerComponent),
  bitsPerPixel: UInt32(cgImage.bitsPerPixel),
  colorSpace: Unmanaged.passRetained(sourceColorSpace),
  bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.last.rawValue),
  version: 0, decode: nil,
  renderingIntent: CGColorRenderingIntent.defaultIntent)
var sourceBuffer = vImage_Buffer()

defer {
  free(sourceBuffer.data)
}

var error = vImageBuffer_InitWithCGImage(&sourceBuffer, &format, nil, cgImage, numericCast(kvImageNoFlags))

guard error == kvImageNoError else {
  print ("[MetalBrushStrokeView]: can't vImageBuffer_InitWithCGImage")
  return

}

//vImagePremultiplyData_RGBA8888(&sourceBuffer, &sourceBuffer, numericCast(kvImageNoFlags))

// create a CGImage from vImage_Buffer
var destCGImage = vImageCreateCGImageFromBuffer(&sourceBuffer, &format, nil, nil, numericCast(kvImageNoFlags), &error)?.takeRetainedValue()

guard error == kvImageNoError else {
  print ("[MetalBrushStrokeView]: can't vImageCreateCGImageFromBuffer")
  return
}

let dstData: CFData = (destCGImage!.dataProvider!.data)!
let pixelData = CFDataGetBytePtr(dstData)

destCGImage = nil

let region = MTLRegionMake2D(0, 0, Int(width), Int(height))
stampTexture.replace(region: region, mipmapLevel: 0, withBytes: pixelData!, bytesPerRow: Int(rowBytes))
let stampColor = UIColor.white
let stampCorners = self.stampSetVerticesFromBbox(bbox: strokeBbox)
self.stampAppendToVertexBuffer(stampLayer: stampLayerMode.stampLayerFG, stampCorners: stampCorners, stampColor: stampColor)
self.metalRenderStampSingle(stampTexture: stampTexture)
self.initializeStampArray() // clears out the stamp array so we always draw 1 stamp at a time

} // end of func metalDrawStrokeUIImage (strokeUIImage: UIImage, strokeBbox: CGRect)
</code>```

Body:
I have a UIImage which I've previously created from a png file:

let strokeUIImage = UIImage(data: pngData)

I want to convert strokeImage (which has opacity) to an MTLTexture for display in an MTKView, but doing the conversion seems to perform an unwanted premultiplication, which darkens all the semitransparent edges.

My blending settings are as follows:

pipelineDescriptor.colorAttachments[0].isBlendingEnabled = true
pipelineDescriptor.colorAttachments[0].rgbBlendOperation = .add
pipelineDescriptor.colorAttachments[0].alphaBlendOperation = .add
pipelineDescriptor.colorAttachments[0].sourceRGBBlendFactor = .one
pipelineDescriptor.colorAttachments[0].sourceAlphaBlendFactor = .one
pipelineDescriptor.colorAttachments[0].destinationRGBBlendFactor = .oneMinusSourceAlpha
pipelineDescriptor.colorAttachments[0].destinationAlphaBlendFactor = .oneMinusSourceAlpha

I've tried two methods of conversion:

let stampTexture = try! MTKTextureLoader(device: self.device!).newTexture(cgImage: strokeUIImage.cgImage!, options: nil)

and the more elaborate dataProvider-driven method:

let image = strokeUIImage.cgImage!
    let imageWidth = image.width
    let imageHeight = image.height
    let bytesPerPixel:Int! = 4
    let rowBytes = imageWidth * bytesPerPixel

    let texDescriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .rgba8Unorm_srgb,
                                                              width: imageWidth,
                                                              height: imageHeight,
                                                              mipmapped: false)

    guard let stampTexture = device!.makeTexture(descriptor: texDescriptor) else { return }

    let srcData: CFData! = image.dataProvider?.data
    let pixelData = CFDataGetBytePtr(srcData)

    let region = MTLRegionMake2D(0, 0, imageWidth, imageHeight)
    stampTexture.replace(region: region, mipmapLevel: 0, withBytes: pixelData!, bytesPerRow: Int(rowBytes))

both of which yield the same unwanted premultiplied result.

The latter I tried, as there were some posts suggesting that the old swift3 method CGDataProviderCopyData() extracts raw pixel data from the image which is not premultiplied.  Sadly, the equivalent:

let srcData: CFData! = image.dataProvider?.data

does not seem to do the trick. Am I missing something?

Any pointers would be appreciated.

Body:
After much experimenting, I've come to a solution which addresses the pre-multiplication issue inherent in CoreGraphics images.  Thanks to Warren's tip regarding using an Accelerate function (vImageUnpremultiplyData_ARGB8888 in particular), I thought, why not build a CGImage using vImage_CGImageFormat which will allow me to play with the bitmapInfo setting that specifies how to interpret alpha...The result is not perfect, as demonstrated by the image attachment below:

Somehow, in the translation the alpha values are getting punched up slightly, (possibly the rgb as well, but not significantly).  By the way, I should point out that the png pixel format is sRGB, and the MTKView I'm using is set to MTLPixelFormat.rgba16Float (app requirement)

Below is the full metalDrawStrokeUIImage routine I implemented. Of particular note is the line:

bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.last.rawValue)

which essentially unassociates the alpha (I think) without calling vImageUnpremultiplyData_ARGB8888.  Looking at the resulting image certainly looks like an un-premultiplied image...

Lastly, to get back a premultiplied texture on the MTKView side, I let the fragment shader handle the pre-multiplication:

fragment float4 premult_fragment(VertexOut interpolated [[stage_in]],
                                 texture2d<float> texture [[texture(0)]],
                                 sampler sampler2D [[sampler(0)]]) {
  float4 sampled = texture.sample(sampler2D, interpolated.texCoord);

  // this fragment shader premultiplies incoming rgb with texture's alpha

  return float4(sampled.r * sampled.a,
                sampled.g * sampled.a,
                sampled.b * sampled.a,
                sampled.a );

} // end of premult_fragment

The result is pretty close to the input source, but the image is maybe 5% more opaque than the incoming png.  Again, png pixel format is sRGB, and the MTKView I'm using to display is set to MTLPixelFormat.rgba16Float .  So, I'm sure something is getting mushed somewhere.  If anyone has any pointers, I'd sure appreciate it.

Below is the rest of the relevant code:

func metalDrawStrokeUIImage (strokeUIImage: UIImage, strokeBbox: CGRect) {

self.metalSetupRenderPipeline(compStyle: compMode.strokeCopy) // needed so stampTexture is not modified by fragmentFunction

let bytesPerPixel = 4
let bitsPerComponent = 8

let width = Int(strokeUIImage.size.width)
let height = Int(strokeUIImage.size.height)

let rowBytes = width * bytesPerPixel
//
let texDescriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .rgba8Unorm_srgb,
                                                             width: width,
                                                             height: height,
                                                             mipmapped: false)
guard let stampTexture = device!.makeTexture(descriptor: texDescriptor) else { return }

//let cgImage: CGImage = strokeUIImage.cgImage!
//let sourceColorSpace = cgImage.colorSpace else {
guard
  let cgImage = strokeUIImage.cgImage,
  let sourceColorSpace = cgImage.colorSpace else {
    print("Unable to initialize cgImage or colorSpace.")
    return
}

var format = vImage_CGImageFormat(
  bitsPerComponent: UInt32(cgImage.bitsPerComponent),
  bitsPerPixel: UInt32(cgImage.bitsPerPixel),
  colorSpace: Unmanaged.passRetained(sourceColorSpace),
  bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.last.rawValue),
  version: 0, decode: nil,
  renderingIntent: CGColorRenderingIntent.defaultIntent)
var sourceBuffer = vImage_Buffer()

defer {
  free(sourceBuffer.data)
}

var error = vImageBuffer_InitWithCGImage(&sourceBuffer, &format, nil, cgImage, numericCast(kvImageNoFlags))

guard error == kvImageNoError else {
  print ("[MetalBrushStrokeView]: can't vImageBuffer_InitWithCGImage")
  return

}

//vImagePremultiplyData_RGBA8888(&sourceBuffer, &sourceBuffer, numericCast(kvImageNoFlags))

// create a CGImage from vImage_Buffer
var destCGImage = vImageCreateCGImageFromBuffer(&sourceBuffer, &format, nil, nil, numericCast(kvImageNoFlags), &error)?.takeRetainedValue()

guard error == kvImageNoError else {
  print ("[MetalBrushStrokeView]: can't vImageCreateCGImageFromBuffer")
  return
}

let dstData: CFData = (destCGImage!.dataProvider!.data)!
let pixelData = CFDataGetBytePtr(dstData)

destCGImage = nil

let region = MTLRegionMake2D(0, 0, Int(width), Int(height))
stampTexture.replace(region: region, mipmapLevel: 0, withBytes: pixelData!, bytesPerRow: Int(rowBytes))
let stampColor = UIColor.white
let stampCorners = self.stampSetVerticesFromBbox(bbox: strokeBbox)
self.stampAppendToVertexBuffer(stampLayer: stampLayerMode.stampLayerFG, stampCorners: stampCorners, stampColor: stampColor)
self.metalRenderStampSingle(stampTexture: stampTexture)
self.initializeStampArray() // clears out the stamp array so we always draw 1 stamp at a time

} // end of func metalDrawStrokeUIImage (strokeUIImage: UIImage, strokeBbox: CGRect)


问:
Generically determining arity of data types
I want to calculate the "arity" of a certain class of data types. Namely data-types with a single constructor and some number of fields. E.g. data T a = T Int () String a. The "arity" will then be the number of fields. For T a this will be 4. I envisage a function with a signature something like this:

```<code>forall a . C a => Int
</code>```

for some appropriate choice of C. I know that if I have Generic a for some type a I get from :: a -> Rep a x, but note that this will require a concrete value for a and I'm interested in calculating it statically. Is this possible somehow? I've also thought about Typeable, but I don't really understand the API.

答:
To answer your question to me in the comments, here's an example of how you can find the arity of a function.

```<code>{-# LANGUAGE ScopedTypeVariables, FlexibleInstances #-}

import Data.Proxy

class Arity a where
    arityP :: Proxy a -> Int

instance {-# OVERLAPPABLE #-} Arity a where
    arityP _ = 0

instance {-# OVERLAPPING #-} Arity b => Arity (a -> b) where
    arityP f = 1 + arityP (Proxy :: Proxy b)

arity :: forall a. Arity a => a -> Int
arity _ = arityP (Proxy :: Proxy a)
</code>```

I feel like this is fairly self-explanatory if you are comfortable with the idioms involved.  This will work well for the use case you asked about, where you are trying to find the arity of a data type/constructor.

```<code>ghci> arity T
4
</code>```

Where it doesn't work is if you try to use it on a polymorphic function.

```<code>ghci> arity id
<interactive>:2:1: error:
• Overlapping instances for Arity a0 arising from a use of ‘arity’
  Matching instances:
    instance [overlappable] [safe] Arity a -- Defined at arity.hs:10:31
    instance [overlapping] [safe] Arity b => Arity (a -> b)
      -- Defined at arity.hs:13:30
</code>```

This makes sense because id potentially has multiple arities, depending on where it is instantiated

```<code>id :: Int -> Int
id :: (Int -> Int) -> Int -> Int
</code>```

Which actually increases my confidence in this approach.  Let me know how it works out.

Body:
I want to calculate the "arity" of a certain class of data types. Namely data-types with a single constructor and some number of fields. E.g. data T a = T Int () String a. The "arity" will then be the number of fields. For T a this will be 4. I envisage a function with a signature something like this:

forall a . C a => Int

for some appropriate choice of C. I know that if I have Generic a for some type a I get from :: a -> Rep a x, but note that this will require a concrete value for a and I'm interested in calculating it statically. Is this possible somehow? I've also thought about Typeable, but I don't really understand the API.

Body:
To answer your question to me in the comments, here's an example of how you can find the arity of a function.

{-# LANGUAGE ScopedTypeVariables, FlexibleInstances #-}

import Data.Proxy

class Arity a where
    arityP :: Proxy a -> Int

instance {-# OVERLAPPABLE #-} Arity a where
    arityP _ = 0

instance {-# OVERLAPPING #-} Arity b => Arity (a -> b) where
    arityP f = 1 + arityP (Proxy :: Proxy b)

arity :: forall a. Arity a => a -> Int
arity _ = arityP (Proxy :: Proxy a)

I feel like this is fairly self-explanatory if you are comfortable with the idioms involved.  This will work well for the use case you asked about, where you are trying to find the arity of a data type/constructor.

ghci> arity T
4

Where it doesn't work is if you try to use it on a polymorphic function.

ghci> arity id
<interactive>:2:1: error:
• Overlapping instances for Arity a0 arising from a use of ‘arity’
  Matching instances:
    instance [overlappable] [safe] Arity a -- Defined at arity.hs:10:31
    instance [overlapping] [safe] Arity b => Arity (a -> b)
      -- Defined at arity.hs:13:30

This makes sense because id potentially has multiple arities, depending on where it is instantiated

id :: Int -> Int
id :: (Int -> Int) -> Int -> Int

Which actually increases my confidence in this approach.  Let me know how it works out.


问:
How can I center the text in the headers for an AG-grid control?
How can I center the text in the headers for an AG-grid control? I have tried using cellstyle and cellclass in the column definition but that did not work. Thank you</p>

答: For (independent) customization of each header, you can make a custom header component: https://www.ag-grid.com/javascript-grid-header-rendering/</p>

ContentLicense: CC BY-SA 3.0


问:
How to Add in items in a column using Flexbox and Material UI
I am looking for some advice as I can't seem to get these items positioned on the modal. I am looking to get add the item counter as text and stars underneath. With the unassigned text at the bottom. I have tried many layouts. This is my code so far:

```<code> const styles = theme => ({
  root: {
    flexGrow: 1,
    overflow: 'hidden',
    padding: theme.spacing(0, 3),
  },
  paper: {
    maxWidth: 800,
    margin: `${theme.spacing(2)}px auto`,
    padding: theme.spacing(2),
  },
  textField: {
    marginLeft: theme.spacing(1),
    marginRight: theme.spacing(1),
    width: 200,
  },
    playButton: {
      display: "flex",
      flexDirection: "column",
      justifyContent: "center",
      alignItems: "center",
      "& .rating": {
        flex: 1
    },
  }
});

function Tasks(props) {
  const { classes } = props;
  return (
    <div className={classes.root}>
      <Paper className={classes.paper}>
        <Grid container spacing={2}>
          <Grid item xs={12} sm container>
            <Grid item xs container direction="column" spacing={2}>
              <Grid item xs>
              <div className="name-label">
              Name
              </div>
              <Typography variant="h6">
              Order cofee beans
              </Typography>
              <div className="form-divider"></div>
                <Typography variant="body2" color="textSecondary">
                  Process of Description
                </Typography>
              </Grid>
            </Grid>
            <Grid item classes={{ root: props.classes.playButton}}>
      <Grid item xs={3} className="playButton">
        <i class="far fa-play-circle fa-2x"></i>
      </Grid>
      <div className="workers-assigned-label">
      Workers Assigned
    </div>
    <div>
      count / total
    </div>
    <div className="rating">
      Stars go here
    </div>
    <div>
      unassigned
    </div>
    </Grid>
          </Grid>
        </Grid>
      </Paper>
    </div>
  );
}

export default withStyles(styles)(Tasks);
</code>```

I have added an image of a screenshot of the design so that it is clear what I am trying to achieve.

Image: enter image description here

答:
You're going to want something like this, where the flex: 1 is whatever you want to be stretching and taking up any extra space.

const styles = theme => ({
  playButton: {
    display: "flex",
    flexDirection: "column",
    justifyContent: "center",
    alignItems: "center",
    position: "relative",
    "& .playButton": {
      position: "absolute",
      top: "80%",
      left: "-55px",
      transform: "translateY(-50%)",
    },
    "& .rating": {
      flex: 1
    }
  }
});

const YourComponent = props => (
  {...}
  <Grid item classes={{ root: props.classes.playButton}}>
    <Grid item xs={3} className="playButton">

    </Grid>

      Workers Assigned

      count / total

      stars go here

      unassigned

  </Grid>
  {...}
);```

I suggest you checkout this resource to see what you can do with flex.

Body:
I am looking for some advice as I can't seem to get these items positioned on the modal. I am looking to get add the item counter as text and stars underneath. With the unassigned text at the bottom. I have tried many layouts. This is my code so far:

 const styles = theme => ({
  root: {
    flexGrow: 1,
    overflow: 'hidden',
    padding: theme.spacing(0, 3),
  },
  paper: {
    maxWidth: 800,
    margin: `${theme.spacing(2)}px auto`,
    padding: theme.spacing(2),
  },
  textField: {
    marginLeft: theme.spacing(1),
    marginRight: theme.spacing(1),
    width: 200,
  },
    playButton: {
      display: "flex",
      flexDirection: "column",
      justifyContent: "center",
      alignItems: "center",
      "& .rating": {
        flex: 1
    },
  }
});

function Tasks(props) {
  const { classes } = props;
  return (

      <Paper className={classes.paper}>
        <Grid container spacing={2}>
          <Grid item xs={12} sm container>
            <Grid item xs container direction="column" spacing={2}>
              <Grid item xs>

              Name

              <Typography variant="h6">
              Order cofee beans
              </Typography>

                <Typography variant="body2" color="textSecondary">
                  Process of Description
                </Typography>
              </Grid>
            </Grid>
            <Grid item classes={{ root: props.classes.playButton}}>
      <Grid item xs={3} className="playButton">

      </Grid>

      Workers Assigned

      count / total

      Stars go here

      unassigned

    </Grid>
          </Grid>
        </Grid>
      </Paper>

  );
}

export default withStyles(styles)(Tasks);

I have added an image of a screenshot of the design so that it is clear what I am trying to achieve.

Image: enter image description here

Body:
You're going to want something like this, where the flex: 1 is whatever you want to be stretching and taking up any extra space.

const styles = theme => ({
  playButton: {
    display: "flex",
    flexDirection: "column",
    justifyContent: "center",
    alignItems: "center",
    position: "relative",
    "& .playButton": {
      position: "absolute",
      top: "80%",
      left: "-55px",
      transform: "translateY(-50%)",
    },
    "& .rating": {
      flex: 1
    }
  }
});

const YourComponent = props => (
  {...}
  <Grid item classes={{ root: props.classes.playButton}}>
    <Grid item xs={3} className="playButton">
      <i class="far fa-play-circle fa-2x"></i>
    </Grid>
    <div className="workers-assigned-label">
      Workers Assigned
    </div>
    <div>
      count / total
    </div>
    <div className="rating">
      stars go here
    </div>
    <div>
      unassigned
    </div>
  </Grid>
  {...}
);

I suggest you checkout this resource to see what you can do with flex.


问:
How to use insertId with big query streaming insert for each rows?
How to use insertId with  Bigquery streaming insert for each row by node.js </p>

```<code>const bigquery = new BigQuery({
  projectId: projectId,
});

// Inserts data into a table
await big query
  .dataset(datasetId)
  .table(tableId)
  .insert(rows);
console.log(`Inserted ${rows.length} rows`);
</code>```

答:
The insertId is included on the InsertionRow structure, which is:

```<code>{
  "insertId": string,
  "json": {
    object
  }
}
</code>```

There is a nodejs example here, but basically:

```<code>const rows = [
{
  insertId: '1',
  json: {
    INSTNM: 'Motion Picture Institute of Michigan',
    CITY: 'Troy',
    STABBR: 'MI'
  }
},
//...
];
</code>```

As mentioned on the document Graham shared:

To help ensure data consistency, you can supply insertId for each
  inserted row. BigQuery uses the insertId property to de-duplicate your
  data on a best effort basis.

Body:
How to use insertId with  Bigquery streaming insert for each row by node.js

const bigquery = new BigQuery({
  projectId: projectId,
});

// Inserts data into a table
await big query
  .dataset(datasetId)
  .table(tableId)
  .insert(rows);
console.log(`Inserted ${rows.length} rows`);

Body:
The insertId is included on the InsertionRow structure, which is:

{
  "insertId": string,
  "json": {
    object
  }
}

There is a nodejs example here, but basically:

const rows = [
{
  insertId: '1',
  json: {
    INSTNM: 'Motion Picture Institute of Michigan',
    CITY: 'Troy',
    STABBR: 'MI'
  }
},
//...
];

As mentioned on the document Graham shared:

To help ensure data consistency, you can supply insertId for each
  inserted row. BigQuery uses the insertId property to de-duplicate your
  data on a best effort basis.


问:
Character Encoding UTF8 Issue when using mb_detect_encoding() with PHP
I am reading an rss feed http://beersandbeans.com/feed/

The feeds says it is UTF8 format, and I am using simplepie rss to import the content When i grab the content and store it in $content I perform the following:

```<code><?php
header ('Content-type: text/html; charset=utf-8');
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head><body>
<?php
echo $content;
echo $enc = mb_detect_encoding($content, "UTF-8,ISO-8859-1", true);
echo $content = mb_convert_encoding($content, "UTF-8", $enc);
echo $enc = mb_detect_encoding($content, "UTF-8,ISO-8859-1", true);
?>
</body></html>
</code>```

This then produces:

```<code>..... Camping:     2,000isk/day for 5 days) = $89 .....
ISO-8859-1
..... Camping: Â  Â           2,000isk/day for 5 days) = $89 .....
UTF-8
</code>```

Why is it outputting the Â ?

答: Try not specifying "UTF-8,ISO-8859-1" and see what encoding it gives you. It might be detecting ISO-8859-1 because it's the last one in that list, rather than the actual encoding of the string.</p>

Body:
I am reading an rss feed http://beersandbeans.com/feed/

The feeds says it is UTF8 format, and I am using simplepie rss to import the content When i grab the content and store it in $content I perform the following:

<?php
header ('Content-type: text/html; charset=utf-8');
?>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<?php
echo $content;
echo $enc = mb_detect_encoding($content, "UTF-8,ISO-8859-1", true);
echo $content = mb_convert_encoding($content, "UTF-8", $enc);
echo $enc = mb_detect_encoding($content, "UTF-8,ISO-8859-1", true);
?>

This then produces:

..... Camping:     2,000isk/day for 5 days) = $89 .....
ISO-8859-1
..... Camping: Â  Â           2,000isk/day for 5 days) = $89 .....
UTF-8

Why is it outputting the Â ?


问:
AngularJS 1.x not showing radio as checked
I am updating a form to have two sets of radio buttons that turns on or off panels.
The first says "Yes" to contact the customer or "No". If we are to contact, then present choice of which method is used, phone or email.  (Previously there was just the question to contact or not.)

While I can get the show function to work properly, I do not understand why I cannot get the radio button to show as selected. (It could be that I am fairly green to AngularJS.)

```<code>  <div class="radio styled-radio" id="callTheCustomerDiv">
    <input class="form-control" id="callTheCustomerRadio1"
           name="callTheCustomer" type="radio" value="Yes"
           ng-required="issueType=='IncidentDiv'"
           ng-model="$parent.callTheCustomer"
           ng-click="contactSelection('none')"/>
    <label for="callTheCustomerRadio1"> Yes</label> - Please indicate how the customer wants to be contacted.<br/>
    <div class="form-group" id="howToContactDiv" ng-show=state class="row fullWidth">
      <div id="contactOptions" class="form-group">
        <label for="phoneRadio">Phone</label>
        <!-- radio indicator is not working correctly -->
        <input id="phoneRadio" class="form-control" type="radio"
               ng-click="contactSelection('phone')"
               name="phoneSelect" ng-model="$parent.phoneSelect"
               value="{{$parent.phoneSelect}}" />

        <label for="emailRadio">Email</label>
        <input id="emailRadio" class="form-control" type="radio"
               ng-click="contactSelection('email')" name="emailSelect"
               ng-model="$parent.emailSelect"
               value="{{$parent.emailSelect}}" />
        <br/>    <!--     phoneSelect : {{phoneSelect}} -->
      </div>
      <div id="phoneContact" ng-show="contactType=='phone'">
        <span>Phone
          <input class="form-control input-sm" type="text"
                 name="callTheCustomerPhone"
                 id="callTheCustomerPhone"
                 ng-model="$parent.callTheCustomerPhone"
                 ng-required="$parent.contactType=='phone' && accForm.phoneNumber.$viewValue === ''"
                 maxlength="20"/>
        </span>
      </div>
</code>```

```<code>      <br/>
      <div id="emailContact" ng-show="contactType=='email'">
        <span>Email
        <input class="form-control input-sm" type="text"
               name="emailTheCustomer" id="emailTheCustomer"
               ng-model="$parent.emailTheCustomer"
               ng-required="$parent.contactType=='email' && accForm.emailTheCustomer.$viewValue === ''"
               maxlength="150"/></span>
      </div>
    </div>
    <input class="form-control" id="callTheCustomerRadio2"
           name="callTheCustomer" type="radio" value="No"
           ng-required="issueType=='IncidentDiv'"
           ng-model="$parent.callTheCustomer"
           ng-click="contactSelection('no')"/>
    <label for="callTheCustomerRadio2">No</label>

  </div>
</code>```

Looks like this when Phone is selected:

and like this when email is selected:

I added this method to the Main controller:

```<code>$scope.contactSelection = (function (contact) {
  if (contact=='none'
    ||contact=='email'
    ||contact=='phone'){
    $scope.state = true;
    $scope.contactType = contact;
    if (contact=='phone'){$scope.phoneSelect = true;$scope.emailSelect = false;}
    if (contact=='email'){$scope.emailSelect = true;$scope.phoneSelect = false;}

  }else{
    $scope.state = false;
    $scope.contactType = 'no';
    $scope.emailTheCustomer = '';
    $scope.callTheCustomerPhone = '';
    $scope.phoneSelect = false;
    $scope.emailSelect = false;
  }
});
</code>```

答:
Couple things were in play here

I had to change the label-input tag order.

```<code> <div class="radio styled-radio" id="callTheCustomerDiv">
    <input class="form-control" id="callTheCustomerRadio1" name="callTheCustomer" type="radio" value="Yes"
           ng-required="issueType=='IncidentDiv'"
           ng-model="callTheCustomer"
           ng-click="contactSelection(null)" />
    <label for="callTheCustomerRadio1"> Yes</label> - Please indicate how the customer wants to be contacted.<br/>
    <div class="form-group" id="howToContactDiv"
    ng-if="customerContact.contactOptionShow" class="row fullWidth">
      <div id="contactOptionsDiv" >
        <div id="contactOptionsSelectDiv" >
            <input  class="form-control" id="phoneRadio" type="radio" name="contactSelection"
            ng-model="customerContact.contactSelection" value="phone" />
            <label for="phoneRadio">Phone</label>

          <input  class="form-control" id="emailRadio" type="radio" name="contactSelection"
          ng-model="customerContact.contactSelection" value="email" />
          <label for="emailRadio">Email</label>
          <br/>
        </div>
        <div id="phoneContactDiv" ng-show="customerContact.contactSelection=='phone'">
          <span>Phone
          <input class="form-control input-sm" type="text" name="callTheCustomerPhone" id="callTheCustomerPhone"
                ng-model="callTheCustomerPhone"
                ng-required="customerContact.contactSelection=='phone' && accForm.phoneNumber.$viewValue === ''"
                maxlength="20"/></span>
        </div>
        <br/>
        <div id="emailContactDiv" ng-show="customerContact.contactSelection=='email'">
          <span>Email
          <input class="form-control input-sm" type="text" name="emailTheCustomer" id="emailTheCustomer"
                ng-model="emailTheCustomer"
                ng-required="customerContact.contactSelection=='email' && accForm.emailTheCustomer.$viewValue === ''" maxlength="150"/></span>
        </div>
      </div>
    </div>
    <input class="form-control" id="callTheCustomerRadio2" name="callTheCustomer" type="radio" value="No"
           ng-required="issueType=='IncidentDiv'" ng-model="callTheCustomer"
           ng-click="contactSelection('clear')" />
    <label for="callTheCustomerRadio2">No</label>
  </div>
</code>```

I completely removed the $parent references and simplified the function by using the
properties of the variable.

modified the mainController method and variable to look like:

```<code>  $scope.customerContact ={
    contactOptionShow : false,
    contactSelection : null
  };
    $scope.contactSelection = (function (contact) {
      if (contact != null
          && contact=='clear'      ){
          $scope.customerContact.contactOptionShow = false;
          $scope.customerContact.contactSelection = '';
          $scope.emailTheCustomer = '';
          $scope.callTheCustomerPhone = '';
      }else{
        $scope.customerContact.contactOptionShow = true;
      }
    });
</code>```

I think it reads better now as well.

Body:
I am updating a form to have two sets of radio buttons that turns on or off panels.
The first says "Yes" to contact the customer or "No". If we are to contact, then present choice of which method is used, phone or email.  (Previously there was just the question to contact or not.)

While I can get the show function to work properly, I do not understand why I cannot get the radio button to show as selected. (It could be that I am fairly green to AngularJS.)

    <input class="form-control" id="callTheCustomerRadio1"
           name="callTheCustomer" type="radio" value="Yes"
           ng-required="issueType=='IncidentDiv'"
           ng-model="$parent.callTheCustomer"
           ng-click="contactSelection('none')"/>
     Yes - Please indicate how the customer wants to be contacted.

        Phone

        <input id="phoneRadio" class="form-control" type="radio"
               ng-click="contactSelection('phone')"
               name="phoneSelect" ng-model="$parent.phoneSelect"
               value="{{$parent.phoneSelect}}" />

        Email
        <input id="emailRadio" class="form-control" type="radio"
               ng-click="contactSelection('email')" name="emailSelect"
               ng-model="$parent.emailSelect"
               value="{{$parent.emailSelect}}" />

        Phone
          <input class="form-control input-sm" type="text"
                 name="callTheCustomerPhone"
                 id="callTheCustomerPhone"
                 ng-model="$parent.callTheCustomerPhone"
                 ng-required="$parent.contactType=='phone' && accForm.phoneNumber.$viewValue === ''"
                 maxlength="20"/>

        Email
        <input class="form-control input-sm" type="text"
               name="emailTheCustomer" id="emailTheCustomer"
               ng-model="$parent.emailTheCustomer"
               ng-required="$parent.contactType=='email' && accForm.emailTheCustomer.$viewValue === ''"
               maxlength="150"/>

    <input class="form-control" id="callTheCustomerRadio2"
           name="callTheCustomer" type="radio" value="No"
           ng-required="issueType=='IncidentDiv'"
           ng-model="$parent.callTheCustomer"
           ng-click="contactSelection('no')"/>
    No

Looks like this when Phone is selected:

and like this when email is selected:

I added this method to the Main controller:

$scope.contactSelection = (function (contact) {
  if (contact=='none'
    ||contact=='email'
    ||contact=='phone'){
    $scope.state = true;
    $scope.contactType = contact;
    if (contact=='phone'){$scope.phoneSelect = true;$scope.emailSelect = false;}
    if (contact=='email'){$scope.emailSelect = true;$scope.phoneSelect = false;}

  }else{
    $scope.state = false;
    $scope.contactType = 'no';
    $scope.emailTheCustomer = '';
    $scope.callTheCustomerPhone = '';
    $scope.phoneSelect = false;
    $scope.emailSelect = false;
  }
});

Body:
Couple things were in play here

I had to change the label-input tag order.

 <div class="radio styled-radio" id="callTheCustomerDiv">
    <input class="form-control" id="callTheCustomerRadio1" name="callTheCustomer" type="radio" value="Yes"
           ng-required="issueType=='IncidentDiv'"
           ng-model="callTheCustomer"
           ng-click="contactSelection(null)" />
    <label for="callTheCustomerRadio1"> Yes</label> - Please indicate how the customer wants to be contacted.<br/>
    <div class="form-group" id="howToContactDiv"
    ng-if="customerContact.contactOptionShow" class="row fullWidth">
      <div id="contactOptionsDiv" >
        <div id="contactOptionsSelectDiv" >
            <input  class="form-control" id="phoneRadio" type="radio" name="contactSelection"
            ng-model="customerContact.contactSelection" value="phone" />
            <label for="phoneRadio">Phone</label>
          &nbsp; &nbsp; &nbsp; &nbsp;
          <input  class="form-control" id="emailRadio" type="radio" name="contactSelection"
          ng-model="customerContact.contactSelection" value="email" />
          <label for="emailRadio">Email</label>
          <br/>
        </div>
        <div id="phoneContactDiv" ng-show="customerContact.contactSelection=='phone'">
          <span>Phone
          <input class="form-control input-sm" type="text" name="callTheCustomerPhone" id="callTheCustomerPhone"
                ng-model="callTheCustomerPhone"
                ng-required="customerContact.contactSelection=='phone' && accForm.phoneNumber.$viewValue === ''"
                maxlength="20"/></span>
        </div>
        <br/>
        <div id="emailContactDiv" ng-show="customerContact.contactSelection=='email'">
          <span>Email
          <input class="form-control input-sm" type="text" name="emailTheCustomer" id="emailTheCustomer"
                ng-model="emailTheCustomer"
                ng-required="customerContact.contactSelection=='email' && accForm.emailTheCustomer.$viewValue === ''" maxlength="150"/></span>
        </div>
      </div>
    </div>
    <input class="form-control" id="callTheCustomerRadio2" name="callTheCustomer" type="radio" value="No"
           ng-required="issueType=='IncidentDiv'" ng-model="callTheCustomer"
           ng-click="contactSelection('clear')" />
    <label for="callTheCustomerRadio2">No</label>
  </div>

I completely removed the $parent references and simplified the function by using the
properties of the variable.

modified the mainController method and variable to look like:

  $scope.customerContact ={
    contactOptionShow : false,
    contactSelection : null
  };
    $scope.contactSelection = (function (contact) {
      if (contact != null
          && contact=='clear'      ){
          $scope.customerContact.contactOptionShow = false;
          $scope.customerContact.contactSelection = '';
          $scope.emailTheCustomer = '';
          $scope.callTheCustomerPhone = '';
      }else{
        $scope.customerContact.contactOptionShow = true;
      }
    });

I think it reads better now as well.


问:
Data structure for counting occurrences
Say I have an array

```<code>[bob, alice, jeff, bob, bob]
</code>```

I would like to transform this array into

```<code>[bob, alice, jeff, bob1, bob2]
</code>```

That is, determining occurrences.

```<code>// iterate through array
// check if element is in finalArray
     // if not add to finalArray
// if found in final array
    // add in duplicateArray
   // check instances of element in duplicateArray and add that number to element
   // insert element+updated number to finalArray
</code>```

This is my implementation of the above algorithm

```<code>     ArrayList<String> list = new ArrayList<>();
    list.add("Bob");
    list.add("Jane");
    list.add("Smith");
    list.add("Bob");
    list.add("Bob");
    list.add("Jane");
    list.add("Smithery");

    ArrayList<String> finalList = new ArrayList<>();
    ArrayList<String> tempList = new ArrayList<>();

    for(String name : list) {
        if(finalList.contains(name)) {
            int count = 0;
            tempList.add(name);
            for(int i=0; i < tempList.size(); i++) {
                if(tempList.get(i) == name) {
                    count++;
                }
            }
            String tempName = name + count;
            finalList.add(tempName);
        } else {
            finalList.add(name);
        }
    }
    for(String name: finalList) {
        System.out.println(name);
    }
</code>```

My question is although ArrayList, and other data structure have .contains method, do any data structures have methods that return the number of instances of the element in the data structure?

答:
This is my current coding implementation that does work.</p>

```<code>     ArrayList<String> list = new ArrayList<>();
    list.add("Bob");
    list.add("Jane");
    list.add("Smith");
    list.add("Bob");
    list.add("Bob");
    list.add("Jane");
    list.add("Smithery");

    ArrayList<String> finalList = new ArrayList<>();
    ArrayList<String> tempList = new ArrayList<>();

    for(String name : list) {
        if(finalList.contains(name)) {
            int count = 0;
            tempList.add(name);
            for(int i=0; i < tempList.size(); i++) {
                if(tempList.get(i) == name) {
                    count++;
                }
            }
            String tempName = name + count;
            finalList.add(tempName);
        } else {
            finalList.add(name);
        }
    }
    for(String name: finalList) {
        System.out.println(name);
    }
</code>```

Title: Data structure for counting occurrences

Body:
Say I have an array

[bob, alice, jeff, bob, bob]

I would like to transform this array into

[bob, alice, jeff, bob1, bob2]

That is, determining occurrences.

// iterate through array
// check if element is in finalArray
     // if not add to finalArray
// if found in final array
    // add in duplicateArray
   // check instances of element in duplicateArray and add that number to element
   // insert element+updated number to finalArray

This is my implementation of the above algorithm

     ArrayList<String> list = new ArrayList<>();
    list.add("Bob");
    list.add("Jane");
    list.add("Smith");
    list.add("Bob");
    list.add("Bob");
    list.add("Jane");
    list.add("Smithery");

    ArrayList<String> finalList = new ArrayList<>();
    ArrayList<String> tempList = new ArrayList<>();

    for(String name : list) {
        if(finalList.contains(name)) {
            int count = 0;
            tempList.add(name);
            for(int i=0; i < tempList.size(); i++) {
                if(tempList.get(i) == name) {
                    count++;
                }
            }
            String tempName = name + count;
            finalList.add(tempName);
        } else {
            finalList.add(name);
        }
    }
    for(String name: finalList) {
        System.out.println(name);
    }

My question is although ArrayList, and other data structure have .contains method, do any data structures have methods that return the number of instances of the element in the data structure?

Body:
This is my current coding implementation that does work.

     ArrayList<String> list = new ArrayList<>();
    list.add("Bob");
    list.add("Jane");
    list.add("Smith");
    list.add("Bob");
    list.add("Bob");
    list.add("Jane");
    list.add("Smithery");

    ArrayList<String> finalList = new ArrayList<>();
    ArrayList<String> tempList = new ArrayList<>();

    for(String name : list) {
        if(finalList.contains(name)) {
            int count = 0;
            tempList.add(name);
            for(int i=0; i < tempList.size(); i++) {
                if(tempList.get(i) == name) {
                    count++;
                }
            }
            String tempName = name + count;
            finalList.add(tempName);
        } else {
            finalList.add(name);
        }
    }
    for(String name: finalList) {
        System.out.println(name);
    }


问:
Pattern for Firebase onAuthStateChanged and Navigation Guards - Quasar app
I am facing an issue in my Quasar app with regards to browser refresh and Firebase authentication.

After a user logs in and then clicks on the browser refresh, then the firebase.auth().currentUser returns null (as this executes asynchronously). This means that when the beforeEach gets executed the currentUser is null and the user is prompted with the logon page. However I see that when the callback to onAuthStateChanged is getting invoked the user is getting set correctly.

Is there any pattern by which, in a Quasar app, the onAuthStateChanged can be used in navigation process so that existing user session is reused?

// Vue-router => index.js
firebase.auth().onAuthStateChanged(user => {
  console.log('onAuthStateChanged Invoked => ' + user);
});

router.beforeEach((to, from, next) => {
  let currentUser = firebase.auth().currentUser;
  let requiresAuth = to.matched.some(record => record.meta.requiresAuth);

  if (requiresAuth && !currentUser) {
    next('signin');
  } else {
    if (requiresAuth && currentUser.emailVerified === false) {
      next('signin');
    } else {
      next();
    }
  }
});
```

答:
I use the firebase.auth().onAuthStateChanged function directly in my router guard like this:
I check if the route needs an authenticated user (optional) and then I load the currently logged in user and commit it in my Vuex store.
This way the currently logged in user is in my Vuex state before the route guard checks access. Otherwise, especially after a page reload, the user is not yet loaded and the guard redirects to the login page...

```<code>...

Router.beforeEach((to, from, next) => {

  let requiresAuth = to.matched.some(record => record.meta.requiresAuth)

  // If route requires auth --> load auth state first from firebase
  if (requiresAuth) {

    firebase.auth().onAuthStateChanged(user => {

      store.commit("user/SET_USER", user);

      let currentUser = firebase.auth().currentUser
      store.commit("user/SET_USER_FULL", currentUser);

      user.getIdToken().then(token => {
        store.commit("user/SET_TOKEN", token)
      });

      if (!user) next('login')
      else next();
    });

  } else next()

})

export default Router
</code>```

I use Quasar. And this code is in my router/index.js. Don't forget to import your store like this: import store from '../store'

Body:
I use the firebase.auth().onAuthStateChanged function directly in my router guard like this:
I check if the route needs an authenticated user (optional) and then I load the currently logged in user and commit it in my Vuex store.
This way the currently logged in user is in my Vuex state before the route guard checks access. Otherwise, especially after a page reload, the user is not yet loaded and the guard redirects to the login page...

...

Router.beforeEach((to, from, next) => {

  let requiresAuth = to.matched.some(record => record.meta.requiresAuth)

  // If route requires auth --> load auth state first from firebase
  if (requiresAuth) {

    firebase.auth().onAuthStateChanged(user => {

      store.commit("user/SET_USER", user);

      let currentUser = firebase.auth().currentUser
      store.commit("user/SET_USER_FULL", currentUser);

      user.getIdToken().then(token => {
        store.commit("user/SET_TOKEN", token)
      });

      if (!user) next('login')
      else next();
    });

  } else next()

})

export default Router

I use Quasar. And this code is in my router/index.js. Don't forget to import your store like this: import store from '../store'


问:
java: convert a string to a string that contains the hex number of each character
I have a string that actually each byte in it is a representation of a hexadecimal number.

I want to create a new string that contains the actual hexadecimal numbers of each character.

I know that i can do String.getBytes() to get the bytes of each character, i know iterate through it with i=0;i<=String.getBytes().length. what i don't understand is how to create a new string that each character is the hexacdecimal number (0-F).

thanks!

答:
You could do something like

```<code>String test = "hello world", result = "";

for (byte b : test.getBytes())
    result += Integer.toHexString(b) + " ";

System.out.println(result);

// result = 68 65 6c 6c 6f 20 77 6f 72 6c 64
</code>```

Keep in mind though, that strings in Java are in unicode.

Body:
You could do something like

String test = "hello world", result = "";

for (byte b : test.getBytes())
    result += Integer.toHexString(b) + " ";

System.out.println(result);

// result = 68 65 6c 6c 6f 20 77 6f 72 6c 64

Keep in mind though, that strings in Java are in unicode.


问:
Use sfinae to single out preferred variadic constructor
I'm trying to write a policy-based class that forwards arguments to its unique super class, but also optionally takes some arguments of its own. The problem I'm facing is, the compiler seems to unconditionally prefer the second constructor below in the face of an implicit conversion - with only the parameter pack - over the first, which is the one I prefer.

#include <utility>
#include <iostream>

template <class Super>
struct Base : public Super {
  // 1
  template <typename... Args,
            typename = std::enable_if_t<std::is_constructible_v<Super, Args&&...>>>
  explicit Base(unsigned long count, Args&&... args)
    : Super(std::forward<Args>(args)...), count(count) {}

  // 2
  template <typename... Args,
            typename = std::enable_if_t<std::is_constructible_v<Super, Args&&...>>>
  explicit Base(Args&&... args) : Super(std::forward<Args>(args)...), count(0) {}

  unsigned long count;
};

struct A {
  explicit A(unsigned long id) {}
  A() {}
};

struct B {
  explicit B(const char* cstring) {}
  explicit B(unsigned long id, const char* cstring) {}
  explicit B(unsigned long id, A a) {}
  B() {}
};

int main() {
  auto a1 = Base(7);             // selects 2, but I want 1
  auto a2 = Base(7ul);           // selects 1
  auto a3 = Base(7, 10);         // selects 1
  auto b1 = Base(4);             // selects 1
  auto b2 = Base("0440");        // selects 2
  auto b3 = Base(4, "0440");     // selects 2, but I want 1
  auto b4 = Base(4, 4, "0440");  // selects 1
  auto b5 = Base(4, A());        // selects 2
  std::printf("%lu %lu %lu\n", a1.count, a2.count, a3.count);
  std::printf("%lu %lu %lu %lu %lu\n", b1.count, b2.count, b3.count, b4.count, b5.count);
  return 0;
}
```

The output is 0 7 7 on the first line, but I want 7 7 7, i.e. Base(7) should select the first constructor, not the second. Idem for b3.

The sfinae on the constructors let the compiler choose 1 when 2 doesn't match the arguments, but I want it to select constructor 1 every time it matches. In the a1 case, the implicit conversion of 7 from int to unsigned long is forcing a choice of constructor 2, which I also don't understand why.

How do I go about solving this?

答:
This seems to do what you want (though comments below point to it maybe being an invalid construct):

```<code>struct Base : public Super {
  // 1
  template <typename... Args,
            typename = std::enable_if_t<std::is_constructible_v<Super, Args...>>>
  explicit Base(unsigned long count, Args&&... args)
    : Super(std::forward<Args&&>(args)...), count(count) {
        static_assert(std::is_same_v<Super*, void>);
    }

  // 2
  template <typename... Args,
            typename = std::enable_if_t<!std::is_constructible_v<Base, Args...>>>
  explicit Base(Args&&... args) : Super(std::forward<Args>(args)...), count(0) {}

  unsigned long count;
};
</code>```

I love godbolt running your code now!

https://godbolt.org/z/UEweak

Body:
I'm trying to write a policy-based class that forwards arguments to its unique super class, but also optionally takes some arguments of its own. The problem I'm facing is, the compiler seems to unconditionally prefer the second constructor below in the face of an implicit conversion - with only the parameter pack - over the first, which is the one I prefer.

#include <utility>
#include <iostream>

template <class Super>
struct Base : public Super {
  // 1
  template <typename... Args,
            typename = std::enable_if_t<std::is_constructible_v<Super, Args&&...>>>
  explicit Base(unsigned long count, Args&&... args)
    : Super(std::forward<Args>(args)...), count(count) {}

  // 2
  template <typename... Args,
            typename = std::enable_if_t<std::is_constructible_v<Super, Args&&...>>>
  explicit Base(Args&&... args) : Super(std::forward<Args>(args)...), count(0) {}

  unsigned long count;
};

struct A {
  explicit A(unsigned long id) {}
  A() {}
};

struct B {
  explicit B(const char* cstring) {}
  explicit B(unsigned long id, const char* cstring) {}
  explicit B(unsigned long id, A a) {}
  B() {}
};

int main() {
  auto a1 = Base(7);             // selects 2, but I want 1
  auto a2 = Base(7ul);           // selects 1
  auto a3 = Base(7, 10);         // selects 1
  auto b1 = Base(4);             // selects 1
  auto b2 = Base("0440");        // selects 2
  auto b3 = Base(4, "0440");     // selects 2, but I want 1
  auto b4 = Base(4, 4, "0440");  // selects 1
  auto b5 = Base(4, A());        // selects 2
  std::printf("%lu %lu %lu\n", a1.count, a2.count, a3.count);
  std::printf("%lu %lu %lu %lu %lu\n", b1.count, b2.count, b3.count, b4.count, b5.count);
  return 0;
}

The output is 0 7 7 on the first line, but I want 7 7 7, i.e. Base(7) should select the first constructor, not the second. Idem for b3.

The sfinae on the constructors let the compiler choose 1 when 2 doesn't match the arguments, but I want it to select constructor 1 every time it matches. In the a1 case, the implicit conversion of 7 from int to unsigned long is forcing a choice of constructor 2, which I also don't understand why.

How do I go about solving this?

Body:
This seems to do what you want (though comments below point to it maybe being an invalid construct):

struct Base : public Super {
  // 1
  template <typename... Args,
            typename = std::enable_if_t<std::is_constructible_v<Super, Args...>>>
  explicit Base(unsigned long count, Args&&... args)
    : Super(std::forward<Args&&>(args)...), count(count) {
        static_assert(std::is_same_v<Super*, void>);
    }

  // 2
  template <typename... Args,
            typename = std::enable_if_t<!std::is_constructible_v<Base, Args...>>>
  explicit Base(Args&&... args) : Super(std::forward<Args>(args)...), count(0) {}

  unsigned long count;
};

I love godbolt running your code now!

https://godbolt.org/z/UEweak


问:
Python event loop does not work properly with stdin
I am trying to get my head around python's asyncio. I have written this piece of code just for demonstration to clear concept.

```<code>import asyncio
import threading

async def printer(b, a):
    print(b)
    await asyncio.sleep(5)
    print(a)

def loop_runner(loop):
    print('[RUNNING LOOP]')
    loop.run_forever()

if __name__ == '__main__':
    event_loop = asyncio.get_event_loop()
    # run_forever() is blocking. running it from separate thread
    loop_thread = threading.Thread(target=loop_runner, args=(event_loop,))
    loop_thread.start()

    while True:
        before, after = input('Before :'), input('After :')
        event_loop.create_task(printer(before, after))
</code>```

I am running event loop from separate thread and trying to create tasks in loop on runtime. But I can't understand why this code is not working. It takes input but then goes to next iteration without printing anything from printer function.

Surprisingly, if I do not take inputs from stdin, and just use hard coded messages like this

```<code>   messages = [('Hello', 'world'), ('Foo', 'bar'), ('Alice', 'Bob')]

    for message in messages:
        before, after = message
        coroutine = printer(f'[ITERATION] {count} [MESSAGE] {before}', f'[ITERATION] {count} [MESSAGE] {after}')
        event_loop.create_task(coroutine)
        count += 1
</code>```

everything just works fine. Output

```<code>[RUNNING LOOP]
[ITERATION] 0 [MESSAGE] Hello
[ITERATION] 1 [MESSAGE] Foo
[ITERATION] 2 [MESSAGE] Alice
[ITERATION] 0 [MESSAGE] world
[ITERATION] 1 [MESSAGE] bar
[ITERATION] 2 [MESSAGE] Bob
</code>```

Please help me understand this behavior with input

答:
You’re using asyncio improperly in the first setup. You shouldn’t need to interpose it with the threading module.

My recommended setup for this is to create an async function main which contains an infinite loop where you ask for input and create tasks. Then, you can run main from an event loop after you’re done declaring it.

Mind you, awaiting the tasks you create inside main in the above setup is optional; since stdout is guaranteed to be synchronized by the kernel (I’m 70%ish sure this is true,) you can have as many tasks as you want running printer() at a time. However, if you do await the tasks, your program won’t print out while the user is trying to input; it’ll call printer(), which writes to stdout, first, and only ask for the next set of input after printer() has completed.

Hope that answers your question. See the below documentation as an additional resource.

https://docs.python.org/3/library/asyncio-task.html

Body:
I am trying to get my head around python's asyncio. I have written this piece of code just for demonstration to clear concept.

import asyncio
import threading

async def printer(b, a):
    print(b)
    await asyncio.sleep(5)
    print(a)

def loop_runner(loop):
    print('[RUNNING LOOP]')
    loop.run_forever()

if __name__ == '__main__':
    event_loop = asyncio.get_event_loop()
    # run_forever() is blocking. running it from separate thread
    loop_thread = threading.Thread(target=loop_runner, args=(event_loop,))
    loop_thread.start()

    while True:
        before, after = input('Before :'), input('After :')
        event_loop.create_task(printer(before, after))

I am running event loop from separate thread and trying to create tasks in loop on runtime. But I can't understand why this code is not working. It takes input but then goes to next iteration without printing anything from printer function.

Surprisingly, if I do not take inputs from stdin, and just use hard coded messages like this

   messages = [('Hello', 'world'), ('Foo', 'bar'), ('Alice', 'Bob')]

    for message in messages:
        before, after = message
        coroutine = printer(f'[ITERATION] {count} [MESSAGE] {before}', f'[ITERATION] {count} [MESSAGE] {after}')
        event_loop.create_task(coroutine)
        count += 1

everything just works fine. Output

[RUNNING LOOP]
[ITERATION] 0 [MESSAGE] Hello
[ITERATION] 1 [MESSAGE] Foo
[ITERATION] 2 [MESSAGE] Alice
[ITERATION] 0 [MESSAGE] world
[ITERATION] 1 [MESSAGE] bar
[ITERATION] 2 [MESSAGE] Bob

Please help me understand this behavior with input


问:
Create an intermediary commit in history
I've been tasked with replicating our centralized VCS solution onto a git repository. My plan is to use a Jenkins pipeline to absorb commits from the CVCS, pull latest from git, then commit those changes onto git and push.

The goal is to capture every commit as it comes in, for which I'm using a webhook from the CVCS that passes relevant information to the pipeline to identify the particular commit in history. For the purposes of this question, assume all development is done in one unending line with no branches.

My concern is the asynchronous nature of a webhook call. If I have commit 1000 synced to git, then commits 1001 and 1002 both come in nearly simultaneously, the Jenkins pipeline might run 1002 before 1001. That in itself isn't a huge problem (I intend to include a text file on the git repo to keep track of the last synced CVCS commit), but it would be nice if I could handle 1001 in a more intelligent way than to discard it.

Is there any way to create an intermediary commit in git history? Something like:

```<code>git checkout HEAD~1
git checkout -b some_temp_branch
git commit -m "This is commit 1001"
git checkout master
git merge some_temp_branch -Xtheirs         # or something?
</code>```

where the resulting history goes from:

```<code>1002
 |
1000
</code>```

to

```<code>1002
 |
1001
 |
1000
</code>```

with no change in the working directory?

答:
It's worth noting that no matter how you do this, what you get is not an inserted commit.

If you rebase—however you do it—you get instead a new branch, ending with a new commit.  The new branch can re-use the name of the old branch (leading to the obvious question, What exactly do we mean by "branch"?), but your new commit chain will have new and different hash IDs from your original commit chain.

That is, if you had:

```<code>... <-c1000a <-c1001a   <-- master
</code>```

because your system thought c1001 should come right after c1000, and now it's realized that, no, there should be a commit in between, you can make a new c1001b:

```<code>... <-c1000a <-c1001a   <-- master
            \
             c1001b
</code>```

but now you have to copy what was c1001a to c1002b:

```<code>... <-c1000a <-c1001a   <-- master
            \
             c1001b <- c1002b
</code>```

You can now have the name master point to c1002b, "forgetting" c1001a entirely:

```<code>... <-c1000a <-c1001a
            \
             c1001b <- c1002b   <-- master
</code>```

The forgotten commit continues to exist (and be valid) for as long as Git remembers its hash ID somewhere (typically, in a reflog entry, for 30+ days, except on --bare repository servers where there's no grace period).  If some other Git has grabbed c1001a, that other Git retains it, and may merge it with c1002b—or whatever the latest tip of master is—later since, if they were both named master, you probably want c1001a merged in.  (You really don't, but Git doesn't know that.)

If you merge, you just get a merge commit at the end.  You add the commit to the new temporary branch:

```<code>             c1001a   <-- master
            /
... <-c1000a
            \
             c1001b   <-- temporary
</code>```

and then git checkout master; git merge -s ours temporary to retain the source tree from c1001a:

```<code>             c1001a
            /      \
... <-c1000a        c1002a   <-- master
            \      /
             c1001b   <-- temporary
</code>```

Erasing the temporary name gives you the final result:

```<code>             c1001a
            /      \
... <-c1000a        c1002a   <-- master
            \      /
             c1001b
</code>```

which won't give any other Git repositories any heartburn, as you didn't deliberately throw out a bad commit in favor of a new and improved version (that the other Git might then bring back).  Instead, you merely added commits, which all Gits understand other Gits to do at any time.

The drawback to the merge method is that this is perhaps not the correct history.

Body:
I've been tasked with replicating our centralized VCS solution onto a git repository. My plan is to use a Jenkins pipeline to absorb commits from the CVCS, pull latest from git, then commit those changes onto git and push.

The goal is to capture every commit as it comes in, for which I'm using a webhook from the CVCS that passes relevant information to the pipeline to identify the particular commit in history. For the purposes of this question, assume all development is done in one unending line with no branches.

My concern is the asynchronous nature of a webhook call. If I have commit 1000 synced to git, then commits 1001 and 1002 both come in nearly simultaneously, the Jenkins pipeline might run 1002 before 1001. That in itself isn't a huge problem (I intend to include a text file on the git repo to keep track of the last synced CVCS commit), but it would be nice if I could handle 1001 in a more intelligent way than to discard it.

Is there any way to create an intermediary commit in git history? Something like:

git checkout HEAD~1
git checkout -b some_temp_branch
git commit -m "This is commit 1001"
git checkout master
git merge some_temp_branch -Xtheirs         # or something?

where the resulting history goes from:

1002
 |
1000

to

1002
 |
1001
 |
1000

with no change in the working directory?

Body:
It's worth noting that no matter how you do this, what you get is not an inserted commit.

If you rebase—however you do it—you get instead a new branch, ending with a new commit.  The new branch can re-use the name of the old branch (leading to the obvious question, What exactly do we mean by "branch"?), but your new commit chain will have new and different hash IDs from your original commit chain.

That is, if you had:

... <-c1000a <-c1001a   <-- master

because your system thought c1001 should come right after c1000, and now it's realized that, no, there should be a commit in between, you can make a new c1001b:

... <-c1000a <-c1001a   <-- master
            \
             c1001b

but now you have to copy what was c1001a to c1002b:

... <-c1000a <-c1001a   <-- master
            \
             c1001b <- c1002b

You can now have the name master point to c1002b, "forgetting" c1001a entirely:

... <-c1000a <-c1001a
            \
             c1001b <- c1002b   <-- master

The forgotten commit continues to exist (and be valid) for as long as Git remembers its hash ID somewhere (typically, in a reflog entry, for 30+ days, except on --bare repository servers where there's no grace period).  If some other Git has grabbed c1001a, that other Git retains it, and may merge it with c1002b—or whatever the latest tip of master is—later since, if they were both named master, you probably want c1001a merged in.  (You really don't, but Git doesn't know that.)

If you merge, you just get a merge commit at the end.  You add the commit to the new temporary branch:

             c1001a   <-- master
            /
... <-c1000a
            \
             c1001b   <-- temporary

and then git checkout master; git merge -s ours temporary to retain the source tree from c1001a:

             c1001a
            /      \
... <-c1000a        c1002a   <-- master
            \      /
             c1001b   <-- temporary

Erasing the temporary name gives you the final result:

             c1001a
            /      \
... <-c1000a        c1002a   <-- master
            \      /
             c1001b

which won't give any other Git repositories any heartburn, as you didn't deliberately throw out a bad commit in favor of a new and improved version (that the other Git might then bring back).  Instead, you merely added commits, which all Gits understand other Gits to do at any time.

The drawback to the merge method is that this is perhaps not the correct history.


问:
How can I remove Child2 by parent using js
I was going to remove Child2 by parent, but its doesn't work

```<code>var y = document.getElementById('parent');
y.childNodes[0].removeChild(y.childNodes[0].childNodes[2]);

<div id="parent">
    <div>
        <a href="#">First</a>
        <a href="#">second</a>
        <a href="#">third</a> <!--I wanna delete this-->
    </div>
</div>
</code>```

Its just doesn't delete anything

答:
Use children instead of childNodes, because childNodes includes other element types whereas children is just elements.

From MDN:

childNodes includes all child nodes, including non-element nodes like text and comment nodes. To get a collection of only elements, use ParentNode.children instead.

You can also use remove() instead of removeChild() which will remove the current element from the dom.

var y = document.getElementById('parent');
y.children[0].children[2].remove();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="parent">
    <div>
        First
        second
        third <!--I wanna delete this-->
    </div>
</div></code>```

Body:
I was going to remove Child2 by parent, but its doesn't work

var y = document.getElementById('parent');
y.childNodes[0].removeChild(y.childNodes[0].childNodes[2]);

        First
        second
        third

Its just doesn't delete anything

Body:
Use children instead of childNodes, because childNodes includes other element types whereas children is just elements.

From MDN:

childNodes includes all child nodes, including non-element nodes like text and comment nodes. To get a collection of only elements, use ParentNode.children instead.

You can also use remove() instead of removeChild() which will remove the current element from the dom.

var y = document.getElementById('parent');
y.children[0].children[2].remove();

<div id="parent">
    <div>
        <a href="#">First</a>
        <a href="#">second</a>
        <a href="#">third</a> <!--I wanna delete this-->
    </div>
</div>


问:
Change JSON key and don't lose any data
I want to change json key but I can not manage

I tried to write a function:

```<code>modifySlotKey(requestObjectIntent, slotValue) {

requestObjectIntent['slots']['toChange'] = requestObjectIntent['slots'][slotValue]

return requestObjectIntent;
}
</code>```

but it doesn't work.

My json is like that:

```<code>"slots": {
  "toChange": {
    "name": "query",
    "value": "torte",
    "confirmationStatus": "NONE",
    "source": "USER"
  }
}
</code>```

but I want to change it to:

```<code>"slots": {
  "slotValue": {
    "name": "query",
    "value": "torte",
    "confirmationStatus": "NONE",
    "source": "USER"
  }
}
</code>```

Could somebody help me please to solve this issue?

答:
your code is fine but you only need to change the order of variables(slotValue = 'toChange') and delete de older key before return.

```<code>requestObjectIntent['slots'][slotValue] = requestObjectIntent['slots']['toChange];
delete(requestObjectIntent['slots']['toChange']);
</code>```

I do a little example and works fine: https://jsfiddle.net/g7t4Lan5/1/

Title: Change JSON key and don't lose any data

Body:
I want to change json key but I can not manage

I tried to write a function:

modifySlotKey(requestObjectIntent, slotValue) {

requestObjectIntent['slots']['toChange'] = requestObjectIntent['slots'][slotValue]

return requestObjectIntent;
}

but it doesn't work.

My json is like that:

"slots": {
  "toChange": {
    "name": "query",
    "value": "torte",
    "confirmationStatus": "NONE",
    "source": "USER"
  }
}

but I want to change it to:

"slots": {
  "slotValue": {
    "name": "query",
    "value": "torte",
    "confirmationStatus": "NONE",
    "source": "USER"
  }
}

Could somebody help me please to solve this issue?

Body:
your code is fine but you only need to change the order of variables(slotValue = 'toChange') and delete de older key before return.

requestObjectIntent['slots'][slotValue] = requestObjectIntent['slots']['toChange];
delete(requestObjectIntent['slots']['toChange']);

I do a little example and works fine: https://jsfiddle.net/g7t4Lan5/1/


答:
commons-codec has Hex.encode(byteArray)

you can also use Integer.toHexString(..) for each byte

Just be careful when obtaining the bytes. Use the method getBytes(ecnoding) instead of the one without arguments which takes the platform encoding.

Title: java: convert a string to a string that contains the hex number of each character

Body:
I have a string that actually each byte in it is a representation of a hexadecimal number.

I want to create a new string that contains the actual hexadecimal numbers of each character.

I know that i can do String.getBytes() to get the bytes of each character, i know iterate through it with i=0;i<=String.getBytes().length. what i don't understand is how to create a new string that each character is the hexacdecimal number (0-F).

thanks!


问:
SQL - How to make exclude condition
I have the following table. I'm trying to get the rows that met my specific condition.

Table look as follows:

```<code>account|transactiontypecode|
-------|-------------------|
1000058|                  8|
1000067|                  2|
1000067|                  8|
</code>```

The query output would retrieve only the account 1000058, as it applies to the transactiontypecode 8. The other account applies too, but it also has another transactiontypecode that does not applies.

So requirement would be to get the accounts that meet specifics transaction codes, and excludes accounts even though it can also have the code required but has codes unwanted too.

This was my guess over above issue, among others, but I think that other eyes may guide me on a better direction.

```<code>with cte1 as (
select
    gp.account,
    case
        when gp.transactiontypecode in (2,8,17) then TRUE
        else false
    end as txcheck
from
    gp.t2001 gp
group by
    1, 2)

select
    account,
    txcheck
from
    cte1
where
    txcheck is true and txcheck is not false;
</code>```

If anyone can help me achieve above requirement, would be great!

答:
Just use not exists if you want the entire rows:

```<code>select t.*
from gp.t2001 t
where t.transactiontypecode  = 8 and
      not exists (select 1
                  from gp.t2001 t2
                  where t2.account = t.account and
                        t2.transactiontypecode <> 8
                 );
</code>```

Or aggregation if you just want the account:

```<code>select t.account
from gp.t2001 t
group by t.account
having min(transactiontypecode) = max(transactiontypecode) and
       min(transactiontypecode) = 8;
</code>```

Title: SQL - How to make exclude condition

Body:
I have the following table. I'm trying to get the rows that met my specific condition.

Table look as follows:

account|transactiontypecode|
-------|-------------------|
1000058|                  8|
1000067|                  2|
1000067|                  8|

The query output would retrieve only the account 1000058, as it applies to the transactiontypecode 8. The other account applies too, but it also has another transactiontypecode that does not applies.

So requirement would be to get the accounts that meet specifics transaction codes, and excludes accounts even though it can also have the code required but has codes unwanted too.

This was my guess over above issue, among others, but I think that other eyes may guide me on a better direction.

with cte1 as (
select
    gp.account,
    case
        when gp.transactiontypecode in (2,8,17) then TRUE
        else false
    end as txcheck
from
    gp.t2001 gp
group by
    1, 2)

select
    account,
    txcheck
from
    cte1
where
    txcheck is true and txcheck is not false;

If anyone can help me achieve above requirement, would be great!

Body:
Just use not exists if you want the entire rows:

select t.*
from gp.t2001 t
where t.transactiontypecode  = 8 and
      not exists (select 1
                  from gp.t2001 t2
                  where t2.account = t.account and
                        t2.transactiontypecode <> 8
                 );

Or aggregation if you just want the account:

select t.account
from gp.t2001 t
group by t.account
having min(transactiontypecode) = max(transactiontypecode) and
       min(transactiontypecode) = 8;


答:
Here's the code (you didn't specify, so let's try Scala):</p>

```<code>// Your dataframes
val upper = ...
val lower = ...

// Find out the columns
val sharedCols = upper.columns.toSet & lower.columns.toSet
val disjointCols = (upper.columns.toSet | lower.columns.toSet) -- sharedCols
val columns = (sharedCols.map(c => coalesce(lower.col(c), upper.col(c)).as(c)) ++ disjointCols.map(c => col(c))).toList

// Join and project
val joined = upper.join(lower, upper.col("uid") === lower.col("uid"), "full_outer").select(columns:_*)
joined.show
</code>```

Title: Spark Join dataframes and conditionally update columns

Body:
Hi I have 2 spark dataframes.

The first one:

+---------------+---------------+-------+--------+---------+-----------+------------+---------------+----------------+
|cluster_socio_6|cluster_socio_7|country|latitude|longitude|last_update|         uid|segment_comp_11|cluster_comp_170|
+---------------+---------------+-------+--------+---------+-----------+------------+---------------+----------------+
|              2|              2|     IT|  41.884|  13.5204| 2019-04-15|d@rNdBkkN-p3|             10|               3|
|             16|             15|     IT| 45.5298|  9.03813| 2019-04-15|Ie2Bbs9PUR8h|             15|               4|
|             16|             15|     IT| 45.5298|  9.03813| 2019-04-15|Jk2Bbs9PUR8h|             15|               4|
+---------------+---------------+-------+--------+---------+-----------+------------+---------------+----------------+

and second one:

+---------------+---------------+-------+--------+---------+-----------+------------+
|cluster_socio_6|cluster_socio_7|country|latitude|longitude|last_update|         uid|
+---------------+---------------+-------+--------+---------+-----------+------------+
|              4|             17|     IT| 40.8413|  14.2008| 2019-04-16|ASBuzjKa6nIB|
|              2|              2|     IT|  41.884|  15.5204| 2019-04-16|d@rNdBkkN-p3|
|             16|             15|     IT| 45.5298|  9.03813| 2019-04-16|Ie2Bbs9PUR8h|
|             16|             15|     IT| 45.5298|  9.03813| 2019-04-15|xyzBbs9PUR8h|
+---------------+---------------+-------+--------+---------+-----------+------------+

apart country,latitude,longitude,last_update and uid, the bottom Df could have different columns added.

The idea is to make a full join by uid, update the common columns and keep the uncommon columns.

How could I accomplish this task?
Thanks.

Body:
Here's the code (you didn't specify, so let's try Scala):

// Your dataframes
val upper = ...
val lower = ...

// Find out the columns
val sharedCols = upper.columns.toSet & lower.columns.toSet
val disjointCols = (upper.columns.toSet | lower.columns.toSet) -- sharedCols
val columns = (sharedCols.map(c => coalesce(lower.col(c), upper.col(c)).as(c)) ++ disjointCols.map(c => col(c))).toList

// Join and project
val joined = upper.join(lower, upper.col("uid") === lower.col("uid"), "full_outer").select(columns:_*)
joined.show


问:
Creating NumPy matrix of a given size in a vectorized manner
If there a built-in NumPy function or any vectorized approach to generate the following 2D NumPy matrices for value of n > 1? Let me give some examples for the desired matrices for n equal to 2, 3, and 4.

One approach would be to construct a matrix of 1’s in the lower triangular part and then simply multiply by a vector np.arange(1, n+1). Any other alternatives?

```<code>import numpy as np
</code>```

For n = 2

```<code>n = 2
arr = np.array([[1, 0], [2, 2]])

# array([[1, 0],
#        [2, 2]])
</code>```

For n = 3

```<code>n = 3
arr = np.array([[1, 0, 0], [2, 2, 0], [3, 3, 3]])

# array([[1, 0, 0],
#        [2, 2, 0],
#        [3, 3, 3]])
</code>```

For n = 4

```<code>n = 4
arr = np.array([[1, 0, 0, 0], [2, 2, 0, 0], [3, 3, 3, 0], [4, 4, 4, 4]])

# array([[1, 0, 0, 0],
#        [2, 2, 0, 0],
#        [3, 3, 3, 0],
#        [4, 4, 4, 4]])
</code>```

My attempt (example for n = 4) using nested for loops. It works for any value of n > 1:

```<code>import numpy as np

n = 4
arr = np.zeros((n, n))

for i in range(n):
    for j in range(0, i+1):
        arr[i][j] = i+1

# array([[1., 0., 0., 0.],
#        [2., 2., 0., 0.],
#        [3., 3., 3., 0.],
#        [4., 4., 4., 4.]])
</code>```

Body:
If there a built-in NumPy function or any vectorized approach to generate the following 2D NumPy matrices for value of n > 1? Let me give some examples for the desired matrices for n equal to 2, 3, and 4.

One approach would be to construct a matrix of 1’s in the lower triangular part and then simply multiply by a vector np.arange(1, n+1). Any other alternatives?

import numpy as np

For n = 2

n = 2
arr = np.array([[1, 0], [2, 2]])

# array([[1, 0],
#        [2, 2]])

For n = 3

n = 3
arr = np.array([[1, 0, 0], [2, 2, 0], [3, 3, 3]])

# array([[1, 0, 0],
#        [2, 2, 0],
#        [3, 3, 3]])

For n = 4

n = 4
arr = np.array([[1, 0, 0, 0], [2, 2, 0, 0], [3, 3, 3, 0], [4, 4, 4, 4]])

# array([[1, 0, 0, 0],
#        [2, 2, 0, 0],
#        [3, 3, 3, 0],
#        [4, 4, 4, 4]])

My attempt (example for n = 4) using nested for loops. It works for any value of n > 1:

import numpy as np

n = 4
arr = np.zeros((n, n))

for i in range(n):
    for j in range(0, i+1):
        arr[i][j] = i+1

# array([[1., 0., 0., 0.],
#        [2., 2., 0., 0.],
#        [3., 3., 3., 0.],
#        [4., 4., 4., 4.]])

Body:
Here is a solution using np.where and broadcasting:

x = np.arange(1,n+1)
np.where(x[:,None]>=x,x[:,None],0)
# array([[1, 0, 0, 0],
#        [2, 2, 0, 0],
#        [3, 3, 3, 0],
#        [4, 4, 4, 4]])


问:
Bytestring containing '*', '+', ')', '@', among other unusual characters
As part of a longer project, I've experimented with audio encoding and decoding with python, using the pyaudio and wave libraries.

I've begun by creating a subroutine that reads data from a wave file, and each time it reads a frame of data from the wave file, it writes it to a text file by converting the bytestring it receives from the wave file to a string it can write to a text file.

That's all fine, but I'm very confused by some of the characters appearing, and I was wondering if there were any explanations to what some of these characters actually mean/do within the context of bytestrings, or if they are erroneous and my program is faulty:

b'*\x0f+\x0f' (I was not expecting * or +)

b'+\x03)\x03' (I was not expecting + or ))

b'@\xf2D\xf2' (I was not expecting @ or D)

There are several other odd combinations, but is there any explanations to these characters that would in turn make my understanding of the other unusual characters clearer? I'm quite new to understanding bytestrings, so please keep that in mind.

答:
When possible, a byte in a byte value is displayed as the ASCII character encoded by the byte.

```<code>>>> ord('*')
42
>>> b'\x2a'  # 0x2a == 42
b'*'
</code>```

Otherwise, the \xXX format is used.

```<code>>>> b'\x00\x2a'  # Two bytes: the null byte and 42
b'\x00*'
</code>```

Body:
When possible, a byte in a byte value is displayed as the ASCII character encoded by the byte.

>>> ord('*')
42
>>> b'\x2a'  # 0x2a == 42
b'*'

Otherwise, the \xXX format is used.

>>> b'\x00\x2a'  # Two bytes: the null byte and 42
b'\x00*'


问:
Python Multiprocessing within Jupyter Notebook does not work
I am new to multiprocessing module in Python and work with Jupyter notebooks.
When I try to run the following code I keep getting AttributeError: Can't get attribute 'load' on <module '__main__' (built-in)>

When I run the file there is no output, it just keeps loading.

```<code>import pandas as pd
import datetime
import urllib
import requests
from pprint import pprint
import time
from io import StringIO
from multiprocessing import Process, Pool

symbols = ['AAP']

start = time.time()
dflist = []

def load(date):
    if date is None:
        return
    url = "http://regsho.finra.org/FNYXshvol{}.txt".format(date)
    try:
        df = pd.read_csv(url,delimiter='|')
        if any(df['Symbol'].isin(symbols)):
            stocks = df[df['Symbol'].isin(symbols)]
            print(stocks.to_string(index=False, header=False))
            # Save stocks to mysql
        else:
            print(f'No stock found for {date}' )
    except urllib.error.HTTPError:
        pass

pool = []
numdays = 365
start_date = datetime.datetime(2019, 1, 15 )  #year - month - day
datelist = [
        (start_date - datetime.timedelta(days=x)).strftime('%Y%m%d') for x in range(0, numdays)
        ]

pool = Pool(processes=16)
pool.map(load, datelist)

pool.close()
pool.join()

print(time.time() - start)
</code>```

What can I do to run this code directly from the notebook without issues?

答:
one way to do it:

1. get load function out and create for example worker.py

2. import worker and worker.load

3.

```<code>from multiprocessing import Pool
import worker
if __name__ ==  '__main__':
  pool = []
  numdays = 365
  start_date = datetime.datetime(2019, 1, 15 )  #year - month - day
  datelist = [
        (start_date - datetime.timedelta(days=x)).strftime('%Y%m%d') for x in
        range(0, numdays)
        ]

  pool = Pool(processes=16)
  pool.map(worker.load, datelist)

  pool.close()
  pool.join()
</code>```

Body:
I am new to multiprocessing module in Python and work with Jupyter notebooks.
When I try to run the following code I keep getting AttributeError: Can't get attribute 'load' on <module '__main__' (built-in)>

When I run the file there is no output, it just keeps loading.

import pandas as pd
import datetime
import urllib
import requests
from pprint import pprint
import time
from io import StringIO
from multiprocessing import Process, Pool

symbols = ['AAP']

start = time.time()
dflist = []

def load(date):
    if date is None:
        return
    url = "http://regsho.finra.org/FNYXshvol{}.txt".format(date)
    try:
        df = pd.read_csv(url,delimiter='|')
        if any(df['Symbol'].isin(symbols)):
            stocks = df[df['Symbol'].isin(symbols)]
            print(stocks.to_string(index=False, header=False))
            # Save stocks to mysql
        else:
            print(f'No stock found for {date}' )
    except urllib.error.HTTPError:
        pass

pool = []
numdays = 365
start_date = datetime.datetime(2019, 1, 15 )  #year - month - day
datelist = [
        (start_date - datetime.timedelta(days=x)).strftime('%Y%m%d') for x in range(0, numdays)
        ]

pool = Pool(processes=16)
pool.map(load, datelist)

pool.close()
pool.join()

print(time.time() - start)

What can I do to run this code directly from the notebook without issues?

Body:
one way to do it:

1. get load function out and create for example worker.py

2. import worker and worker.load

3.

from multiprocessing import Pool
import worker
if __name__ ==  '__main__':
  pool = []
  numdays = 365
  start_date = datetime.datetime(2019, 1, 15 )  #year - month - day
  datelist = [
        (start_date - datetime.timedelta(days=x)).strftime('%Y%m%d') for x in
        range(0, numdays)
        ]

  pool = Pool(processes=16)
  pool.map(worker.load, datelist)

  pool.close()
  pool.join()