问:
How can I define ShapeBuilder for SwiftUI
As we know we have a very useful wrapper called @ViewBuilder for view but I am missing same wrapper for Shape protocol, Since there is no wrapper for this available, I am looking to try build one for learning porous.

Here is working code for view and looking to build the wrapper for Shape:

```<code>@ViewBuilder func testForView(value: Bool) -> some View {
    if value {
         Text("Hello")
    }
    else {
         Button("world!") {}
    }
}

// The Goal:
@ShapeBuilder func testForShape(value: Bool) -> some Shape {
    if value {
         Circle()
    }
    else {
         Rectangle()
    }
}
</code>```

I have experience working with wrappers or even defining a custom wrapper, but all my attempts were wrapping a value, not a function! I never tried to wrapp a function, frankly I do not know that it is thing in Swift or SwiftUI. So how can I make @ShapeBuilder works like @ViewBuilder works, I know that I must use Tuple or more correctly TupleShape, so I think I should define TupleShape as well.

答:
First we should ask whether it's worth writing a ShapeBuilder instead of writing an AnyShape type like this:

```<code>public struct AnyShape: Shape {
    public let makePath: (CGRect) -> Path

    public init(makePath: @escaping (CGRect) -> Path) {
        self.makePath = makePath
    }

    public init<Wrapped: Shape>(_ shape: Wrapped) {
        self.makePath = { shape.path(in: $0) }
    }

    public func path(in rect: CGRect) -> Path {
        return makePath(rect)
    }
}
</code>```

We can use AnyShape to write your testForShape function like this:

```<code>func testForShape(value: Bool) -> AnyShape {
    if value {
        return AnyShape(Circle())
    }
    else {
        return AnyShape(Rectangle())
    }
}
</code>```

I've used AnyShape in various projects.

Anyway, if we want to write ShapeBuilder, we can start with the simplest possible implementation, which only supports a body containing a single, unconditional child shape:

```<code>@resultBuilder
public struct ShapeBuilder {
    public static func buildBlock<C0: Shape>(_ c0: C0) -> C0 { c0 }
}
</code>```

We can now use it like this:

```<code>@ShapeBuilder
func shape1() -> some Shape {
    Circle()
}
</code>```

Hooray!

We can extend it to support a body containing no child shapes by adding a zero-argument buildBlock and an EmptyShape type for it to return:

```<code>extension ShapeBuilder {
    public static func buildBlock() -> EmptyShape { EmptyShape() }
}

public struct EmptyShape: Shape {
    public func path(in rect: CGRect) -> Path { Path() }
}
</code>```

Now we can write the following function without errors:

```<code>@ShapeBuilder
func shape0() -> some Shape {
}
</code>```

To support an if statement without an else clause, we add a buildOptional method and an OptionalShape type for it to return:

```<code>extension ShapeBuilder {
    public static func buildOptional<C0: Shape>(_ c0: C0?) -> OptionalShape<C0> {
        return OptionalShape(c0)
    }
}

public struct OptionalShape<Content: Shape>: Shape {
    public let content: Content?

    public init(_ content: Content?) {
        self.content = content
    }

    public func path(in rect: CGRect) -> Path {
        return content?.path(in: rect) ?? Path()
    }
}
</code>```

Now we can use it like this:

```<code>@ShapeBuilder
func shape2(flag: Bool) -> some Shape {
    if flag {
        Circle()
    }
}
</code>```

To support an if statement with an else clause, and to support a switch statement, we add buildEither and an EitherShape type for it to return:

```<code>extension ShapeBuilder {
    public static func buildEither<First: Shape, Second: Shape>(first: First) -> EitherShape<First, Second> {
        return .first(first)
    }

    public static func buildEither<First: Shape, Second: Shape>(second: Second) -> EitherShape<First, Second> {
        return .second(second)
    }
}

public enum EitherShape<First: Shape, Second: Shape>: Shape {
    case first(First)
    case second(Second)

    public func path(in rect: CGRect) -> Path {
        switch self {
        case .first(let first): return first.path(in: rect)
        case .second(let second): return second.path(in: rect)
        }
    }
}
</code>```

We can now write this function:

```<code>@ShapeBuilder
func shape3(_ n: Int) -> some Shape {
    if n < 0 {
        Rectangle()
    } else {
        switch n {
        case 0:
            EmptyShape()
        case 1:
            Rectangle()
        default:
            Capsule()
        }
    }
}
</code>```

We can support combining two child shapes by writing a buildBlock method that takes two arguments, and a Tuple2Shape for it to return:

```<code>extension ShapeBuilder {
    public static func buildBlock<C0: Shape, C1: Shape>(_ c0: C0, _ c1: C1) -> Tuple2Shape<C0, C1> {
        return Tuple2Shape(c0, c1)
    }
}

public struct Tuple2Shape<C0: Shape, C1: Shape>: Shape {
    public let tuple: (C0, C1)

    public init(_ c0: C0, _ c1: C1) {
        tuple = (c0, c1)
    }

    public func path(in rect: CGRect) -> Path {
        var path = tuple.0.path(in: rect)
        path.addPath(tuple.1.path(in: rect))
        return path
    }
}
</code>```

Now we can write this function:

```<code>@ShapeBuilder
func shape4() -> some Shape {
    Circle()
    Rectangle()
}
</code>```

We can support combining two child shapes by writing a buildBlock method that takes three arguments, and a Tuple3Shape for it to return:

```<code>extension ShapeBuilder {
    public static func buildBlock<C0: Shape, C1: Shape, C2: Shape>(_ c0: C0, _ c1: C1, _ c2: C2) -> Tuple3Shape<C0, C1, C2> {
        return Tuple3Shape(c0, c1, c2)
    }
}

public struct Tuple3Shape<C0: Shape, C1: Shape, C2: Shape>: Shape {
    public let tuple: (C0, C1, C2)

    public init(_ c0: C0, _ c1: C1, _ c2: C2) {
        tuple = (c0, c1, c2)
    }

    public func path(in rect: CGRect) -> Path {
        var path = tuple.0.path(in: rect)
        path.addPath(tuple.1.path(in: rect))
        path.addPath(tuple.2.path(in: rect))
        return path
    }
}
</code>```

That lets us write this function:

```<code>@ShapeBuilder
func shape5() -> some Shape {
    Circle()
    Rectangle()
    Capsule()
}
</code>```

ViewBuilder has buildBlock methods up to arity 10, but I'm not going to write out any more. You can do it yourself if you need them.

Anyway, here's the ShapeBuilder implementation all together for easy copy'n'paste:

```<code>@resultBuilder
public struct ShapeBuilder {
    public static func buildBlock<C0: Shape>(_ c0: C0) -> C0 { c0 }
}

extension ShapeBuilder {
    public static func buildBlock() -> EmptyShape { EmptyShape() }
}

public struct EmptyShape: Shape {
    public func path(in rect: CGRect) -> Path { Path() }
}

extension ShapeBuilder {
    public static func buildOptional<C0: Shape>(_ c0: C0?) -> OptionalShape<C0> {
        return OptionalShape(c0)
    }
}

public struct OptionalShape<Content: Shape>: Shape {
    public let content: Content?

    public init(_ content: Content?) {
        self.content = content
    }

    public func path(in rect: CGRect) -> Path {
        return content?.path(in: rect) ?? Path()
    }
}

extension ShapeBuilder {
    public static func buildEither<First: Shape, Second: Shape>(first: First) -> EitherShape<First, Second> {
        return .first(first)
    }

    public static func buildEither<First: Shape, Second: Shape>(second: Second) -> EitherShape<First, Second> {
        return .second(second)
    }
}

public enum EitherShape<First: Shape, Second: Shape>: Shape {
    case first(First)
    case second(Second)

    public func path(in rect: CGRect) -> Path {
        switch self {
        case .first(let first): return first.path(in: rect)
        case .second(let second): return second.path(in: rect)
        }
    }
}

extension ShapeBuilder {
    public static func buildBlock<C0: Shape, C1: Shape>(_ c0: C0, _ c1: C1) -> Tuple2Shape<C0, C1> {
        return Tuple2Shape(c0, c1)
    }
}

public struct Tuple2Shape<C0: Shape, C1: Shape>: Shape {
    public let tuple: (C0, C1)

    public init(_ c0: C0, _ c1: C1) {
        tuple = (c0, c1)
    }

    public func path(in rect: CGRect) -> Path {
        var path = tuple.0.path(in: rect)
        path.addPath(tuple.1.path(in: rect))
        return path
    }
}

extension ShapeBuilder {
    public static func buildBlock<C0: Shape, C1: Shape, C2: Shape>(_ c0: C0, _ c1: C1, _ c2: C2) -> Tuple3Shape<C0, C1, C2> {
        return Tuple3Shape(c0, c1, c2)
    }
}

public struct Tuple3Shape<C0: Shape, C1: Shape, C2: Shape>: Shape {
    public let tuple: (C0, C1, C2)

    public init(_ c0: C0, _ c1: C1, _ c2: C2) {
        tuple = (c0, c1, c2)
    }

    public func path(in rect: CGRect) -> Path {
        var path = tuple.0.path(in: rect)
        path.addPath(tuple.1.path(in: rect))
        path.addPath(tuple.2.path(in: rect))
        return path
    }
}
</code>```

Body:
As we know we have a very useful wrapper called @ViewBuilder for view but I am missing same wrapper for Shape protocol, Since there is no wrapper for this available, I am looking to try build one for learning porous.

Here is working code for view and looking to build the wrapper for Shape:

@ViewBuilder func testForView(value: Bool) -> some View {
    if value {
         Text("Hello")
    }
    else {
         Button("world!") {}
    }
}

// The Goal:
@ShapeBuilder func testForShape(value: Bool) -> some Shape {
    if value {
         Circle()
    }
    else {
         Rectangle()
    }
}

I have experience working with wrappers or even defining a custom wrapper, but all my attempts were wrapping a value, not a function! I never tried to wrapp a function, frankly I do not know that it is thing in Swift or SwiftUI. So how can I make @ShapeBuilder works like @ViewBuilder works, I know that I must use Tuple or more correctly TupleShape, so I think I should define TupleShape as well.

Body:
First we should ask whether it's worth writing a ShapeBuilder instead of writing an AnyShape type like this:

public struct AnyShape: Shape {
    public let makePath: (CGRect) -> Path

    public init(makePath: @escaping (CGRect) -> Path) {
        self.makePath = makePath
    }

    public init<Wrapped: Shape>(_ shape: Wrapped) {
        self.makePath = { shape.path(in: $0) }
    }

    public func path(in rect: CGRect) -> Path {
        return makePath(rect)
    }
}

We can use AnyShape to write your testForShape function like this:

func testForShape(value: Bool) -> AnyShape {
    if value {
        return AnyShape(Circle())
    }
    else {
        return AnyShape(Rectangle())
    }
}

I've used AnyShape in various projects.

Anyway, if we want to write ShapeBuilder, we can start with the simplest possible implementation, which only supports a body containing a single, unconditional child shape:

@resultBuilder
public struct ShapeBuilder {
    public static func buildBlock<C0: Shape>(_ c0: C0) -> C0 { c0 }
}

We can now use it like this:

@ShapeBuilder
func shape1() -> some Shape {
    Circle()
}

Hooray!

We can extend it to support a body containing no child shapes by adding a zero-argument buildBlock and an EmptyShape type for it to return:

extension ShapeBuilder {
    public static func buildBlock() -> EmptyShape { EmptyShape() }
}

public struct EmptyShape: Shape {
    public func path(in rect: CGRect) -> Path { Path() }
}

Now we can write the following function without errors:

@ShapeBuilder
func shape0() -> some Shape {
}

To support an if statement without an else clause, we add a buildOptional method and an OptionalShape type for it to return:

extension ShapeBuilder {
    public static func buildOptional<C0: Shape>(_ c0: C0?) -> OptionalShape<C0> {
        return OptionalShape(c0)
    }
}

public struct OptionalShape<Content: Shape>: Shape {
    public let content: Content?

    public init(_ content: Content?) {
        self.content = content
    }

    public func path(in rect: CGRect) -> Path {
        return content?.path(in: rect) ?? Path()
    }
}

Now we can use it like this:

@ShapeBuilder
func shape2(flag: Bool) -> some Shape {
    if flag {
        Circle()
    }
}

To support an if statement with an else clause, and to support a switch statement, we add buildEither and an EitherShape type for it to return:

extension ShapeBuilder {
    public static func buildEither<First: Shape, Second: Shape>(first: First) -> EitherShape<First, Second> {
        return .first(first)
    }

    public static func buildEither<First: Shape, Second: Shape>(second: Second) -> EitherShape<First, Second> {
        return .second(second)
    }
}

public enum EitherShape<First: Shape, Second: Shape>: Shape {
    case first(First)
    case second(Second)

    public func path(in rect: CGRect) -> Path {
        switch self {
        case .first(let first): return first.path(in: rect)
        case .second(let second): return second.path(in: rect)
        }
    }
}

We can now write this function:

@ShapeBuilder
func shape3(_ n: Int) -> some Shape {
    if n < 0 {
        Rectangle()
    } else {
        switch n {
        case 0:
            EmptyShape()
        case 1:
            Rectangle()
        default:
            Capsule()
        }
    }
}

We can support combining two child shapes by writing a buildBlock method that takes two arguments, and a Tuple2Shape for it to return:

extension ShapeBuilder {
    public static func buildBlock<C0: Shape, C1: Shape>(_ c0: C0, _ c1: C1) -> Tuple2Shape<C0, C1> {
        return Tuple2Shape(c0, c1)
    }
}

public struct Tuple2Shape<C0: Shape, C1: Shape>: Shape {
    public let tuple: (C0, C1)

    public init(_ c0: C0, _ c1: C1) {
        tuple = (c0, c1)
    }

    public func path(in rect: CGRect) -> Path {
        var path = tuple.0.path(in: rect)
        path.addPath(tuple.1.path(in: rect))
        return path
    }
}

Now we can write this function:

@ShapeBuilder
func shape4() -> some Shape {
    Circle()
    Rectangle()
}

We can support combining two child shapes by writing a buildBlock method that takes three arguments, and a Tuple3Shape for it to return:

extension ShapeBuilder {
    public static func buildBlock<C0: Shape, C1: Shape, C2: Shape>(_ c0: C0, _ c1: C1, _ c2: C2) -> Tuple3Shape<C0, C1, C2> {
        return Tuple3Shape(c0, c1, c2)
    }
}

public struct Tuple3Shape<C0: Shape, C1: Shape, C2: Shape>: Shape {
    public let tuple: (C0, C1, C2)

    public init(_ c0: C0, _ c1: C1, _ c2: C2) {
        tuple = (c0, c1, c2)
    }

    public func path(in rect: CGRect) -> Path {
        var path = tuple.0.path(in: rect)
        path.addPath(tuple.1.path(in: rect))
        path.addPath(tuple.2.path(in: rect))
        return path
    }
}

That lets us write this function:

@ShapeBuilder
func shape5() -> some Shape {
    Circle()
    Rectangle()
    Capsule()
}

ViewBuilder has buildBlock methods up to arity 10, but I'm not going to write out any more. You can do it yourself if you need them.

Anyway, here's the ShapeBuilder implementation all together for easy copy'n'paste:

@resultBuilder
public struct ShapeBuilder {
    public static func buildBlock<C0: Shape>(_ c0: C0) -> C0 { c0 }
}

extension ShapeBuilder {
    public static func buildBlock() -> EmptyShape { EmptyShape() }
}

public struct EmptyShape: Shape {
    public func path(in rect: CGRect) -> Path { Path() }
}

extension ShapeBuilder {
    public static func buildOptional<C0: Shape>(_ c0: C0?) -> OptionalShape<C0> {
        return OptionalShape(c0)
    }
}

public struct OptionalShape<Content: Shape>: Shape {
    public let content: Content?

    public init(_ content: Content?) {
        self.content = content
    }

    public func path(in rect: CGRect) -> Path {
        return content?.path(in: rect) ?? Path()
    }
}

extension ShapeBuilder {
    public static func buildEither<First: Shape, Second: Shape>(first: First) -> EitherShape<First, Second> {
        return .first(first)
    }

    public static func buildEither<First: Shape, Second: Shape>(second: Second) -> EitherShape<First, Second> {
        return .second(second)
    }
}

public enum EitherShape<First: Shape, Second: Shape>: Shape {
    case first(First)
    case second(Second)

    public func path(in rect: CGRect) -> Path {
        switch self {
        case .first(let first): return first.path(in: rect)
        case .second(let second): return second.path(in: rect)
        }
    }
}

extension ShapeBuilder {
    public static func buildBlock<C0: Shape, C1: Shape>(_ c0: C0, _ c1: C1) -> Tuple2Shape<C0, C1> {
        return Tuple2Shape(c0, c1)
    }
}

public struct Tuple2Shape<C0: Shape, C1: Shape>: Shape {
    public let tuple: (C0, C1)

    public init(_ c0: C0, _ c1: C1) {
        tuple = (c0, c1)
    }

    public func path(in rect: CGRect) -> Path {
        var path = tuple.0.path(in: rect)
        path.addPath(tuple.1.path(in: rect))
        return path
    }
}

extension ShapeBuilder {
    public static func buildBlock<C0: Shape, C1: Shape, C2: Shape>(_ c0: C0, _ c1: C1, _ c2: C2) -> Tuple3Shape<C0, C1, C2> {
        return Tuple3Shape(c0, c1, c2)
    }
}

public struct Tuple3Shape<C0: Shape, C1: Shape, C2: Shape>: Shape {
    public let tuple: (C0, C1, C2)

    public init(_ c0: C0, _ c1: C1, _ c2: C2) {
        tuple = (c0, c1, c2)
    }

    public func path(in rect: CGRect) -> Path {
        var path = tuple.0.path(in: rect)
        path.addPath(tuple.1.path(in: rect))
        path.addPath(tuple.2.path(in: rect))
        return path
    }
}


来源: stackexchange

问:
java.lang.IllegalStateException: YouTubeServiceEntity not initialized error when using YouTubePlayerApi
I'm using YouTubePlayerAPI and YouTubePlayerSupportFragment in my app and I'm getting the following error, but I couldn't find out what is causing it. I've been looking for information but I haven't found anything useful.

```<code>java.lang.IllegalStateException: YouTubeServiceEntity not initialized
    at android.os.Parcel.readException(Parcel.java:1433)
    at android.os.Parcel.readException(Parcel.java:1379)
    at com.google.android.youtube.player.internal.l$a$a.a(Unknown Source)
    at com.google.android.youtube.player.internal.o.a(Unknown Source)
    at com.google.android.youtube.player.internal.ad.a(Unknown Source)
    at com.google.android.youtube.player.YouTubePlayerView.a(Unknown Source)
    at com.google.android.youtube.player.YouTubePlayerView$1.a(Unknown Source)
    at com.google.android.youtube.player.internal.r.g(Unknown Source)
    at com.google.android.youtube.player.internal.r$c.a(Unknown Source)
    at com.google.android.youtube.player.internal.r$b.a(Unknown Source)
    at com.google.android.youtube.player.internal.r$a.handleMessage(Unknown Source)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:5041)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    at dalvik.system.NativeStart.main(Native Method)
</code>```

In the stackstrace there isn't any line number pointing to any of my classes or activities.

Any idea of it?

Thanks!

EDIT

My custom YoutubePlayerFragment Class: YouTubeVideoPlayerFragment.java

```<code>public class YouTubeVideoPlayerFragment extends YouTubePlayerSupportFragment {

private static final String ARG_URL = "url";

// ===========================================================
// Constructors
// ===========================================================

/**
 * Mandatory empty constructor for the fragment manager to instantiate the
 * fragment (e.g. upon screen orientation changes).
 */
public YouTubeVideoPlayerFragment() {
}

/**
 * Factory method to generate a new instance of the fragment given a video URL.
 *
 * @param url The video url this fragment represents
 * @return A new instance of this fragment with itemId extras
 */
public static YouTubeVideoPlayerFragment newInstance(String url) {
    final YouTubeVideoPlayerFragment mFragment = new YouTubeVideoPlayerFragment();

    // Set up extras
    final Bundle args = new Bundle();
    args.putString(ARG_URL, url);
    mFragment.setArguments(args);

    // Initialize YouTubePlayer
    mFragment.init();

    return mFragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

private void init(){
    initialize(Constants.API_KEY, new YouTubePlayer.OnInitializedListener() {
        @Override
        public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) {
            if (!wasRestored) {
                youTubePlayer.cueVideo(getArguments().getString(ARG_URL));
                youTubePlayer.setShowFullscreenButton(false);
            }
    }
}
</code>```

fragment.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:background="@color/black" >

    <!-- For YoutubeFragment -->
    <FrameLayout
        android:id="@+id/youtube_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>
</code>```

calling method:

```<code>// Create a new instance of YouTubeVideoPlayerFragment providing video id
        // and place it in the corresponding FrameLayout
        final YouTubeVideoPlayerFragment youTubeVideoPlayerFragment = YouTubeVideoPlayerFragment.newInstance(VIDEO_ID);
        final FragmentTransaction ft = getChildFragmentManager().beginTransaction();
        ft.replace(R.id.youtube_fragment, youTubeVideoPlayerFragment);
        ft.commit();
</code>```

EDIT

I've found out the origin of that error. This is the scenario:

The activity starts. In onCreate() it instantiates a new YouTubeVideoPlayerFragment and initializes YouTube object (which starts the YouTubeServiceEntity internally) in its newInstance() method. Then the YouTube fragment that was instantiated before, is attached with FragmentManager to the corresponding FrameLayout while video is loading.

Here is the issue: If user exits the activity before video had been loaded, the exception is thrown.

So if user want to exit from the activity in that case, what should I do and how? I don't really know what to do!

答: I could fix this error by using a ProgressDialog to wait until the player is loaded.

ContentLicense: CC BY-SA 3.0

Body:
I'm using YouTubePlayerAPI and YouTubePlayerSupportFragment in my app and I'm getting the following error, but I couldn't find out what is causing it. I've been looking for information but I haven't found anything useful.

java.lang.IllegalStateException: YouTubeServiceEntity not initialized
    at android.os.Parcel.readException(Parcel.java:1433)
    at android.os.Parcel.readException(Parcel.java:1379)
    at com.google.android.youtube.player.internal.l$a$a.a(Unknown Source)
    at com.google.android.youtube.player.internal.o.a(Unknown Source)
    at com.google.android.youtube.player.internal.ad.a(Unknown Source)
    at com.google.android.youtube.player.YouTubePlayerView.a(Unknown Source)
    at com.google.android.youtube.player.YouTubePlayerView$1.a(Unknown Source)
    at com.google.android.youtube.player.internal.r.g(Unknown Source)
    at com.google.android.youtube.player.internal.r$c.a(Unknown Source)
    at com.google.android.youtube.player.internal.r$b.a(Unknown Source)
    at com.google.android.youtube.player.internal.r$a.handleMessage(Unknown Source)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:5041)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    at dalvik.system.NativeStart.main(Native Method)

In the stackstrace there isn't any line number pointing to any of my classes or activities.

Any idea of it?

Thanks!

EDIT

My custom YoutubePlayerFragment Class: YouTubeVideoPlayerFragment.java

public class YouTubeVideoPlayerFragment extends YouTubePlayerSupportFragment {

private static final String ARG_URL = "url";

// ===========================================================
// Constructors
// ===========================================================

/**
 * Mandatory empty constructor for the fragment manager to instantiate the
 * fragment (e.g. upon screen orientation changes).
 */
public YouTubeVideoPlayerFragment() {
}

/**
 * Factory method to generate a new instance of the fragment given a video URL.
 *
 * @param url The video url this fragment represents
 * @return A new instance of this fragment with itemId extras
 */
public static YouTubeVideoPlayerFragment newInstance(String url) {
    final YouTubeVideoPlayerFragment mFragment = new YouTubeVideoPlayerFragment();

    // Set up extras
    final Bundle args = new Bundle();
    args.putString(ARG_URL, url);
    mFragment.setArguments(args);

    // Initialize YouTubePlayer
    mFragment.init();

    return mFragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

private void init(){
    initialize(Constants.API_KEY, new YouTubePlayer.OnInitializedListener() {
        @Override
        public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) {
            if (!wasRestored) {
                youTubePlayer.cueVideo(getArguments().getString(ARG_URL));
                youTubePlayer.setShowFullscreenButton(false);
            }
    }
}

fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:background="@color/black" >

    <FrameLayout
        android:id="@+id/youtube_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

calling method:

// Create a new instance of YouTubeVideoPlayerFragment providing video id
        // and place it in the corresponding FrameLayout
        final YouTubeVideoPlayerFragment youTubeVideoPlayerFragment = YouTubeVideoPlayerFragment.newInstance(VIDEO_ID);
        final FragmentTransaction ft = getChildFragmentManager().beginTransaction();
        ft.replace(R.id.youtube_fragment, youTubeVideoPlayerFragment);
        ft.commit();

EDIT

I've found out the origin of that error. This is the scenario:

The activity starts. In onCreate() it instantiates a new YouTubeVideoPlayerFragment and initializes YouTube object (which starts the YouTubeServiceEntity internally) in its newInstance() method. Then the YouTube fragment that was instantiated before, is attached with FragmentManager to the corresponding FrameLayout while video is loading.

Here is the issue: If user exits the activity before video had been loaded, the exception is thrown.

So if user want to exit from the activity in that case, what should I do and how? I don't really know what to do!

ContentLicense: CC BY-SA 4.0


问:
The type initializer for 'System.Data.SqlClient.TdsParser' threw an exception error while calling Stored Procedure from Azure function
I have an Azure Event hub with readings from my smart electricity meter. I am trying to use an Azure Function to write the meter readings to an Azure SQL DB. I have created a target table in the Azure SQL DB and a Stored Procedure to parse a JSON and store the contents in the table. I have successfully tested the stored procedure.

When I call it from my Azure Function however I am getting an error: The type initializer for 'System.Data.SqlClient.TdsParser' threw an exception. For testing purposes, I have tried to execute a simple SQL select statement from my Azure Function, but that gives the same error. I am lost at the moment as I have tried many options without any luck. Here is the Azure function code:

#r "Microsoft.Azure.EventHubs"

using System;
using System.Text;
using System.Data;
using Microsoft.Azure.EventHubs;
using System.Data.SqlClient;
using System.Configuration;
using Dapper;

public static async Task Run(string events, ILogger log)
{
    var exceptions = new List<Exception>();

    try
      {
            if(String.IsNullOrWhiteSpace(events))
                return;
            try{
                string ConnString = Environment.GetEnvironmentVariable("SQLAZURECONNSTR_azure-db-connection-meterreadevents", EnvironmentVariableTarget.Process);

                using(SqlConnection conn = new SqlConnection(ConnString))
                {
                    conn.Execute("dbo.ImportEvents", new { Events = events }, commandType: CommandType.StoredProcedure);
                }

            } catch (Exception ex) {
                log.LogInformation($"C# Event Hub trigger function exception: {ex.Message}");
            }
        }
        catch (Exception e)
        {
            // We need to keep processing the rest of the batch - capture this exception and continue.
            // Also, consider capturing details of the message that failed to process so it can be processed again later.
            exceptions.Add(e);
        }

    // Once processing of the batch is complete if any messages in the batch failed process throw an exception so that there is a record of the failure.

    if (exceptions.Count > 1)
        throw new AggregateException(exceptions);

    if (exceptions.Count == 1)
        throw exceptions.Single();
}
```

<p>The events coming in are in JSON form as follows</p>

```{
   "current_consumption":450,
   "back_low":0.004,
   "current_back":0,
   "total_high":13466.338,
   "gas":8063.749,
   "current_rate":"001",
   "total_low":12074.859,
   "back_high":0.011,
   "timestamp":"2020-02-29 22:21:14.087210"
}
```

<p>The stored procedure is as follows:</p>

```CREATE PROCEDURE [dbo].[ImportEvents]
@Events NVARCHAR(MAX)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON

    -- Insert statements for procedure here
    INSERT INTO dbo.MeterReadEvents

    SELECT * FROM OPENJSON(@Events) WITH (timestamp datetime2, current_consumption int, current_rate nchar(3), current_back int, total_low numeric(8, 3), back_high numeric(8, 3), total_high numeric(8, 3), gas numeric(7, 3), back_low numeric(8, 3))
END
```

I have added a connection string of type SQL AZURE and changed {your password} by the actual password in the string. Any thoughts on how to fix this issue or maybe how to get more logging as the error is very general?.

答: Pretty silly but I got this after installing the EntityFrameworkCore Nuget package but not EntityFrameworkCore.SqlServer Nuget package. I had the SqlServer version for EntityFramework 6 installed.</p>

Body:
I have an Azure Event hub with readings from my smart electricity meter. I am trying to use an Azure Function to write the meter readings to an Azure SQL DB. I have created a target table in the Azure SQL DB and a Stored Procedure to parse a JSON and store the contents in the table. I have successfully tested the stored procedure.

When I call it from my Azure Function however I am getting an error: The type initializer for 'System.Data.SqlClient.TdsParser' threw an exception. For testing purposes, I have tried to execute a simple SQL select statement from my Azure Function, but that gives the same error. I am lost at the moment as I have tried many options without any luck. Here is the Azure function code:

#r "Microsoft.Azure.EventHubs"

using System;
using System.Text;
using System.Data;
using Microsoft.Azure.EventHubs;
using System.Data.SqlClient;
using System.Configuration;
using Dapper;

public static async Task Run(string events, ILogger log)
{
    var exceptions = new List<Exception>();

    try
      {
            if(String.IsNullOrWhiteSpace(events))
                return;
            try{
                string ConnString = Environment.GetEnvironmentVariable("SQLAZURECONNSTR_azure-db-connection-meterreadevents", EnvironmentVariableTarget.Process);

                using(SqlConnection conn = new SqlConnection(ConnString))
                {
                    conn.Execute("dbo.ImportEvents", new { Events = events }, commandType: CommandType.StoredProcedure);
                }

            } catch (Exception ex) {
                log.LogInformation($"C# Event Hub trigger function exception: {ex.Message}");
            }
        }
        catch (Exception e)
        {
            // We need to keep processing the rest of the batch - capture this exception and continue.
            // Also, consider capturing details of the message that failed to process so it can be processed again later.
            exceptions.Add(e);
        }

    // Once processing of the batch is complete if any messages in the batch failed process throw an exception so that there is a record of the failure.

    if (exceptions.Count > 1)
        throw new AggregateException(exceptions);

    if (exceptions.Count == 1)
        throw exceptions.Single();
}

The events coming in are in JSON form as follows

{
   "current_consumption":450,
   "back_low":0.004,
   "current_back":0,
   "total_high":13466.338,
   "gas":8063.749,
   "current_rate":"001",
   "total_low":12074.859,
   "back_high":0.011,
   "timestamp":"2020-02-29 22:21:14.087210"
}

The stored procedure is as follows:

CREATE PROCEDURE [dbo].[ImportEvents]
@Events NVARCHAR(MAX)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON

    -- Insert statements for procedure here
    INSERT INTO dbo.MeterReadEvents

    SELECT * FROM OPENJSON(@Events) WITH (timestamp datetime2, current_consumption int, current_rate nchar(3), current_back int, total_low numeric(8, 3), back_high numeric(8, 3), total_high numeric(8, 3), gas numeric(7, 3), back_low numeric(8, 3))
END

I have added a connection string of type SQL AZURE and changed {your password} by the actual password in the string. Any thoughts on how to fix this issue or maybe how to get more logging as the error is very general?.


问:
Problem with SVN in iPhone?
I am using Smart SVN for committed my code to server. I have faced some problem, some of the classes are there in my project work copy and the server also. When i open that project file and i missed some classes and images in the xcode file. But all the files are in the project work copy, when opened that file some files are missing only in Xcode. After that, i have to drag those missing my file from my local copy to Xcode file, then it works fine. In the server all files are there, but i donno why it is not coming to Xcode folder. </p>

答:
Check if your project file is also committed and updated.
You and your teammates should always commit your project file after you added some files into your project.</p>

Title: Problem with SVN in iPhone?


问:
next.js environment variables are undefined (Next.js 10.0.5)
I am coding a website with Next.js and I tried to add google Tag Manager.

I followed the tutorial on the Next.js Github example but for some reasons I can't access to my environment variables.

It says my variable is undefined.

I created a file .env.local on my project folder (at the same level as components, node_modules, pages, etc)

In this file I created a variable like this (test purpose) :

```<code>NEXT_PUBLIC_DB_HOST=localhost
</code>```

And on my index page I tried this code :

```<code>console.log("test ", process.env.NEXT_PUBLIC_DB_HOST);
</code>```

But in my console I get a "test  undefined".

I tried to put my variable into an .env file instead, without success.

What I am doing wrong ?

答:
For those using NextJS +9 and looking for environment variables in the browser, you should use the NEXT_PUBLIC_ prefix. Example:

```<code>NEXT_PUBLIC_ANALYTICS_ID=123456789
</code>```

See documentation for reference.

Body:
I am coding a website with Next.js and I tried to add google Tag Manager.

I followed the tutorial on the Next.js Github example but for some reasons I can't access to my environment variables.

It says my variable is undefined.

I created a file .env.local on my project folder (at the same level as components, node_modules, pages, etc)

In this file I created a variable like this (test purpose) :

NEXT_PUBLIC_DB_HOST=localhost

And on my index page I tried this code :

console.log("test ", process.env.NEXT_PUBLIC_DB_HOST);

But in my console I get a "test  undefined".

I tried to put my variable into an .env file instead, without success.

What I am doing wrong ?

Body:
For those using NextJS +9 and looking for environment variables in the browser, you should use the NEXT_PUBLIC_ prefix. Example:

NEXT_PUBLIC_ANALYTICS_ID=123456789

See documentation for reference.


问:
Thymeleaf cache set to false not working
I have a spring application under development.
The configuration of the project is as follows:

spring-dev-tools dependency is one of the maven dependencies

thymeleaf dependency is added through spring-boot-starter, that is org.springframework.boot:spring-boot-starter-thymeleaf

I have explicitly disabled template cache with spring.thymeleaf.cache=false

The src/main/resources folder is marked as resource in my IntelliJ IDEA project.

I am using IntelliJ IDEA project to run the application.
When I run the application, I can see in the console output that: LiveReload server is running on port 35729

Although, it seems like all my configuration is correct, the running application is not loading any changes I made to the templates while it is running.

答:
If you are using Spring Tool Suite 4, you need to implement the following in your application.properties to disable the cache from Thymeleaf:

```<code>spring.thymeleaf.cache=false
spring.thymeleaf.prefix=file:src/main/resources/templates/
</code>```

Adding the spring.thymeleaf.prefix value worked for me.

For more information about the solution:

https://github.com/spring-projects/spring-boot/issues/34#issuecomment-316295791

Body:
If you are using Spring Tool Suite 4, you need to implement the following in your application.properties to disable the cache from Thymeleaf:

spring.thymeleaf.cache=false
spring.thymeleaf.prefix=file:src/main/resources/templates/

Adding the spring.thymeleaf.prefix value worked for me.

For more information about the solution:

https://github.com/spring-projects/spring-boot/issues/34#issuecomment-316295791


问:
is cpu_online_mask integer value
There is this, cpu_online_mask macro defined in Linux Kernel, wanted to know what does it return?
does it return some integer value?

```<code>#define cpu_online_mask   ((const struct cpumask *)&__cpu_online_mask)
</code>```

https://elixir.bootlin.com/linux/latest/source/include/linux/cpumask.h#L96

or does it return a pointer to cpumask struct

```<code>typedef struct cpumask { DECLARE_BITMAP(bits, NR_CPUS); } cpumask_t;

</code>```

so that DECLARE_BITMAP(bits, NR_CPUS) = cpu_online_mask  ??

I didn't understand how member of struct "cpumask" DECLARE_BITMAP(bits, NR_CPUS) is initialized ?

答:
is cpu_online_mask integer value

No.

wanted to know what does it return?

A pointer to constant struct cpumask.

does it return some integer value?

No.

does it return a pointer to cpumask struct

Yes!

o that DECLARE_BITMAP(bits, NR_CPUS) = cpu_online_mask ?

No. It's just DECLARE_BITMAP from types.h. You could say that DECLARE_BITMAP(bits, NR_CPUS) defines cpu_online_mask->bits member.

how member of struct "cpumask" DECLARE_BITMAP(bits, NR_CPUS) is initialized ?

The variable __cpu_online_mask has no initializer in kernel/cpu.c.

*** The macro cpu_online_mask does not really "return" anything, the token in source code cpu_online_mask is literally replaced by the result of expansion. For example code like cpu_online_mask->bits[0] = 1; is replaced by ((const struct cpumask *)&__cpu_online_mask)->buts[0] = 1; and then compiled.

Title: is cpu_online_mask integer value

Body:
There is this, cpu_online_mask macro defined in Linux Kernel, wanted to know what does it return?
does it return some integer value?

#define cpu_online_mask   ((const struct cpumask *)&__cpu_online_mask)

https://elixir.bootlin.com/linux/latest/source/include/linux/cpumask.h#L96

or does it return a pointer to cpumask struct

typedef struct cpumask { DECLARE_BITMAP(bits, NR_CPUS); } cpumask_t;

so that DECLARE_BITMAP(bits, NR_CPUS) = cpu_online_mask  ??

I didn't understand how member of struct "cpumask" DECLARE_BITMAP(bits, NR_CPUS) is initialized ?


问:
Merging NPM dependancy with a VUE.js Javascript Project
For a particular case in a Vue.js and JavaScript project a NPM package dependency have to be merge with the current JavaScript code base.

In that specific case, the NPM package should not be part of the nodes_modules folder anymore but rather be part of the JavaScript code itself.

In that case as both codebases will grow together in the future. (Independently from the original NPM package and not as a Fork)

How can I merge or fusion a NPM package to a Javascript project?

Additional Details:

The library that need to be merge is OIDC client. It's an open source project "Archived" by it's author (So no possibility to create Pull Request for a new release).

It is use to create a SSO for an internal project. This library has been retain by architect the for specific need of the project and there is no other option than this one.

There is no "internal package manager" available in this company

I don't want to host the fork on my personal Github and manage the package on NPM website

答:
After many attempt to solve this problem, it turn out that Patch-Package do the best job to merge a dependency by simply patching over instead of forking.

Syntax is pretty simple and it integrate very well with NPM:

Installation: npm i patch-package

Modify the code of your dependency directly in node_modules folder

Run npx patch-package some-package where some-package is the name of your package to patch

https://github.com/ds300/patch-package

Documentation: https://github.com/ds300/patch-package


问:
how to get data from the sublinks array
I need to get all the values for substitution in ng For, I did, but outputs only the first elements

info.component.html

```<code> <div *ngFor="let infoItem of infoItems" class="info__item">
        <div class="info__title">{{ infoItem.title }}</div>
        <ul class="info__list">
          <li class="info__list_item"><a href="#" class="info__link">{{ infoItem.sublinks[].title }}</a></li>
        </ul>
 </div>
</code>```

info.items.ts

```<code>export const INFO_ITEMS: IInfoItem[] = [
  {
    title: 'Company',
    sublinks: [
      {
        title: 'About CyberMetals',
      },
      {
        title: 'Careers',
      },
    ],
  },
  {
    title: 'My Account',
    sublinks: [
      {
        title: 'Registration',
      },
      {
        title: 'Account Login',
      },
    ],
  },
</code>```

答:
You need another *ngFor for the sublinks[] as it's also an array.
The HMTL should be like this:

{{ infoItem.title }}

       {{ sublinks.title }}

```

Title: how to get data from the sublinks array

Body:
I need to get all the values for substitution in ng For, I did, but outputs only the first elements

info.component.html

{{ infoItem.title }}

{{ infoItem.sublinks[].title }}

info.items.ts

export const INFO_ITEMS: IInfoItem[] = [
  {
    title: 'Company',
    sublinks: [
      {
        title: 'About CyberMetals',
      },
      {
        title: 'Careers',
      },
    ],
  },
  {
    title: 'My Account',
    sublinks: [
      {
        title: 'Registration',
      },
      {
        title: 'Account Login',
      },
    ],
  },

Body:
You need another *ngFor for the sublinks[] as it's also an array.
The HMTL should be like this:

<div *ngFor="let infoItem of infoItems" class="info__item">
  <div class="info__title">{{ infoItem.title }}</div>
  <ul class="info__list">
    <div *ngFor="let sublinks of infoItem.sublinks" class="info__item">
     <li class="info__list_item">
       <a href="#" class="info__link">{{ sublinks.title }}</a>
     </li>
    </div>
  </ul>
</div>


问:
How can I return data from a .json file with Discord.py
I want to store data in a .json file, and I want to also be able to fetch this data by using a discord bot using discord.py</p>

答:
I wouldn't use json, but instead use a database like MongoDB

Still want to use json? Use the json module that is built in to python.


问:
While installing Andorid studio AVD An error occurred while preparing SDK package Google APIs Intel x86 Atom System Image: Read timed out
Error Android Studio

Packages to install:

Google APIs Intel x86 Atom System Image (system-images;android-30;google_apis;x86)

Preparing "Install Google APIs Intel x86 Atom System Image (revision: 10)".
Downloading https://dl.google.com/android/repository/sys-img/google_apis/x86-30_r10.zip
An error occurred while preparing SDK package Google APIs Intel x86 Atom System Image: Read timed out.
"Install Google APIs Intel x86 Atom System Image (revision: 10)" failed.
Failed packages:

Google APIs Intel x86 Atom System Image (system-images;android-30;google_apis;x86)

答:
error when install AVD in Android studio

I did a lot of research on this topic until I came to the following conclusion and solved my problem

This error occurs when your system is unable to access Google's servers.

Unfortunately, Google has banned some countries and even with VPn it can not be bypassed, you have to use DNS. Set these Dns in your Windows: 178.22.122.100 & 185.51.200.2 .

this link help you to change or set Dns in Windows (This is very simple for programmers):
change dns in windows

This is a very disgusting thing by Google that limits programmers because of their nationality


问:
primefaces p:schedule allowparallel events at move event
I want to be able to drag an event even though there is a parallel event at the same time.
If the start-end period of the events are different then the ui let me move the event. But ifthe two events have a parallel window px first one 10-12 and second one 11-12 then it does not allow me to do the move.
From the back-end code i can do it though</p>

答:
The solution is to go at the backend and at each event to set at true the proeprty OverlapAllowed.

```<code>defaultScheduleEvent.setOverlapAllowed(true);
</code>```

Body:
The solution is to go at the backend and at each event to set at true the proeprty OverlapAllowed.

defaultScheduleEvent.setOverlapAllowed(true);


问:
VAR model selection in R
I have employed the automatic selection procedure which suggest VAR(2).

```<code>> VARselect(dlogdata,lag.max=10,type="const")
$selection
AIC(n)  HQ(n)  SC(n) FPE(n)
     8      2      2      4
</code>```

However, when checking for white noise, there are significant auto-correlations.

So, I have been increasing the order of the VAR model, until there are no significant auto correlations. I came to VAR(6):

This seems like a very not parsimonious model.

QUESTIONS:

How should I choose the best model? How can I compare the goodness of fit of VAR model with different order?

How can I validate the model?

答:
If you are interested in serially correlated errors you must perform a jointed serial test for all the model. Considering the next example, using Canada data set, only considering the first 2 variable in data, let assume optimal lag is 3, then we have:

library(vars)
#> Loading required package: MASS
#> Loading required package: strucchange
#> Loading required package: zoo
#>
#> Attaching package: 'zoo'
#> The following objects are masked from 'package:base':
#>
#>     as.Date, as.Date.numeric
#> Loading required package: sandwich
#> Loading required package: urca
#> Loading required package: lmtest
library(magrittr)
data("Canada")
model <- VAR(Canada[,1:2],3)
```
<p>Then perform the Portmanteau test</p>
```serial.test(model)
#>
#>  Portmanteau Test (asymptotic)
#>
#> data:  Residuals of VAR object model
#> Chi-squared = 35.009, df = 52, p-value = 0.966
```
<p>We can check residuals:</p>
```plot(serial.test(model))
```

Created on 2022-02-11 by the reprex package (v1.0.0)

vars::VARselect() only select the best model based on information criteria (IC), is has nothing to do with serial correlated problem. Model selected based in AIC, for example, only guaranteed that your error are minimal.

Title: VAR model selection in R

Body:
I have employed the automatic selection procedure which suggest VAR(2).

> VARselect(dlogdata,lag.max=10,type="const")
$selection
AIC(n)  HQ(n)  SC(n) FPE(n)
     8      2      2      4

However, when checking for white noise, there are significant auto-correlations.

So, I have been increasing the order of the VAR model, until there are no significant auto correlations. I came to VAR(6):

This seems like a very not parsimonious model.

QUESTIONS:

How should I choose the best model? How can I compare the goodness of fit of VAR model with different order?

How can I validate the model?

Body:
If you are interested in serially correlated errors you must perform a jointed serial test for all the model. Considering the next example, using Canada data set, only considering the first 2 variable in data, let assume optimal lag is 3, then we have:

library(vars)
#> Loading required package: MASS
#> Loading required package: strucchange
#> Loading required package: zoo
#>
#> Attaching package: 'zoo'
#> The following objects are masked from 'package:base':
#>
#>     as.Date, as.Date.numeric
#> Loading required package: sandwich
#> Loading required package: urca
#> Loading required package: lmtest
library(magrittr)
data("Canada")
model <- VAR(Canada[,1:2],3)

Then perform the Portmanteau test

serial.test(model)
#>
#>  Portmanteau Test (asymptotic)
#>
#> data:  Residuals of VAR object model
#> Chi-squared = 35.009, df = 52, p-value = 0.966

We can check residuals:

plot(serial.test(model))

Created on 2022-02-11 by the reprex package (v1.0.0)

vars::VARselect() only select the best model based on information criteria (IC), is has nothing to do with serial correlated problem. Model selected based in AIC, for example, only guaranteed that your error are minimal.