问:
No native splash screen registered for given view controller. Call 'SplashScreen.show' for given view controller first in expo
Splash Screen was working fine, but suddenly it started to warn like this. I don't know what is affecting it. Help me with it.

App.js

```<code>import React, { useState } from 'react';
import { Platform } from 'react-native';
import * as SecureStore from 'expo-secure-store';
import * as SplashScreen from 'expo-splash-screen';
import axios from 'axios';

// Navigation
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator, TransitionPresets } from '@react-navigation/stack';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';

import { AuthContext } from './src/AuthContext';
import * as Icons from 'react-native-heroicons/outline'
import * as IconsSolid from 'react-native-heroicons/solid'
import { BASE_API_URL } from './src/Config';

// Screens
import LoginScreen from './screens/LoginScreen';
import FeedScreen from './screens/FeedScreen';
import PeopleScreen from './screens/PeopleScreen';
import AddPostScreen from './screens/AddPostScreen';
import ProfileScreen from './screens/ProfileScreen';
import SettingsScreen from './screens/SettingsScreen';

const Stack = Platform.OS == 'android' ? createStackNavigator() : createNativeStackNavigator();
const Tab = createBottomTabNavigator()

const tab_icon_color = '#000'
const tab_icon_size = 30

SplashScreen.preventAutoHideAsync()

function LoggedInTabs() {
  return (
    <Tab.Navigator
      screenOptions={{
        tabBarShowLabel: false,
        tabBarStyle: {
          height: 50,
        }
      }}
    >
      <Tab.Screen name="Feed" component={FeedScreen}
        options={{
          tabBarIcon: ({ focused }) => {
            return (
              focused ? <IconsSolid.HomeIcon color={tab_icon_color} size={tab_icon_size} /> : <Icons.HomeIcon color={tab_icon_color} size={tab_icon_size} />
            );
          }
        }}
      />
      <Tab.Screen name="People" component={PeopleScreen}
        options={{
          tabBarIcon: ({ focused }) => {
            return (
              focused ? <IconsSolid.UsersIcon color={tab_icon_color} size={tab_icon_size} /> : <Icons.UsersIcon color={tab_icon_color} size={tab_icon_size} />
            );
          }
        }}
      />
      <Tab.Screen name="Profile" component={ProfileScreen}
        options={{
          tabBarIcon: ({ focused }) => {
            return (
              focused ? <IconsSolid.UserIcon color={tab_icon_color} size={tab_icon_size} /> : <Icons.UserIcon color={tab_icon_color} size={tab_icon_size} />
            );
          }
        }}
      />
      <Tab.Screen name="Settings" component={SettingsScreen}
        options={{
          tabBarIcon: ({ focused }) => {
            return (
              focused ? <IconsSolid.Cog6ToothIcon color={tab_icon_color} size={tab_icon_size} /> : <Icons.Cog6ToothIcon color={tab_icon_color} size={tab_icon_size} />
            );
          }
        }}
      />
    </Tab.Navigator>
  );
}

function LoggedInStack() {
  return (
    <Stack.Navigator
      screenOptions={{
        gestureEnabled: true,
        gestureDirection: 'horizontal',
        ...TransitionPresets.SlideFromRightIOS,
      }}
      headerMore="float"
    >
    </Stack.Navigator>
  )
}

// Main Export
export default function App({ navigation }) {

  const [userGlobalToken, setUserGlobalToken] = useState(null)
  const [userGlobalData, setUserGlobalData] = useState(null)
  const [isAppLoading, setIsAppLoading] = useState(true)
  const [loginState, dispatch] = React.useReducer(
    (prevState, action) => {
      switch (action.type) {
        case 'RESTORE_TOKEN':
          return {
            ...prevState,
            userToken: action.token,
            userData: action.data,
            isLoading: false,
          };
        case 'SIGN_IN':
          return {
            ...prevState,
            isSignout: false,
            userToken: action.token,
            userData: action.data,
          };
        case 'SIGN_OUT':
          return {
            ...prevState,
            isSignout: true,
            userToken: null,
            userData: null,
          };
      }
    },
    {
      isLoading: true,
      isSignout: false,
      userToken: null,
      userData: null,
    }
  );

  React.useEffect(() => {
    // Fetch the token from storage then navigate to our appropriate place
    const bootstrapAsync = async () => {
      setIsAppLoading(true)

      let userToken;
      let userData;

      try {
        userToken = await SecureStore.getItemAsync('userToken');
        userData = await SecureStore.getItemAsync('userData')
      } catch (e) {
        console.log(e)
      }

      // CODE TO GET UPDATED DATA OF THE USER HERE AND VERIFY THE TOKEN
      setUserGlobalToken(JSON.parse(userToken))
      setUserGlobalData(JSON.parse(userData))
      setIsAppLoading(false)
      dispatch({ type: 'RESTORE_TOKEN', token: userToken, data: userData });
    };

    bootstrapAsync();
  }, []);

  React.useEffect(() => {
    const checkLoginState = async () => {
      if (loginState.isLoading == false) {
        try {
          await SplashScreen.hideAsync()
        } catch (e) {
          console.log('SplashHide '+e)
        }
      }
    }
    checkLoginState();
  }, [loginState.isLoading])

  const authContext = React.useMemo(
    () => ({
      signIn: async (userProfileToken, userProfileData) => {
        // Signing in the user and storing user token and user data in Secure Store
        try {
          await SecureStore.setItemAsync('userToken', JSON.stringify(userProfileToken))
          await SecureStore.setItemAsync('userData', JSON.stringify(userProfileData))
        } catch (e) {
          console.log(e)
        }

        setUserGlobalToken(userProfileToken)
        setUserGlobalData(userProfileData)

        dispatch({ type: 'SIGN_IN', token: userProfileToken, data: userProfileData });
      },
      // Sigining out user by making the Secure Store values null (token and data)
      signOut: async () => {
        try {
          await SecureStore.deleteItemAsync('userToken')
          await SecureStore.deleteItemAsync('userData')
        } catch (e) {
          console.log(e)
        }
        dispatch({ type: 'SIGN_OUT' })
      },
    }), []);

  // Returning the Stack (Conditional)
  return (
    <AuthContext.Provider
      value={{ ...authContext, userGlobalToken, userGlobalData, setUserGlobalData }}
    >
      <NavigationContainer>
        <Stack.Navigator
          screenOptions={{
            gestureEnabled: true,
            gestureDirection: 'horizontal',
            ...TransitionPresets.SlideFromRightIOS,
          }}
          headerMore="float"

        >
          {
            loginState.userToken == null ? (
              // Logged Out Stack
              <>
                <Stack.Screen name="Login" component={LoginScreen}
                  options={{ animationTypeForReplace: loginState.isSignout ? 'pop' : 'push', headerStyle: {height: 45} }}
                />
              </>
            ) : (
              <>
                {/* Logged In Stack */}
                <Stack.Screen name="Home" component={LoggedInTabs} options={{ headerShown: false }} />
                <Stack.Screen name="Add Post" component={AddPostScreen} options={{ presentation: 'modal' }} />
              </>
            )}
        </Stack.Navigator>
      </NavigationContainer>
    </AuthContext.Provider>
  );
}
</code>```

Also help me to show SpalshScreen while the Token is fetched from SecureStore. I tried but it still it shows Login screen and goes to Home stack.
I use Expo, and I use the SplashScreen from Expo.

Thanks in advance!

Body:
Splash Screen was working fine, but suddenly it started to warn like this. I don't know what is affecting it. Help me with it.

App.js

import React, { useState } from 'react';
import { Platform } from 'react-native';
import * as SecureStore from 'expo-secure-store';
import * as SplashScreen from 'expo-splash-screen';
import axios from 'axios';

// Navigation
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator, TransitionPresets } from '@react-navigation/stack';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';

import { AuthContext } from './src/AuthContext';
import * as Icons from 'react-native-heroicons/outline'
import * as IconsSolid from 'react-native-heroicons/solid'
import { BASE_API_URL } from './src/Config';

// Screens
import LoginScreen from './screens/LoginScreen';
import FeedScreen from './screens/FeedScreen';
import PeopleScreen from './screens/PeopleScreen';
import AddPostScreen from './screens/AddPostScreen';
import ProfileScreen from './screens/ProfileScreen';
import SettingsScreen from './screens/SettingsScreen';

const Stack = Platform.OS == 'android' ? createStackNavigator() : createNativeStackNavigator();
const Tab = createBottomTabNavigator()

const tab_icon_color = '#000'
const tab_icon_size = 30

SplashScreen.preventAutoHideAsync()

function LoggedInTabs() {
  return (
    <Tab.Navigator
      screenOptions={{
        tabBarShowLabel: false,
        tabBarStyle: {
          height: 50,
        }
      }}
    >
      <Tab.Screen name="Feed" component={FeedScreen}
        options={{
          tabBarIcon: ({ focused }) => {
            return (
              focused ? <IconsSolid.HomeIcon color={tab_icon_color} size={tab_icon_size} /> : <Icons.HomeIcon color={tab_icon_color} size={tab_icon_size} />
            );
          }
        }}
      />
      <Tab.Screen name="People" component={PeopleScreen}
        options={{
          tabBarIcon: ({ focused }) => {
            return (
              focused ? <IconsSolid.UsersIcon color={tab_icon_color} size={tab_icon_size} /> : <Icons.UsersIcon color={tab_icon_color} size={tab_icon_size} />
            );
          }
        }}
      />
      <Tab.Screen name="Profile" component={ProfileScreen}
        options={{
          tabBarIcon: ({ focused }) => {
            return (
              focused ? <IconsSolid.UserIcon color={tab_icon_color} size={tab_icon_size} /> : <Icons.UserIcon color={tab_icon_color} size={tab_icon_size} />
            );
          }
        }}
      />
      <Tab.Screen name="Settings" component={SettingsScreen}
        options={{
          tabBarIcon: ({ focused }) => {
            return (
              focused ? <IconsSolid.Cog6ToothIcon color={tab_icon_color} size={tab_icon_size} /> : <Icons.Cog6ToothIcon color={tab_icon_color} size={tab_icon_size} />
            );
          }
        }}
      />
    </Tab.Navigator>
  );
}

function LoggedInStack() {
  return (
    <Stack.Navigator
      screenOptions={{
        gestureEnabled: true,
        gestureDirection: 'horizontal',
        ...TransitionPresets.SlideFromRightIOS,
      }}
      headerMore="float"
    >
    </Stack.Navigator>
  )
}

// Main Export
export default function App({ navigation }) {

  const [userGlobalToken, setUserGlobalToken] = useState(null)
  const [userGlobalData, setUserGlobalData] = useState(null)
  const [isAppLoading, setIsAppLoading] = useState(true)
  const [loginState, dispatch] = React.useReducer(
    (prevState, action) => {
      switch (action.type) {
        case 'RESTORE_TOKEN':
          return {
            ...prevState,
            userToken: action.token,
            userData: action.data,
            isLoading: false,
          };
        case 'SIGN_IN':
          return {
            ...prevState,
            isSignout: false,
            userToken: action.token,
            userData: action.data,
          };
        case 'SIGN_OUT':
          return {
            ...prevState,
            isSignout: true,
            userToken: null,
            userData: null,
          };
      }
    },
    {
      isLoading: true,
      isSignout: false,
      userToken: null,
      userData: null,
    }
  );

  React.useEffect(() => {
    // Fetch the token from storage then navigate to our appropriate place
    const bootstrapAsync = async () => {
      setIsAppLoading(true)

      let userToken;
      let userData;

      try {
        userToken = await SecureStore.getItemAsync('userToken');
        userData = await SecureStore.getItemAsync('userData')
      } catch (e) {
        console.log(e)
      }

      // CODE TO GET UPDATED DATA OF THE USER HERE AND VERIFY THE TOKEN
      setUserGlobalToken(JSON.parse(userToken))
      setUserGlobalData(JSON.parse(userData))
      setIsAppLoading(false)
      dispatch({ type: 'RESTORE_TOKEN', token: userToken, data: userData });
    };

    bootstrapAsync();
  }, []);

  React.useEffect(() => {
    const checkLoginState = async () => {
      if (loginState.isLoading == false) {
        try {
          await SplashScreen.hideAsync()
        } catch (e) {
          console.log('SplashHide '+e)
        }
      }
    }
    checkLoginState();
  }, [loginState.isLoading])

  const authContext = React.useMemo(
    () => ({
      signIn: async (userProfileToken, userProfileData) => {
        // Signing in the user and storing user token and user data in Secure Store
        try {
          await SecureStore.setItemAsync('userToken', JSON.stringify(userProfileToken))
          await SecureStore.setItemAsync('userData', JSON.stringify(userProfileData))
        } catch (e) {
          console.log(e)
        }

        setUserGlobalToken(userProfileToken)
        setUserGlobalData(userProfileData)

        dispatch({ type: 'SIGN_IN', token: userProfileToken, data: userProfileData });
      },
      // Sigining out user by making the Secure Store values null (token and data)
      signOut: async () => {
        try {
          await SecureStore.deleteItemAsync('userToken')
          await SecureStore.deleteItemAsync('userData')
        } catch (e) {
          console.log(e)
        }
        dispatch({ type: 'SIGN_OUT' })
      },
    }), []);

  // Returning the Stack (Conditional)
  return (
    <AuthContext.Provider
      value={{ ...authContext, userGlobalToken, userGlobalData, setUserGlobalData }}
    >
      <NavigationContainer>
        <Stack.Navigator
          screenOptions={{
            gestureEnabled: true,
            gestureDirection: 'horizontal',
            ...TransitionPresets.SlideFromRightIOS,
          }}
          headerMore="float"

        >
          {
            loginState.userToken == null ? (
              // Logged Out Stack
              <>
                <Stack.Screen name="Login" component={LoginScreen}
                  options={{ animationTypeForReplace: loginState.isSignout ? 'pop' : 'push', headerStyle: {height: 45} }}
                />
              </>
            ) : (
              <>
                {/* Logged In Stack */}
                <Stack.Screen name="Home" component={LoggedInTabs} options={{ headerShown: false }} />
                <Stack.Screen name="Add Post" component={AddPostScreen} options={{ presentation: 'modal' }} />
              </>
            )}
        </Stack.Navigator>
      </NavigationContainer>
    </AuthContext.Provider>
  );
}

Also help me to show SpalshScreen while the Token is fetched from SecureStore. I tried but it still it shows Login screen and goes to Home stack.
I use Expo, and I use the SplashScreen from Expo.

Thanks in advance!


来源: stackexchange

问:
error: OpenCV(4.7.0) FAILED: fs.is_open(). Can't open "EDSR_x3.pb" in function 'ReadProtoFromBinaryFile'
Im trying out this article. But it doesn't work as intended.

This is the Python code copied from the article:

```<code>import cv2
from cv2 import dnn_superres

# Create an SR object
sr = dnn_superres.DnnSuperResImpl_create()

# Read image
image = cv2.imread('./raw_data/input.png')

# Read the desired model
path = "EDSR_x3.pb"
sr.readModel(path)

# Set the desired model and scale to get correct pre- and post-processing
sr.setModel("edsr", 3)

# Upscale the image
result = sr.upsample(image)

# Save the image
cv2.imwrite("./raw_data/upscaled.png", result)
</code>```

But when I run it I get the error message:

```<code>error: OpenCV(4.7.0) /Users/runner/work/opencv-python/opencv-python/opencv/modules/dnn/src/caffe/caffe_io.cpp:1138: error: (-2:Unspecified error) FAILED: fs.is_open(). Can't open "EDSR_x3.pb" in function 'ReadProtoFromBinaryFile'
</code>```

I'm using OpenCV(4.7.0) (the contrib package), I downloaded the "EDSR_x3.pb" model which is on the same folder as the code, and I'm using the input image from the model's GitHub repo.

Does anyone know why it doesn't work or has the same issue?

ContentLicense: CC BY-SA 4.0

Body:
Im trying out this article. But it doesn't work as intended.

This is the Python code copied from the article:

import cv2
from cv2 import dnn_superres

# Create an SR object
sr = dnn_superres.DnnSuperResImpl_create()

# Read image
image = cv2.imread('./raw_data/input.png')

# Read the desired model
path = "EDSR_x3.pb"
sr.readModel(path)

# Set the desired model and scale to get correct pre- and post-processing
sr.setModel("edsr", 3)

# Upscale the image
result = sr.upsample(image)

# Save the image
cv2.imwrite("./raw_data/upscaled.png", result)

But when I run it I get the error message:

error: OpenCV(4.7.0) /Users/runner/work/opencv-python/opencv-python/opencv/modules/dnn/src/caffe/caffe_io.cpp:1138: error: (-2:Unspecified error) FAILED: fs.is_open(). Can't open "EDSR_x3.pb" in function 'ReadProtoFromBinaryFile'

I'm using OpenCV(4.7.0) (the contrib package), I downloaded the "EDSR_x3.pb" model which is on the same folder as the code, and I'm using the input image from the model's GitHub repo.

Does anyone know why it doesn't work or has the same issue?


问:
How to Failed to open TCP connection to web.archive.org:443 (Connection refused - connect(2) for "web.archive.org" port 443)
I had an error downloading the wayback machine site. When entering the command to download the site from webArchive, the following error appears (Connection refused - connect(2) for "web.archive.org" port 443) was empty and was removed.I used the following command for the download site docker run --rm -it -v $PWD/websites:/websites hartator/wayback-machine-downloader nchealthyschools.org --to 20191124012453 -c 5. Please help to download the site.

I downloaded a JSON list of the site and tried to extract each link by command wayback_machine_downloader URLS_LINK --exact-url --directory /root/websites/nchealthyschools.org. The same error knocks out


问:
Python cannot import 'load_image_sync' from 'easy_pil'
I am trying to upload online my discord bot, but when I run my python script I have this error :
" ImportError: cannot import name 'load_image_sync' from 'easy_pil' "

It works well in local so I don't know what is the problem...

Here is my code :

```<code>import discord
import random
from discord import File
from discord.ext import commands
from easy_pil import Editor, load_image_sync, Font

bot = commands.Bot(command_prefix=".", intents=discord.Intents.all())

@bot.event
async def on_ready():
    print("Bot is ready to use...")

@bot.event
async def on_member_join(member):

    channel = member.guild.system_channel

    background = Editor("GrimWelcome.png")
    profile_img = await load_image_async(str(member.avatar.url))
</code>```

Use load_image_async with easy-pil but it cannot be imported.

Body:
I am trying to upload online my discord bot, but when I run my python script I have this error :
" ImportError: cannot import name 'load_image_sync' from 'easy_pil' "

It works well in local so I don't know what is the problem...

Here is my code :

import discord
import random
from discord import File
from discord.ext import commands
from easy_pil import Editor, load_image_sync, Font

bot = commands.Bot(command_prefix=".", intents=discord.Intents.all())

@bot.event
async def on_ready():
    print("Bot is ready to use...")

@bot.event
async def on_member_join(member):

    channel = member.guild.system_channel

    background = Editor("GrimWelcome.png")
    profile_img = await load_image_async(str(member.avatar.url))

Use load_image_async with easy-pil but it cannot be imported.


问:
Font resource ID #0x7f090008 could not be retrieved
In crashlytics I saw crashes with Fatal Exception: android.content.res.Resources$NotFoundException Font resource ID #0x7f090008 could not be retrieved. in many devices with different api versions. But, when I tested in my devices and emulators, there is no crash at all. The crash is happening inside recycler view adapter's onBind() method. I have fonts folder with xml and ttf type fonts.


问:
Is it secure to send a CSRF token from server to clients in a GET request response body
Adding CSRF tokens to my node back-end & react front-end app that uses express-sessions.

The client needs to request a new token anytime it loads a form. Is it secure to have a route, lets say my.api.com/token, and allow the client to make a GET request to that endpoint for a token that is sent back in the body of the response? (This app will be strictly HTTPS)


问:
JS: append a node to its parent in a for loop
My end goal is to make executable js code in the HTML body that can directly interact with DOMs such as this:

```<code><body>
  var h = "hello";
  if(h == "hello") {
    <p>True!</p>
  } else {
    <p>False!</p>
  }
</body>
</code>```

I made a lot of prototyping and even though what I did in the past worked, nested DOMs broke the code so I'm writing it from scratch again.

I ended up with a function that stores in a variable the content of the body. This variable returns a body object that got in it every child elements, some with the name "text" that refers to all the text in the body that's not the content of a DOM, which is in my case the JS code.

What I'm thinking about is to add to a string all the code and the objects, then eval the string.

I made a for loop that passes the body object's content. There are 2 scenarios: the sub object is a text node, then I want to add to a string variable the text node's content, or it's a node that is not a text node, then I want to append it to its parent.

I ended up with this code:

```<code>function main() {

    var base = $("body").contents();
    $("body").empty();
    let str = "";
    for (let i = 0; i < base.length; i++) {
        if(base[i].toString() == "[object Text]") {
            str+= base[i].data
        } else {
            str+= "$(" + parentnode + ").append(" + base[i] + ");";
        }
    }
    eval(str);
}
</code>```

The problem is that I don't know how to navigate in an object, for example the nodes has properties like "parentNode". The syntax base[I].parentNode returns in the console that it's not define. And I don't know if I should append the value of the property "innerHTML" that is present in the nodes property, or if I should append the node object itself. I'm a bit lost at this point... What do you think about it?

Body:
My end goal is to make executable js code in the HTML body that can directly interact with DOMs such as this:

  var h = "hello";
  if(h == "hello") {

True!

  } else {

False!

  }

I made a lot of prototyping and even though what I did in the past worked, nested DOMs broke the code so I'm writing it from scratch again.

I ended up with a function that stores in a variable the content of the body. This variable returns a body object that got in it every child elements, some with the name "text" that refers to all the text in the body that's not the content of a DOM, which is in my case the JS code.

What I'm thinking about is to add to a string all the code and the objects, then eval the string.

I made a for loop that passes the body object's content. There are 2 scenarios: the sub object is a text node, then I want to add to a string variable the text node's content, or it's a node that is not a text node, then I want to append it to its parent.

I ended up with this code:

function main() {

    var base = $("body").contents();
    $("body").empty();
    let str = "";
    for (let i = 0; i < base.length; i++) {
        if(base[i].toString() == "[object Text]") {
            str+= base[i].data
        } else {
            str+= "$(" + parentnode + ").append(" + base[i] + ");";
        }
    }
    eval(str);
}

The problem is that I don't know how to navigate in an object, for example the nodes has properties like "parentNode". The syntax base[I].parentNode returns in the console that it's not define. And I don't know if I should append the value of the property "innerHTML" that is present in the nodes property, or if I should append the node object itself. I'm a bit lost at this point... What do you think about it?


问:
Is it a problem that BufferBlock is always on?
I need log provider for my .NET Core project (especially, I want to send logs to Graylog with HTTP) and I searched all log repos on GitHub to find a good idea.

At the end of the day I found a few solutions and wanted to use the one that has BufferBlock;
But I have some questions.

Firstly, here is the code.

```<code>using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;

namespace Gelf.Extensions.Logging
{
    public class GelfMessageProcessor
    {
        private readonly BufferBlock<GelfMessage> _messageBuffer;

        private Task _processorTask = Task.CompletedTask;

        public GelfMessageProcessor(IGelfClient gelfClient)
        {
            GelfClient = gelfClient;
            _messageBuffer = new BufferBlock<GelfMessage>(new DataflowBlockOptions
            {
                BoundedCapacity = 10000
            });
        }

        internal IGelfClient GelfClient { get; set; }

        public void Start()
        {
            _processorTask = Task.Run(StartAsync);
        }

        private async Task StartAsync()
        {
            while (!_messageBuffer.Completion.IsCompleted)
            {
                try
                {
                    var message = await _messageBuffer.ReceiveAsync();
                    await GelfClient.SendMessageAsync(message);
                }
                catch (InvalidOperationException)
                {
                    // The source completed without providing data to receive.
                }
                catch (Exception ex)
                {
                    Debug.Fail("Unhandled exception while sending GELF message.",
                        ex.ToString());
                }
            }
        }

        public void Stop()
        {
            _messageBuffer.Complete();
            _processorTask.Wait();
        }

        public void SendMessage(GelfMessage message)
        {
            if (!_messageBuffer.Post(message))
            {
                Debug.Fail("Failed to add GELF message to buffer.");
            }
        }
    }
}
</code>```

If you check this code, you can see that we have a BufferBlock where we have sent messages. And this block receive our message and send in a while loop, this while loop never stop in this project because it’s never been triggered as IsCompleted.

My first question is;

Its BufferBlock is looking always on, should I close this block?

Is it normal to being always on? If it stays on through the process, how much memory does it consume?

What would happen if no message came to BufferBlock for few hours?

I want to use this, but I’m confused for this two questions, I couldn't find any answer. I can't predict what kind of problems it will cause unless I find the answers.

Also, I am open to suggestions about how to send logs to Graylog with HTTP and without using BufferBlock, maybe we can find a different way. (Please don't suggest me NuGet packages, I have to do without packages.)

Body:
I need log provider for my .NET Core project (especially, I want to send logs to Graylog with HTTP) and I searched all log repos on GitHub to find a good idea.

At the end of the day I found a few solutions and wanted to use the one that has BufferBlock;
But I have some questions.

Firstly, here is the code.

using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;

namespace Gelf.Extensions.Logging
{
    public class GelfMessageProcessor
    {
        private readonly BufferBlock<GelfMessage> _messageBuffer;

        private Task _processorTask = Task.CompletedTask;

        public GelfMessageProcessor(IGelfClient gelfClient)
        {
            GelfClient = gelfClient;
            _messageBuffer = new BufferBlock<GelfMessage>(new DataflowBlockOptions
            {
                BoundedCapacity = 10000
            });
        }

        internal IGelfClient GelfClient { get; set; }

        public void Start()
        {
            _processorTask = Task.Run(StartAsync);
        }

        private async Task StartAsync()
        {
            while (!_messageBuffer.Completion.IsCompleted)
            {
                try
                {
                    var message = await _messageBuffer.ReceiveAsync();
                    await GelfClient.SendMessageAsync(message);
                }
                catch (InvalidOperationException)
                {
                    // The source completed without providing data to receive.
                }
                catch (Exception ex)
                {
                    Debug.Fail("Unhandled exception while sending GELF message.",
                        ex.ToString());
                }
            }
        }

        public void Stop()
        {
            _messageBuffer.Complete();
            _processorTask.Wait();
        }

        public void SendMessage(GelfMessage message)
        {
            if (!_messageBuffer.Post(message))
            {
                Debug.Fail("Failed to add GELF message to buffer.");
            }
        }
    }
}

If you check this code, you can see that we have a BufferBlock where we have sent messages. And this block receive our message and send in a while loop, this while loop never stop in this project because it’s never been triggered as IsCompleted.

My first question is;

Its BufferBlock is looking always on, should I close this block?

Is it normal to being always on? If it stays on through the process, how much memory does it consume?

What would happen if no message came to BufferBlock for few hours?

I want to use this, but I’m confused for this two questions, I couldn't find any answer. I can't predict what kind of problems it will cause unless I find the answers.

Also, I am open to suggestions about how to send logs to Graylog with HTTP and without using BufferBlock, maybe we can find a different way. (Please don't suggest me NuGet packages, I have to do without packages.)


问:
Add multiple marker on google map and show Infowindow whenever I click on any marker on google map
I want to able to add multiple marker on the google map and when I click on any of them, it will show an infoWindow the location of the marker. However, the issue I am facing is not able to enable the infoWindow to pop up when any of the marker is clicked.

Please see my codes below.

```<code><!DOCTYPE html>
<html>
    <body>
        <h1>My First Google Map Marker</h1>

        <div id="map" style="width: 100%;height: 400px;"></div>

        <script>

            const labels = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            let labelIndex = 0;

            function initMap() {
                const defaultLoc = { lat:1.31170, lng:103.77495 };
                const map = new google.maps.Map(document.getElementById("map"), {
                    zoom: 12,
                    center: defaultLoc
                });

                google.maps.event.addListener(map, "click", (event) => {
                    addMarker(event.latLng, map);
                })

                const marker = new google.maps.Marker({
                    position: { lat:1.31170, lng:103.77495 },
                    map: map,
                });

                var infoWindow = new google.maps.InfoWindow();

                google.maps.event.addListener(marker, "click", function (e) {

                        infoWindow.setContent("<p>Marker Location:" + marker.getPosition() + "</p>");
                        infoWindow.open(map, marker);

                });
            }

            function addMarker(location, map) {
                new google.maps.Marker({
                    position: location,
                    label: labels[labelIndex++ % labels.length],
                    map: map,
                });
            }

            window.initMap = initMap;

        </script>
        <script src="https://maps.googleapis.com/maps/api/js?key=<google map api key>&callback=initMap"></script>
    </body>
</html>
</code>```

Body:
I want to able to add multiple marker on the google map and when I click on any of them, it will show an infoWindow the location of the marker. However, the issue I am facing is not able to enable the infoWindow to pop up when any of the marker is clicked.

Please see my codes below.

<!DOCTYPE html>

My First Google Map Marker


问:
WebSocket-Sharp + Socket.io - Unable to Connect
So I've seen some people having issues with sending/receiving messages from Socket.io with WebSocket-Sharp, but I'm not seeing any issues with just connecting.

This is on a Windows 10 machine.  From a browser, I have no issues connecting to the Socket.io using some demo code.

I'm hoping someone has come across this, and has a solution :)

Edit: Less interested in this now that I've gotten this working with another library.  Hope the question helps someone else in the future though.

ws.Connect()

12/30/2022 10:09:14 AM|Fatal|<>c__DisplayClass17.<startReceiving>b__16|WebSocketSharp.WebSocketException: A non data frame is compressed.

ws.ConnectAsync()

12/30/2022 10:11:56 AM|Fatal|Ext.ReadBytesAsync|System.IO.IOException: Unable to read data from the transport connection: An established connection was aborted by the software in your host machine. ---> System.Net.Sockets.SocketException: An established connection was aborted by the software in your host machine

C# implementation of WebSocket-Sharp

```<code>using (var ws = new WebSocket("ws://localhost:1337/socket.io/?EIO=2&transport=websocket"))
{
   ws.Connect();
}
</code>```

NodeJS (excluded requires), this works from a browser.
(Express, NodeJS, Socket.io)

```<code>app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
    console.log('Something Connected.');
  socket.on('chat message', (msg) => {
    io.emit('chat message', msg);
    console.log(msg);
  });
  socket.on('disconnect', () => {
    console.log('Something Disconnected.');
  });
});

server.listen(1337, () => {
  console.log('listening on *:1337');
});
</code>```

Body:
So I've seen some people having issues with sending/receiving messages from Socket.io with WebSocket-Sharp, but I'm not seeing any issues with just connecting.

This is on a Windows 10 machine.  From a browser, I have no issues connecting to the Socket.io using some demo code.

I'm hoping someone has come across this, and has a solution :)

Edit: Less interested in this now that I've gotten this working with another library.  Hope the question helps someone else in the future though.

ws.Connect()

12/30/2022 10:09:14 AM|Fatal|<>c__DisplayClass17.<startReceiving>b__16|WebSocketSharp.WebSocketException: A non data frame is compressed.

ws.ConnectAsync()

12/30/2022 10:11:56 AM|Fatal|Ext.ReadBytesAsync|System.IO.IOException: Unable to read data from the transport connection: An established connection was aborted by the software in your host machine. ---> System.Net.Sockets.SocketException: An established connection was aborted by the software in your host machine

C# implementation of WebSocket-Sharp

using (var ws = new WebSocket("ws://localhost:1337/socket.io/?EIO=2&transport=websocket"))
{
   ws.Connect();
}

NodeJS (excluded requires), this works from a browser.
(Express, NodeJS, Socket.io)

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
    console.log('Something Connected.');
  socket.on('chat message', (msg) => {
    io.emit('chat message', msg);
    console.log(msg);
  });
  socket.on('disconnect', () => {
    console.log('Something Disconnected.');
  });
});

server.listen(1337, () => {
  console.log('listening on *:1337');
});


问:
Getting unintended output with requests.get() method when headers is used to fetch data from Github endpoint
I am trying to fetch some data from a Huggingface Datasets repository on Github using requests.get() method.

If I use the headers parameter in the .get() method, I am getting the wrong features downloaded as shown below.

```<code>import requests

MY_GITHUB_TOKEN = "XXXXXXXXXXXXXX"
header = {"Authorization": f"token {MY_GITHUB_TOKEN}"}

i =[]
for p in range(5):
    issues = requests.get(f"https://api.github.com/repos/huggingface/datasets/issues?page={p}&per_page=2", headers=header)
    i.extend(issues.json())
i
</code>```

```<code>['message',
 'documentation_url',
 'message',
 'documentation_url',
 'message',
 'documentation_url',
 'message',
 'documentation_url',
 'message',
 'documentation_url']
</code>```

If I remove the headers parameter in the .get() method, I am getting the correct features downloaded as shown below.

```<code>i =[]
for p in range(5):
    issues = requests.get(f"https://api.github.com/repos/huggingface/datasets/issues?page={p}&per_page=2")
    i.extend(issues.json())
i
</code>```

```<code>[{'url': 'https://api.github.com/repos/huggingface/datasets/issues/5396',
  'repository_url': 'https://api.github.com/repos/huggingface/datasets',
  'labels_url': 'https://api.github.com/repos/huggingface/datasets/issues/5396/labels{/name}',
  'comments_url': 'https://api.github.com/repos/huggingface/datasets/issues/5396/comments',
  'events_url': 'https://api.github.com/repos/huggingface/datasets/issues/5396/events',
  'html_url': 'https://github.com/huggingface/datasets/pull/5396',
  'id': 1514002934,
  'node_id': 'PR_kwDODunzps5GXMhp',
  'number': 5396,
  'title': 'Fix checksum verification',
  'user': {'login': 'daskol',
   'id': 9336514,
   'node_id': 'MDQ6VXNlcjkzMzY1MTQ=',
   'avatar_url': 'https://avatars.githubusercontent.com/u/9336514?v=4',
   'gravatar_id': '',
   'url': 'https://api.github.com/users/daskol',
   'html_url': 'https://github.com/daskol',
   'followers_url': 'https://api.github.com/users/daskol/followers',
   'following_url': 'https://api.github.com/users/daskol/following{/other_user}',
   'gists_url': 'https://api.github.com/users/daskol/gists{/gist_id}',
   'starred_url': 'https://api.github.com/users/daskol/starred{/owner}{/repo}',
   'subscriptions_url': 'https://api.github.com/users/daskol/subscriptions',
   'organizations_url': 'https://api.github.com/users/daskol/orgs',
   'repos_url': 'https://api.github.com/users/daskol/repos',
   'events_url': 'https://api.github.com/users/daskol/events{/privacy}',
   'received_events_url': 'https://api.github.com/users/daskol/received_events',
   'type': 'User',
   'site_admin': False},
  'labels': [],
  'state': 'open',
  'locked': False,
  'assignee': None,
  'assignees': [],
  'milestone': None,
  'comments': 0,
  'created_at': '2022-12-29T19:45:17Z',
  'updated_at': '2022-12-29T19:45:17Z',
  'closed_at': None,
  'author_association': 'NONE',
  'active_lock_reason': None,
  'draft': False,
  'pull_request': {'url': 'https://api.github.com/repos/huggingface/datasets/pulls/5396',
   'html_url': 'https://github.com/huggingface/datasets/pull/5396',
   'diff_url': 'https://github.com/huggingface/datasets/pull/5396.diff',
   'patch_url': 'https://github.com/huggingface/datasets/pull/5396.patch',
   'merged_at': None},
  'body': 'Expected checksum was verified against checksum dict (not checksum).',
  'reactions': {'url': 'https://api.github.com/repos/huggingface/datasets/issues/5396/reactions',
   'total_count': 0,
   '+1': 0,
   '-1': 0,
   'laugh': 0,
   'hooray': 0,
   'confused': 0,
   'heart': 0,
   'rocket': 0,
   'eyes': 0},
  'timeline_url': 'https://api.github.com/repos/huggingface/datasets/issues/5396/timeline',
  'performed_via_github_app': None,
  'state_reason': None},
 {'url': 'https://api.github.com/repos/huggingface/datasets/issues/5393',
  'repository_url': 'https://api.github.com/repos/huggingface/datasets',
  'labels_url': 'https://api.github.com/repos/huggingface/datasets/issues/5393/labels{/name}',
  'comments_url': 'https://api.github.com/repos/huggingface/datasets/issues/5393/comments',
  'events_url': 'https://api.github.com/repos/huggingface/datasets/issues/5393/events',
  'html_url': 'https://github.com/huggingface/datasets/pull/5393',
  'id': 1512908613,
  'node_id': 'PR_kwDODunzps5GTg0a',
  'number': 5393,
  'title': 'Finish Deprecating the `fs=` arg',
  'user': {'login': 'dconathan',
   'id': 15098095,
   'node_id': 'MDQ6VXNlcjE1MDk4MDk1',
   'avatar_url': 'https://avatars.githubusercontent.com/u/15098095?v=4',
   'gravatar_id': '',
   'url': 'https://api.github.com/users/dconathan',
   'html_url': 'https://github.com/dconathan',
   'followers_url': 'https://api.github.com/users/dconathan/followers',
   'following_url': 'https://api.github.com/users/dconathan/following{/other_user}',
   'gists_url': 'https://api.github.com/users/dconathan/gists{/gist_id}',
   'starred_url': 'https://api.github.com/users/dconathan/starred{/owner}{/repo}',
   'subscriptions_url': 'https://api.github.com/users/dconathan/subscriptions',
   'organizations_url': 'https://api.github.com/users/dconathan/orgs',
   'repos_url': 'https://api.github.com/users/dconathan/repos',
   'events_url': 'https://api.github.com/users/dconathan/events{/privacy}',
   'received_events_url': 'https://api.github.com/users/dconathan/received_events',
   'type': 'User',
   'site_admin': False},
  'labels': [],
  'state': 'open',
  'locked': False,
  'assignee': None,
  'assignees': [],
  'milestone': None,
  'comments': 2,
  'created_at': '2022-12-28T15:33:17Z',
  'updated_at': '2022-12-29T14:13:04Z',
  'closed_at': None,
  'author_association': 'NONE',
  'active_lock_reason': None,
  'draft': False,
  'pull_request': {'url': 'https://api.github.com/repos/huggingface/datasets/pulls/5393',
..........................
.......................................
</code>```

But without headers (token authentication parameter) the process is very slow and is getting timed out (given number of pages and number of items per page I am trying to download are large). As per the documentation of requests library and Github, I guess I have defined the headers and token parameters correctly. Any inputs what is the problem?

Body:
I am trying to fetch some data from a Huggingface Datasets repository on Github using requests.get() method.

If I use the headers parameter in the .get() method, I am getting the wrong features downloaded as shown below.

import requests

MY_GITHUB_TOKEN = "XXXXXXXXXXXXXX"
header = {"Authorization": f"token {MY_GITHUB_TOKEN}"}

i =[]
for p in range(5):
    issues = requests.get(f"https://api.github.com/repos/huggingface/datasets/issues?page={p}&per_page=2", headers=header)
    i.extend(issues.json())
i

['message',
 'documentation_url',
 'message',
 'documentation_url',
 'message',
 'documentation_url',
 'message',
 'documentation_url',
 'message',
 'documentation_url']

If I remove the headers parameter in the .get() method, I am getting the correct features downloaded as shown below.

i =[]
for p in range(5):
    issues = requests.get(f"https://api.github.com/repos/huggingface/datasets/issues?page={p}&per_page=2")
    i.extend(issues.json())
i

[{'url': 'https://api.github.com/repos/huggingface/datasets/issues/5396',
  'repository_url': 'https://api.github.com/repos/huggingface/datasets',
  'labels_url': 'https://api.github.com/repos/huggingface/datasets/issues/5396/labels{/name}',
  'comments_url': 'https://api.github.com/repos/huggingface/datasets/issues/5396/comments',
  'events_url': 'https://api.github.com/repos/huggingface/datasets/issues/5396/events',
  'html_url': 'https://github.com/huggingface/datasets/pull/5396',
  'id': 1514002934,
  'node_id': 'PR_kwDODunzps5GXMhp',
  'number': 5396,
  'title': 'Fix checksum verification',
  'user': {'login': 'daskol',
   'id': 9336514,
   'node_id': 'MDQ6VXNlcjkzMzY1MTQ=',
   'avatar_url': 'https://avatars.githubusercontent.com/u/9336514?v=4',
   'gravatar_id': '',
   'url': 'https://api.github.com/users/daskol',
   'html_url': 'https://github.com/daskol',
   'followers_url': 'https://api.github.com/users/daskol/followers',
   'following_url': 'https://api.github.com/users/daskol/following{/other_user}',
   'gists_url': 'https://api.github.com/users/daskol/gists{/gist_id}',
   'starred_url': 'https://api.github.com/users/daskol/starred{/owner}{/repo}',
   'subscriptions_url': 'https://api.github.com/users/daskol/subscriptions',
   'organizations_url': 'https://api.github.com/users/daskol/orgs',
   'repos_url': 'https://api.github.com/users/daskol/repos',
   'events_url': 'https://api.github.com/users/daskol/events{/privacy}',
   'received_events_url': 'https://api.github.com/users/daskol/received_events',
   'type': 'User',
   'site_admin': False},
  'labels': [],
  'state': 'open',
  'locked': False,
  'assignee': None,
  'assignees': [],
  'milestone': None,
  'comments': 0,
  'created_at': '2022-12-29T19:45:17Z',
  'updated_at': '2022-12-29T19:45:17Z',
  'closed_at': None,
  'author_association': 'NONE',
  'active_lock_reason': None,
  'draft': False,
  'pull_request': {'url': 'https://api.github.com/repos/huggingface/datasets/pulls/5396',
   'html_url': 'https://github.com/huggingface/datasets/pull/5396',
   'diff_url': 'https://github.com/huggingface/datasets/pull/5396.diff',
   'patch_url': 'https://github.com/huggingface/datasets/pull/5396.patch',
   'merged_at': None},
  'body': 'Expected checksum was verified against checksum dict (not checksum).',
  'reactions': {'url': 'https://api.github.com/repos/huggingface/datasets/issues/5396/reactions',
   'total_count': 0,
   '+1': 0,
   '-1': 0,
   'laugh': 0,
   'hooray': 0,
   'confused': 0,
   'heart': 0,
   'rocket': 0,
   'eyes': 0},
  'timeline_url': 'https://api.github.com/repos/huggingface/datasets/issues/5396/timeline',
  'performed_via_github_app': None,
  'state_reason': None},
 {'url': 'https://api.github.com/repos/huggingface/datasets/issues/5393',
  'repository_url': 'https://api.github.com/repos/huggingface/datasets',
  'labels_url': 'https://api.github.com/repos/huggingface/datasets/issues/5393/labels{/name}',
  'comments_url': 'https://api.github.com/repos/huggingface/datasets/issues/5393/comments',
  'events_url': 'https://api.github.com/repos/huggingface/datasets/issues/5393/events',
  'html_url': 'https://github.com/huggingface/datasets/pull/5393',
  'id': 1512908613,
  'node_id': 'PR_kwDODunzps5GTg0a',
  'number': 5393,
  'title': 'Finish Deprecating the `fs=` arg',
  'user': {'login': 'dconathan',
   'id': 15098095,
   'node_id': 'MDQ6VXNlcjE1MDk4MDk1',
   'avatar_url': 'https://avatars.githubusercontent.com/u/15098095?v=4',
   'gravatar_id': '',
   'url': 'https://api.github.com/users/dconathan',
   'html_url': 'https://github.com/dconathan',
   'followers_url': 'https://api.github.com/users/dconathan/followers',
   'following_url': 'https://api.github.com/users/dconathan/following{/other_user}',
   'gists_url': 'https://api.github.com/users/dconathan/gists{/gist_id}',
   'starred_url': 'https://api.github.com/users/dconathan/starred{/owner}{/repo}',
   'subscriptions_url': 'https://api.github.com/users/dconathan/subscriptions',
   'organizations_url': 'https://api.github.com/users/dconathan/orgs',
   'repos_url': 'https://api.github.com/users/dconathan/repos',
   'events_url': 'https://api.github.com/users/dconathan/events{/privacy}',
   'received_events_url': 'https://api.github.com/users/dconathan/received_events',
   'type': 'User',
   'site_admin': False},
  'labels': [],
  'state': 'open',
  'locked': False,
  'assignee': None,
  'assignees': [],
  'milestone': None,
  'comments': 2,
  'created_at': '2022-12-28T15:33:17Z',
  'updated_at': '2022-12-29T14:13:04Z',
  'closed_at': None,
  'author_association': 'NONE',
  'active_lock_reason': None,
  'draft': False,
  'pull_request': {'url': 'https://api.github.com/repos/huggingface/datasets/pulls/5393',
..........................
.......................................

But without headers (token authentication parameter) the process is very slow and is getting timed out (given number of pages and number of items per page I am trying to download are large). As per the documentation of requests library and Github, I guess I have defined the headers and token parameters correctly. Any inputs what is the problem?


问:
Implementing factory pattern with abstract base class in python - Abstract class is not callable
I'm trying to implement a factory pattern whereby I can retrieve an instantiate a various similar classes based on input. If I have code something like this:

```<code>from abc import ABC, abstractmethod

class AbstractTranscoder(ABC):

    @abstractmethod
    def transcode():
        raise NotImplementedError

class Transcoder1(AbstractTranscoder):

    def transcode():
        ...

class TranscoderFactory:

    TRANSCODERS = {'transcoder1': Transcoder1}

    def get_transcoder(name: str) -> AbstractTranscoder:
        return TRANSCODERS[name]
</code>```

My goal is to be able to then use the factory pattern to retrieve the class as follows:

```<code>transcoder_class = TranscoderFactory().get_transcoder('transcoder1')
transcoder_object = transcoder_class()
</code>```

I think this will work, but the issue is because I'm using Type Annotations, the IDE yells at me 'AbstractTranscoder object is not callable'. Is there a preferable way to implement this such that the IDE does not think I am trying to instantiate an Abstract class, but rather one of its concrete subclasses?

Thanks.

Body:
I'm trying to implement a factory pattern whereby I can retrieve an instantiate a various similar classes based on input. If I have code something like this:

from abc import ABC, abstractmethod

class AbstractTranscoder(ABC):

    @abstractmethod
    def transcode():
        raise NotImplementedError

class Transcoder1(AbstractTranscoder):

    def transcode():
        ...

class TranscoderFactory:

    TRANSCODERS = {'transcoder1': Transcoder1}

    def get_transcoder(name: str) -> AbstractTranscoder:
        return TRANSCODERS[name]

My goal is to be able to then use the factory pattern to retrieve the class as follows:

transcoder_class = TranscoderFactory().get_transcoder('transcoder1')
transcoder_object = transcoder_class()

I think this will work, but the issue is because I'm using Type Annotations, the IDE yells at me 'AbstractTranscoder object is not callable'. Is there a preferable way to implement this such that the IDE does not think I am trying to instantiate an Abstract class, but rather one of its concrete subclasses?

Thanks.


问:
Dispose and Flush method in MsftFileSystemImage (Powershell script)
I found a Powershell Script that burn the Zip File from one location $Path = "C:\temp\test.zip" to CD ROM. The script program work fine. I try to enchance the program by delete the zip file in the $Path after the script complete but run into error.

Remove-Item : Cannot remove item "C:\temp\test.zip": The process cannot
access the file "C:\temp\test.zip" because it is being used by another proces

This is my code:

```<code>Function Out-CD
{
    [CmdletBinding()]

    param (
        $Path = 'C:\temp\test.zip',
        $CdTitle = 'data'
    )

    BEGIN
    {
        try
        {
            Write-Verbose 'Creating COM Objects.' -Verbose

            $DiskMaster      = New-Object -com IMAPI2.MsftDiscMaster2
            $DiscRecorder    = New-Object -com IMAPI2.MsftDiscRecorder2
            $FileSystemImage = New-Object -com IMAPI2FS.MsftFileSystemImage
            $DiscFormatData  = New-Object -com IMAPI2.MsftDiscFormat2Data
        }
        catch
        {
            $err = $Error[0]
            Write-Error $err
            return
        }
    }

    PROCESS
    {
        Write-Verbose 'Initializing Disc Recorder.' -Verbose
        $id = $DiskMaster.Item(0)
        $DiscRecorder.InitializeDiscRecorder($id)

        Write-Verbose 'Assigning recorder.' -Verbose
        $dir = $FileSystemImage.Root
        $DiscFormatData.Recorder = $DiscRecorder
        $DiscFormatData.ClientName = 'PowerShell Burner'

        Write-Verbose 'Multisession?' -Verbose
        if (-not $DiscFormatData.MediaHeuristicallyBlank)
        {
        Write-Verbose 'inside if condition' -Verbose
            try
            {
                $FileSystemImage.MultisessionInterfaces = $DiscFormatData.MultisessionInterfaces
                Write-Verbose 'Importing existing session.' -Verbose

                $FileSystemImage.ImportFileSystem() | Out-Null
            }
            catch
            {
                $err = $Error[0]
                Write-Error $err
                return
            }
        }
        else
        {
            Write-Verbose 'Empty medium.' -Verbose
            $FileSystemImage.ChooseImageDefaults($DiscRecorder)
            $FileSystemImage.VolumeName = $CdTitle
        }

        Write-Verbose "Adding directory tree ($Path)." -Verbose
        $dir.AddTree($Path, $true)

        Write-Verbose 'Creating image.' -Verbose
        $result = $FileSystemImage.CreateResultImage()
        $stream = $result.ImageStream

        Write-Verbose 'Burning.' -Verbose
        $DiscFormatData.Write($stream)

        Write-Verbose 'Done.' -Verbose
    }

    END {
         //My Code
       Remove-Item -Path $Path -Force -Recurse
    }
}
</code>```

I am wondering is that because MsftFileSystemImage is still running and it needed to be flush() or close() or delete()? I looked at the Microsoft Website but cannot find any method that I mentioned above

Body:
I found a Powershell Script that burn the Zip File from one location $Path = "C:\temp\test.zip" to CD ROM. The script program work fine. I try to enchance the program by delete the zip file in the $Path after the script complete but run into error.

Remove-Item : Cannot remove item "C:\temp\test.zip": The process cannot
access the file "C:\temp\test.zip" because it is being used by another proces

This is my code:

Function Out-CD
{
    [CmdletBinding()]

    param (
        $Path = 'C:\temp\test.zip',
        $CdTitle = 'data'
    )

    BEGIN
    {
        try
        {
            Write-Verbose 'Creating COM Objects.' -Verbose

            $DiskMaster      = New-Object -com IMAPI2.MsftDiscMaster2
            $DiscRecorder    = New-Object -com IMAPI2.MsftDiscRecorder2
            $FileSystemImage = New-Object -com IMAPI2FS.MsftFileSystemImage
            $DiscFormatData  = New-Object -com IMAPI2.MsftDiscFormat2Data
        }
        catch
        {
            $err = $Error[0]
            Write-Error $err
            return
        }
    }

    PROCESS
    {
        Write-Verbose 'Initializing Disc Recorder.' -Verbose
        $id = $DiskMaster.Item(0)
        $DiscRecorder.InitializeDiscRecorder($id)

        Write-Verbose 'Assigning recorder.' -Verbose
        $dir = $FileSystemImage.Root
        $DiscFormatData.Recorder = $DiscRecorder
        $DiscFormatData.ClientName = 'PowerShell Burner'

        Write-Verbose 'Multisession?' -Verbose
        if (-not $DiscFormatData.MediaHeuristicallyBlank)
        {
        Write-Verbose 'inside if condition' -Verbose
            try
            {
                $FileSystemImage.MultisessionInterfaces = $DiscFormatData.MultisessionInterfaces
                Write-Verbose 'Importing existing session.' -Verbose

                $FileSystemImage.ImportFileSystem() | Out-Null
            }
            catch
            {
                $err = $Error[0]
                Write-Error $err
                return
            }
        }
        else
        {
            Write-Verbose 'Empty medium.' -Verbose
            $FileSystemImage.ChooseImageDefaults($DiscRecorder)
            $FileSystemImage.VolumeName = $CdTitle
        }

        Write-Verbose "Adding directory tree ($Path)." -Verbose
        $dir.AddTree($Path, $true)

        Write-Verbose 'Creating image.' -Verbose
        $result = $FileSystemImage.CreateResultImage()
        $stream = $result.ImageStream

        Write-Verbose 'Burning.' -Verbose
        $DiscFormatData.Write($stream)

        Write-Verbose 'Done.' -Verbose
    }

    END {
         //My Code
       Remove-Item -Path $Path -Force -Recurse
    }
}

I am wondering is that because MsftFileSystemImage is still running and it needed to be flush() or close() or delete()? I looked at the Microsoft Website but cannot find any method that I mentioned above


问:
Use Beam Search in encoder-decoder
How can tfa.seq2seq.BeamSearchDecoder, for example, be used with a simple encoder-decoder architecture? Suppose the task is machine translation, where the encoder returns a vector representation of the input sequence. The decoder uses Embedding, LSTM and Dense layers to translate the text word by word. It gets an error "Argument 'cell' (<keras.layers.rnn.lstm.LSTM object at 0x000002658BF13C40>) is not RNNCell: property 'output_size' is missing, property 'state_size' is missing." when I try to set:

```<code>beam_search_decoder = tfa.seq2seq.BeamSearchDecoder(
    cell= model.decoder.lstm,
</code>```

There are very few sources and the only example I found uses the attention mechanism. How should I create a beam search decoder based on a simple decoder with LSTM layer?

Title: Use Beam Search in encoder-decoder

Body:
How can tfa.seq2seq.BeamSearchDecoder, for example, be used with a simple encoder-decoder architecture? Suppose the task is machine translation, where the encoder returns a vector representation of the input sequence. The decoder uses Embedding, LSTM and Dense layers to translate the text word by word. It gets an error "Argument 'cell' (<keras.layers.rnn.lstm.LSTM object at 0x000002658BF13C40>) is not RNNCell: property 'output_size' is missing, property 'state_size' is missing." when I try to set:

beam_search_decoder = tfa.seq2seq.BeamSearchDecoder(
    cell= model.decoder.lstm,

There are very few sources and the only example I found uses the attention mechanism. How should I create a beam search decoder based on a simple decoder with LSTM layer?


问:
How to authenticate 2 types of custom users using one login Django?
So I've customized user using the AbstractUser and then inherited two users from my custom user. The signup works just fine and registers my users. However I'm having trouble creating login logic that looks in all 2 models to find the credentials and then takes user to their respective dashboard.

Here is my models.py:

```<code>class User(AbstractUser):
    is_doc = models.BooleanField(default=False)
    is_patient = models.BooleanField(default=False)

    objects = UserManager()

class Patient(User):
    address = models.CharField(max_length=210)

    def __str__(self):
        return self.first_name + " " + self.last_name

class Doctor(User):
    address = models.CharField(max_length=210)

    def __str__(self):
        return self.first_name
</code>```

managers.py:

```<code>class UserManager(BaseUserManager):

    def create_user(self, email, password=None):

        if email is None:
            raise TypeError('Users must have an email address.')

        user = self.model(email=self.normalize_email(email))
        user.set_password(password)
        user.save()

        return user
    def create_patient(self, email, password):
        if password is None:
            raise TypeError('Must have a password')

        user = self.model(email=self.normalize_email(email))
        user.set_password(password)
        user.is_patient = True
        user.save()

    def create_superuser(self, email, password):

        if password is None:
            raise TypeError('Superusers must have a password.')

        user = self.create_user(email, password)
        user.is_superuser = True
        user.is_staff = True
        user.save()

        return user
</code>```

views.py:

```<code>def patient_signup(request):
    if request.method == 'POST':
        form = forms.PatientSignUpForm(request.POST)
        if form.is_valid():
            models.Patient.objects.create(**form.cleaned_data)
            return redirect('')

    else:
        form = forms.PatientSignUpForm(initial={'is_patient': True})

    return render(request, 'patient_signup.html', {'form': form})
</code>```

The default authentication using django.contrib.auth does not work and just redirects the same login page again (tried following the docs). So I don't have a login view logic now. How would I login my users and determine is_patient or is_doctor?

Body:
So I've customized user using the AbstractUser and then inherited two users from my custom user. The signup works just fine and registers my users. However I'm having trouble creating login logic that looks in all 2 models to find the credentials and then takes user to their respective dashboard.

Here is my models.py:

class User(AbstractUser):
    is_doc = models.BooleanField(default=False)
    is_patient = models.BooleanField(default=False)

    objects = UserManager()

class Patient(User):
    address = models.CharField(max_length=210)

    def __str__(self):
        return self.first_name + " " + self.last_name

class Doctor(User):
    address = models.CharField(max_length=210)

    def __str__(self):
        return self.first_name

managers.py:

class UserManager(BaseUserManager):

    def create_user(self, email, password=None):

        if email is None:
            raise TypeError('Users must have an email address.')

        user = self.model(email=self.normalize_email(email))
        user.set_password(password)
        user.save()

        return user
    def create_patient(self, email, password):
        if password is None:
            raise TypeError('Must have a password')

        user = self.model(email=self.normalize_email(email))
        user.set_password(password)
        user.is_patient = True
        user.save()

    def create_superuser(self, email, password):

        if password is None:
            raise TypeError('Superusers must have a password.')

        user = self.create_user(email, password)
        user.is_superuser = True
        user.is_staff = True
        user.save()

        return user

views.py:

def patient_signup(request):
    if request.method == 'POST':
        form = forms.PatientSignUpForm(request.POST)
        if form.is_valid():
            models.Patient.objects.create(**form.cleaned_data)
            return redirect('')

    else:
        form = forms.PatientSignUpForm(initial={'is_patient': True})

    return render(request, 'patient_signup.html', {'form': form})

The default authentication using django.contrib.auth does not work and just redirects the same login page again (tried following the docs). So I don't have a login view logic now. How would I login my users and determine is_patient or is_doctor?


问:
chess board (box spacing) with css
I'm trying to make like the picture but I cant figure out how to make spaces between the boxes and how to make inside square?here is what I'm trying to acheave

html not full

```<code>      <table>
          <div>
            <tr>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
            </tr>
          </div>
          <div>
            <tr>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
              <th></th>
            </tr>
          </div>
          <div>

CSS

    th {
      width: 50px;
      height: 50px;
      padding: 15px;
    }

    th:nth-child(even) {
      border: 5px solid rgb(89, 218, 89);
      background: orangered;
    }
    th:nth-child(odd) {
      border: 5px solid orangered;
      background: rgb(89, 218, 89);
    }

</code>```

Title: chess board (box spacing) with css

Body:
I'm trying to make like the picture but I cant figure out how to make spaces between the boxes and how to make inside square?here is what I'm trying to acheave

html not full

CSS

    th {
      width: 50px;
      height: 50px;
      padding: 15px;
    }

    th:nth-child(even) {
      border: 5px solid rgb(89, 218, 89);
      background: orangered;
    }
    th:nth-child(odd) {
      border: 5px solid orangered;
      background: rgb(89, 218, 89);
    }


问:
How to add space between bar in a stacked bar chart in Chart.js
I'm creating a bar chart in my Angular app v.14 and I can't insert the part of code that I have already seen on the guide in Chart.js to be able to add space between bars:
" barThickness: 0.6
barPercentage: 0.6 "
I need to figure the part of code to insert this rows!

I'm trying to have this result:

Thanks in advance!


问:
Flask-SQLAlchemy IntegrityError-UNIQUE constraint failed
I'm making a blogging social media website using Flask and an SQLite3 database, with a system wherein users can follow/unfollow each other. However, a bug in the program doesn't let a user follow more than one person, since the relationship table I've defined to depict the relationship between two users throws an IntegrityError every time a user tries to follow more than one person, saying the UNIQUE constraint has been violated. Here is the user model and table I'm using:

```<code># Project/application/models.py

followers = db.Table('followers', db.Column('follower_id', db.Integer, db.ForeignKey('user.id')), db.Column('followed_id', db.Integer, db.ForeignKey('user.id')))

class User(db.Model, UserMixin):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String, unique=True)
    password = db.Column(db.String)
    email = db.Column(db.String, unique=True)
    doj = db.Column(db.DateTime(timezone=True), default=func.now())
    followed = db.relationship('User', secondary=followers, primaryjoin=(followers.c.follower_id == id), secondaryjoin=(followers.c.followed_id == id), backref=db.backref('followers', lazy='dynamic'), lazy='dynamic')
    posts = db.relationship('Blog', backref='user', passive_deletes=True)

    def is_following(self, user):
        return self.followed.filter(followers.c.followed_id == user.id).count() > 0

    def follow(self, user):
        if not self.is_following(user):
            self.followed.append(user)

    def unfollow(self, user):
        if self.is_following(user):
            self.followed.remove(user)
</code>```

Here is the endpoint where I try to implement this functionality:

```<code># Project/application/controllers.py

@controllers.route("/<name>", methods=["GET", "POST"])
def userpage(name):
    userreq = User.query.filter_by(username=name).first()
    userblogs = Blog.query.filter_by(author=userreq.id).order_by(Blog.timestamp)

    if current_user.is_authenticated:
        if userreq.id == current_user.id:
            return redirect(url_for(".dashboard"))
        if request.method == "POST":
            if not current_user.is_following(userreq):
                current_user.follow(userreq)
                db.session.commit()
            else:
                current_user.unfollow(userreq)
                db.session.commit()
            return redirect(url_for(".userpage", name=userreq.username))
    else:
        if request.method == "POST":
            flash("You must log in to follow other users!", category='error')
            return redirect(url_for("auth.login"))
    return render_template("dashboard.html", logged_user=current_user, posts=userblogs, display_user=userreq)
</code>```

This is how I display the button in my template code:

```<code><!-- Project/templates/dashboard.html -->

{% if logged_user.is_authenticated %}
            {% if not logged_user.is_following(display_user) %}
            <form method="POST" class="form-inline"><button type="submit" class="btn btn-sm btn-primary">Follow</button></form><br/>
            {% else %}
            <form method="POST" class="form-inline"><button type="submit" class="btn btn-sm btn-outline-secondary">Following</button></form><br/>
            {% endif %}
        {% endif %}
</code>```

I've tried including all kinds of constraints in my relationship table followers, from making the primary key true to explicitly specifying the values in individual columns need not be none. My problem is I want the relationship table to take the follower_id and following_id together and treat it as a composite primary key, instead of treating both as values that must be unique, and I have no idea how to achieve this.

Body:
I'm making a blogging social media website using Flask and an SQLite3 database, with a system wherein users can follow/unfollow each other. However, a bug in the program doesn't let a user follow more than one person, since the relationship table I've defined to depict the relationship between two users throws an IntegrityError every time a user tries to follow more than one person, saying the UNIQUE constraint has been violated. Here is the user model and table I'm using:

# Project/application/models.py

followers = db.Table('followers', db.Column('follower_id', db.Integer, db.ForeignKey('user.id')), db.Column('followed_id', db.Integer, db.ForeignKey('user.id')))

class User(db.Model, UserMixin):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String, unique=True)
    password = db.Column(db.String)
    email = db.Column(db.String, unique=True)
    doj = db.Column(db.DateTime(timezone=True), default=func.now())
    followed = db.relationship('User', secondary=followers, primaryjoin=(followers.c.follower_id == id), secondaryjoin=(followers.c.followed_id == id), backref=db.backref('followers', lazy='dynamic'), lazy='dynamic')
    posts = db.relationship('Blog', backref='user', passive_deletes=True)

    def is_following(self, user):
        return self.followed.filter(followers.c.followed_id == user.id).count() > 0

    def follow(self, user):
        if not self.is_following(user):
            self.followed.append(user)

    def unfollow(self, user):
        if self.is_following(user):
            self.followed.remove(user)

Here is the endpoint where I try to implement this functionality:

# Project/application/controllers.py

@controllers.route("/<name>", methods=["GET", "POST"])
def userpage(name):
    userreq = User.query.filter_by(username=name).first()
    userblogs = Blog.query.filter_by(author=userreq.id).order_by(Blog.timestamp)

    if current_user.is_authenticated:
        if userreq.id == current_user.id:
            return redirect(url_for(".dashboard"))
        if request.method == "POST":
            if not current_user.is_following(userreq):
                current_user.follow(userreq)
                db.session.commit()
            else:
                current_user.unfollow(userreq)
                db.session.commit()
            return redirect(url_for(".userpage", name=userreq.username))
    else:
        if request.method == "POST":
            flash("You must log in to follow other users!", category='error')
            return redirect(url_for("auth.login"))
    return render_template("dashboard.html", logged_user=current_user, posts=userblogs, display_user=userreq)

This is how I display the button in my template code:

{% if logged_user.is_authenticated %}
            {% if not logged_user.is_following(display_user) %}
            <form method="POST" class="form-inline"><button type="submit" class="btn btn-sm btn-primary">Follow</button></form>

            {% else %}
            <form method="POST" class="form-inline"><button type="submit" class="btn btn-sm btn-outline-secondary">Following</button></form>

            {% endif %}
        {% endif %}

I've tried including all kinds of constraints in my relationship table followers, from making the primary key true to explicitly specifying the values in individual columns need not be none. My problem is I want the relationship table to take the follower_id and following_id together and treat it as a composite primary key, instead of treating both as values that must be unique, and I have no idea how to achieve this.


问:
How to import locally images in a React-project
I have a following problem:

I'm trying to upload local images to my react project.
I use the "Create React App".
I'm not quite clear in which folder I should place the images: in the public or in the src folder?
There are different opinions in the forum.
In this project I have the photos in the public folder and just upload them with their name (img.png). On GitHub it seems to work,
but if I want to load it locally via the browser (npm start) then the photos are not displayed.
Tried all the methods described in the forum (../ or ../../ or import img from'' etc) but nothing helped.

GitHub-link

I want the images to load in the local browser.


问:
How to pass the Timestamp in GetMapping
Im trying to fetch the data from DB which is updated from todays date to last 30days updated data(Timestamp)

Controller-class

```<code>@GetMapping("/getcodeByTs/createdTs")
public List<CodeSet> getCodeSetByCreatedTs(@RequestBody Timestamp createdTs){
    return codesetService.getCodeSetByCreatedTs(createdTs);
}
</code>```

Service-layer

```<code>public List<CodeSet> getCodeSetByCreatedTs(Timestamp createdTs){
    return codeRepo.findCodeSetByCreatedTs(createdTs);
}
</code>```

Repository

```<code>@Query(value="Select * from CODE_SET Where CREATED_TS = ? ",nativeQuery=true)
public List<CodeSet> findCodeSetByCreatedTs(Timestamp createdTs);
</code>```

postman-output

```<code>Required request body is missing: public
java.util.List<com.example.first.entity.CodeSet>
com.example.first.controller.CodeSetController.getCodeSetByCreatedTs(java.sql.Timestamp)
</code>```

How can i fetch the data from DB

Title: How to pass the Timestamp in GetMapping

Body:
Im trying to fetch the data from DB which is updated from todays date to last 30days updated data(Timestamp)

Controller-class

@GetMapping("/getcodeByTs/createdTs")
public List<CodeSet> getCodeSetByCreatedTs(@RequestBody Timestamp createdTs){
    return codesetService.getCodeSetByCreatedTs(createdTs);
}

Service-layer

public List<CodeSet> getCodeSetByCreatedTs(Timestamp createdTs){
    return codeRepo.findCodeSetByCreatedTs(createdTs);
}

Repository

@Query(value="Select * from CODE_SET Where CREATED_TS = ? ",nativeQuery=true)
public List<CodeSet> findCodeSetByCreatedTs(Timestamp createdTs);

postman-output

Required request body is missing: public
java.util.List<com.example.first.entity.CodeSet>
com.example.first.controller.CodeSetController.getCodeSetByCreatedTs(java.sql.Timestamp)

How can i fetch the data from DB


问:
How can I decrease the number of firestore reads with React context?
I'm making a firestore application with ReactJS, I made some tricks to decrease the number of document reads of it, I already created a context with snapshots, basically I set a query inside a function and I pass it's result through the context, so I won't need to call the query again, and every update I have in the collection, the snapshot shows me.

But I want more, my question is: Do I have more tricks to use with react context to decrease the number of document reads?

For example, can I pass a collection reference as context?

Like this:

```<code>const collectionReference = collection(db, "collectionName");
</code>```

Body:
I'm making a firestore application with ReactJS, I made some tricks to decrease the number of document reads of it, I already created a context with snapshots, basically I set a query inside a function and I pass it's result through the context, so I won't need to call the query again, and every update I have in the collection, the snapshot shows me.

But I want more, my question is: Do I have more tricks to use with react context to decrease the number of document reads?

For example, can I pass a collection reference as context?

Like this:

const collectionReference = collection(db, "collectionName");


问:
How do I change the material of a line renderer while it is a prefab?
first time asking a question on here, but I couldn't find my answer anywhere else. I'm relatively new to Unity and C#, but have experience coding in other languages.
I'm trying to make a drawing scene in my Unity2D game, where you can use your mouse to draw on a canvas, but am having trouble with switching colors. I set up the drawing, and it works pretty well. However, I want the player to be able to switch the color of the "ink" by pressing a button with their desired color on it, so I would have an orange, red, blue, green... etc.

I have tried many different ways of doing this, but am still stuck. Every time I press the button, it just spawns a line, and doesn't change the color.

This is the code I have now(which doesn't work):

```<code>public class ChooseColor : MonoBehaviour
{
    [SerializeField]
    private Material mat;
    private Renderer rend;

    private void Start()
    {

        GameObject prefab = Resources.Load<GameObject>("Assets/Assets");
        rend = prefab.GetComponent<Renderer>();

        rend.material = mat;
    }
}
</code>```

This has frustrated me and I hope someone can help, thanks.

Body:
first time asking a question on here, but I couldn't find my answer anywhere else. I'm relatively new to Unity and C#, but have experience coding in other languages.
I'm trying to make a drawing scene in my Unity2D game, where you can use your mouse to draw on a canvas, but am having trouble with switching colors. I set up the drawing, and it works pretty well. However, I want the player to be able to switch the color of the "ink" by pressing a button with their desired color on it, so I would have an orange, red, blue, green... etc.

I have tried many different ways of doing this, but am still stuck. Every time I press the button, it just spawns a line, and doesn't change the color.

This is the code I have now(which doesn't work):

public class ChooseColor : MonoBehaviour
{
    [SerializeField]
    private Material mat;
    private Renderer rend;

    private void Start()
    {

        GameObject prefab = Resources.Load<GameObject>("Assets/Assets");
        rend = prefab.GetComponent<Renderer>();

        rend.material = mat;
    }
}

This has frustrated me and I hope someone can help, thanks.


问:
Powershell Subtract 1 textbox value from another
I am trying to subtract 1 Textbox value from another and output that in the second Textbox

please see example of what I am trying to achieve.

this is Textbox1

This is Textbox2

the subtraction I am trying to do is

```<code>$button3_Click = {
$sum1 = $textbox1.Text
$sum3 = $textbox2.text
    if($radiobutton3.checked -eq $true){
    $equals = $sum3 - $sum1
    $textbox2.Text = $equals
    }
}
</code>```

the outcome I would like is Textbox2 to change to the answer 151, is this possible?

Body:
I am trying to subtract 1 Textbox value from another and output that in the second Textbox

please see example of what I am trying to achieve.

this is Textbox1

This is Textbox2

the subtraction I am trying to do is

$button3_Click = {
$sum1 = $textbox1.Text
$sum3 = $textbox2.text
    if($radiobutton3.checked -eq $true){
    $equals = $sum3 - $sum1
    $textbox2.Text = $equals
    }
}

the outcome I would like is Textbox2 to change to the answer 151, is this possible?


问:
How to connect to an Oracle database installed on a Windows 11 virtual machine (Parallels) using a computer with Apple Silicon (M1)?
Since Oracle Database cannot be installed on Apple Silicon, I decided to take a workaround, but now I do not understand how to connect to the Oracle Database, which I installed on a Windows 11 virtual machine through Parallels.

I understand that this makes little sense, since in fact you can use Oracle from Windows 11 and do whatever you want with it.

But as an experiment, I wanted to try connecting to an already deployed HR database in my Windows 11 virtual machine using DataGrip on my Apple Silicon (M1) computer.

I know that there are other ways to use Oracle on a Mac (using Docker for example) but maybe we can come up with some other alternative, or maybe there already is, but I don't know about it.

I hope I wrote as clear as possible. Sorry, I'm using a translator.

I used this instruction to install Instant Client (as I understand it, this tool helps us connect to the Database server, be it a virtual machine or a remote server), I spent several hours installing everything. In Datagrip, when connecting, I specified different settings, wrote the path to the installed instantclient, however, I constantly get an error when connecting (whatever settings I choose), I googled this error, but I still did not understand how I can apply them It is for M1 and not Windows computers.

The error looked like this:

Failed DBMS: Oracle (no ver.)  Case sensitivity: plain=mixed, delimited=exact Native library cannot be loaded.  no ocijdbc21 in java.library.path: /Users/malkhaz/instantclient_19_8:/Users/malkhaz/lib:/Users/malkhaz/instantclient_19_8.


问:
Py2App - immediate abort() crash
I'm trying to package a script into a .dmg file using Py2App. When I try to open the packaged file,  it immediately crashes.

I tried bundling the files in both Alias mode and regularly.

Alias bundling using python3 setup.py py2app -A

It generates a dist folder which contains the packaged application. I can't open the application directly, but I can open it by unpacking the file, and opening the Unix Executable File in the MacOS folder.

Opening the application this way works, along with all functionalities.

Regular bundling using python3 setup.py py2app

I can't open the application regularly, and even through the Unix Executable File when unpacked.

I'd appreciate any input I could get. Really not sure how to proceed from here.

Below are my setup. I'm not sure if I'm missing anything in setup.py? Please note I can open the file when I bundle the package in Alias mode, but ONLY when I unpack the app file in the dist folder.

File Structure

```<code>|-- assets
|-- logs
|-- scripts
|--  utils
 README.MD
 requirements.txt
 setup.py <-- for Py2App
 main.py <-- entry point

</code>```

setup.py

```<code>from setuptools import setup
from glob import glob

"""
    Description:
        - Converts python script into .dmg file for macs
        - Run "python setup.py py2app" in terminal to start
"""

APP=["main.py"]

DATA_FILES=[
    ('assets', glob('assets/*.*')),
    ('logs', glob('logs/*.*')),
    ('scripts', glob('scripts/*.*')),
    ('utils', glob('utils/*.*'))
]

OPTIONS={
    "argv_emulation": True,
    "iconfile": "assets/spdr.png",
    "includes": ["os", "yaml", "concurrent.futures", "datetime", "time"],
    "packages": ["pandas", "PySimpleGUI"]
}

# I tried not including includes, and packages from OPTIONS, and it doesn't seem to help either.

setup(
    app=APP,
    data_files=DATA_FILES,
    options={"py2app": OPTIONS},
    setup_requires=["py2app"],
)

</code>```

Title: Py2App - immediate abort() crash

Body:
I'm trying to package a script into a .dmg file using Py2App. When I try to open the packaged file,  it immediately crashes.

I tried bundling the files in both Alias mode and regularly.

Alias bundling using python3 setup.py py2app -A

It generates a dist folder which contains the packaged application. I can't open the application directly, but I can open it by unpacking the file, and opening the Unix Executable File in the MacOS folder.

Opening the application this way works, along with all functionalities.

Regular bundling using python3 setup.py py2app

I can't open the application regularly, and even through the Unix Executable File when unpacked.

I'd appreciate any input I could get. Really not sure how to proceed from here.

Below are my setup. I'm not sure if I'm missing anything in setup.py? Please note I can open the file when I bundle the package in Alias mode, but ONLY when I unpack the app file in the dist folder.

File Structure

|-- assets
|-- logs
|-- scripts
|--  utils
 README.MD
 requirements.txt
 setup.py <-- for Py2App
 main.py <-- entry point

setup.py

from setuptools import setup
from glob import glob

"""
    Description:
        - Converts python script into .dmg file for macs
        - Run "python setup.py py2app" in terminal to start
"""

APP=["main.py"]

DATA_FILES=[
    ('assets', glob('assets/*.*')),
    ('logs', glob('logs/*.*')),
    ('scripts', glob('scripts/*.*')),
    ('utils', glob('utils/*.*'))
]

OPTIONS={
    "argv_emulation": True,
    "iconfile": "assets/spdr.png",
    "includes": ["os", "yaml", "concurrent.futures", "datetime", "time"],
    "packages": ["pandas", "PySimpleGUI"]
}

# I tried not including includes, and packages from OPTIONS, and it doesn't seem to help either.

setup(
    app=APP,
    data_files=DATA_FILES,
    options={"py2app": OPTIONS},
    setup_requires=["py2app"],
)


问:
PHP - Curl is unable to get local issuer certificate for only one domain
When trying to access one particular API through curl in PHP, I get the curl error code 60 - unable to get local issuer certificate. The strange thing is that I only get this error for this particular domain, and only when using curl in php.

When accessing the API with command line curl, the issue does not occur. When trying to access any other SSL domain via curl in php, the issue does not occur. In fact, I have found another website that uses the same intermediate certificate (i.e. RapidSSL Global TLS RSA4096 SHA256 2022 CA1), and I can access that website.

I have of course tried setting cacert.pem manually, for both curl and openssl, through both the php.ini and through curl_setopt in code, but to no avail. I have also verified that the root certificate that is used by the problematic api (i.e. Digicert Global Root CA) is present in both the downloaded and default CA stores.

At this point, I would appreciate any guesses as to what could possibly be causing this behaviour.

Here is the output of Curl in verbose mode when trying to access the problematic website:

```<code>*   Trying <IP>:443...
* Connected to <Domain> (<IP>) port 443 (#0)
* ALPN: offers h2
* ALPN: offers http/1.1
*  CAfile: /usr/local/etc/openssl@1.1/cert.pem
*  CApath: none
* SSL certificate problem: unable to get local issuer certificate
* Closing connection 0
</code>```

Update: after running testssl.sh, it seems that chain of trust is not entirely complete. This does not explain why only curl with php has this issue, and I would still appreciate it if anybody could point me to a way to accept this particular flaw without disabling SSL verification entirely.

Body:
When trying to access one particular API through curl in PHP, I get the curl error code 60 - unable to get local issuer certificate. The strange thing is that I only get this error for this particular domain, and only when using curl in php.

When accessing the API with command line curl, the issue does not occur. When trying to access any other SSL domain via curl in php, the issue does not occur. In fact, I have found another website that uses the same intermediate certificate (i.e. RapidSSL Global TLS RSA4096 SHA256 2022 CA1), and I can access that website.

I have of course tried setting cacert.pem manually, for both curl and openssl, through both the php.ini and through curl_setopt in code, but to no avail. I have also verified that the root certificate that is used by the problematic api (i.e. Digicert Global Root CA) is present in both the downloaded and default CA stores.

At this point, I would appreciate any guesses as to what could possibly be causing this behaviour.

Here is the output of Curl in verbose mode when trying to access the problematic website:

*   Trying <IP>:443...
* Connected to <Domain> (<IP>) port 443 (#0)
* ALPN: offers h2
* ALPN: offers http/1.1
*  CAfile: /usr/local/etc/openssl@1.1/cert.pem
*  CApath: none
* SSL certificate problem: unable to get local issuer certificate
* Closing connection 0

Update: after running testssl.sh, it seems that chain of trust is not entirely complete. This does not explain why only curl with php has this issue, and I would still appreciate it if anybody could point me to a way to accept this particular flaw without disabling SSL verification entirely.


问:
Problem accessing multidimensional array length and fields
Here is code to test a multidimensional array

public class Multiarraytest {

    public int size_main = 5;
    public int size_aux = 20;

    Multiarraytest() {
        float[][] float_mul = new float[size_main][size_aux];
    }

    void init_int(Multiarraytest mul) {
        int i, j = 0;

        while(i < mul.length) {
            while(j < mul[i].length) {
                mul[i][j] = (i + (j/10));
                j++;
            }
            i++;
        }
    }

    public static void main(String[] args) {

    }
}
```

But
here are the results of javac Multiarraytest.java.

error: cannot find symbol While(i < mul.length)
^
symbol: variable length
location: variable mul of type Multiarraytest

error: array required, but Multiarraytest found while(j < mul[i].length
^
error: array required, but Multiarraytest found mul[i][j] = (i + (j/10));

I have not found what's going wrong.

mul is a 2 dimensional array

mul.length should give the length of the first array

mul[1] should lead to the array nested in the first case of mul

mul[1].length should give the length of the array nested in the first case of mul

mul[1][2] should give access to read/write of the second case of the array nested in the first case of mul.

Where have I made a mistake?

This is a cut down version of what I was doing but same errors are reported. I read tutorial and close copy-cut it. Except it's a float multidimensional array instead of int multidimensional array and I try to fill it in a loop instead at the initializing time.

Body:
Here is code to test a multidimensional array

public class Multiarraytest {

    public int size_main = 5;
    public int size_aux = 20;

    Multiarraytest() {
        float[][] float_mul = new float[size_main][size_aux];
    }

    void init_int(Multiarraytest mul) {
        int i, j = 0;

        while(i < mul.length) {
            while(j < mul[i].length) {
                mul[i][j] = (i + (j/10));
                j++;
            }
            i++;
        }
    }

    public static void main(String[] args) {

    }
}

But
here are the results of javac Multiarraytest.java.

error: cannot find symbol While(i < mul.length)
^
symbol: variable length
location: variable mul of type Multiarraytest

error: array required, but Multiarraytest found while(j < mul[i].length
^
error: array required, but Multiarraytest found mul[i][j] = (i + (j/10));

I have not found what's going wrong.

mul is a 2 dimensional array

mul.length should give the length of the first array

mul[1] should lead to the array nested in the first case of mul

mul[1].length should give the length of the array nested in the first case of mul

mul[1][2] should give access to read/write of the second case of the array nested in the first case of mul.

Where have I made a mistake?

This is a cut down version of what I was doing but same errors are reported. I read tutorial and close copy-cut it. Except it's a float multidimensional array instead of int multidimensional array and I try to fill it in a loop instead at the initializing time.


问:
ImportError: attempted relative import with no known parent package
This is my folder structure

```<code>PARENT/
    config.py
    myfolder/
        main.py
</code>```

I would like to import config.py to my main.py

```<code>from . import configure as cfg
</code>```

It returns the following error

```<code>from . import configure as cfg
ImportError: attempted relative import with no known parent package
</code>```

I would like to know what is the recommended way to put config constants?

Body:
This is my folder structure

PARENT/
    config.py
    myfolder/
        main.py

I would like to import config.py to my main.py

from . import configure as cfg

It returns the following error

from . import configure as cfg
ImportError: attempted relative import with no known parent package

I would like to know what is the recommended way to put config constants?


问:
Autosize gives different textSize results althought having same width and height in the Layout Inspector
I have two AppCompatTextview's in my ConstraintLayout. I am using app:autoSizeTextType="uniform" attribute to autoSize the textSize according to the width and height of the AppCompatTextview's. I have tested the app and I have used the layout inspector and I have seen that both AppCompatTextview's have exactly the same width and height but different textSize and baseline:

AppCompatTextview 1:

height: 23dp width: 100dp baseline: 60 textsize: 15,7 sp

AppCompatTextview 2:

height: 23dp width: 100dp baseline: 61 textsize: 16 sp

I don't understand why they have different baseline and textsize if they have exactly the same width and height and exactly the same attributes:

```<code>    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/AppCompatTextView1"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="@dimen/margin_acc"
        android:layout_marginBottom="@dimen/margin_acc"
        android:text="@string/ttx"
        app:autoSizeMinTextSize="2dp"
        app:autoSizeTextType="uniform"
        app:layout_constraintBottom_toBottomOf="@id/re1"
        app:layout_constraintEnd_toStartOf="@id/re2"
        app:layout_constraintStart_toEndOf="@id/re3"
        app:layout_constraintTop_toTopOf="@id/re4"
        />

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/AppCompatTextView2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="@dimen/margin_acc"
        android:layout_marginBottom="@dimen/margin_acc"
        android:text="@string/ttx2"
        app:autoSizeMinTextSize="2dp"
        app:autoSizeTextType="uniform"
        app:layout_constraintBottom_toBottomOf="@id/le1"
        app:layout_constraintEnd_toStartOf="@id/le2"
        app:layout_constraintStart_toEndOf="@id/le3"
        app:layout_constraintTop_toTopOf="@id/le4"
        />
</code>```

Body:
I have two AppCompatTextview's in my ConstraintLayout. I am using app:autoSizeTextType="uniform" attribute to autoSize the textSize according to the width and height of the AppCompatTextview's. I have tested the app and I have used the layout inspector and I have seen that both AppCompatTextview's have exactly the same width and height but different textSize and baseline:

AppCompatTextview 1:

height: 23dp width: 100dp baseline: 60 textsize: 15,7 sp

AppCompatTextview 2:

height: 23dp width: 100dp baseline: 61 textsize: 16 sp

I don't understand why they have different baseline and textsize if they have exactly the same width and height and exactly the same attributes:

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/AppCompatTextView1"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="@dimen/margin_acc"
        android:layout_marginBottom="@dimen/margin_acc"
        android:text="@string/ttx"
        app:autoSizeMinTextSize="2dp"
        app:autoSizeTextType="uniform"
        app:layout_constraintBottom_toBottomOf="@id/re1"
        app:layout_constraintEnd_toStartOf="@id/re2"
        app:layout_constraintStart_toEndOf="@id/re3"
        app:layout_constraintTop_toTopOf="@id/re4"
        />

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/AppCompatTextView2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="@dimen/margin_acc"
        android:layout_marginBottom="@dimen/margin_acc"
        android:text="@string/ttx2"
        app:autoSizeMinTextSize="2dp"
        app:autoSizeTextType="uniform"
        app:layout_constraintBottom_toBottomOf="@id/le1"
        app:layout_constraintEnd_toStartOf="@id/le2"
        app:layout_constraintStart_toEndOf="@id/le3"
        app:layout_constraintTop_toTopOf="@id/le4"
        />


问:
How to reference forked repo or local repo as node module
I created a.js file that utilizes the whoiser library: https://github.com/LayeredStudio/whoiser by calling

```<code>const whoiser = require('whoiser')

</code>```

After I used npm install whoiser

There is a forked repo that fixes some issues, but hasn't been merged. My question is, how do I reference to the forked repo instead of this main one that has the fixes OR even better, download the main repo, make my own changes, and reference to my local copy instead? I am not using a package.json, not sure if I need to be for this? I just have one .js file that is currently using the require posted above.

I don't know where to start. Is it as easy as just adding the forked repo link to the require statement? That's where my head was going since I don't have a package.json or anything.

Body:
I created a.js file that utilizes the whoiser library: https://github.com/LayeredStudio/whoiser by calling

const whoiser = require('whoiser')

After I used npm install whoiser

There is a forked repo that fixes some issues, but hasn't been merged. My question is, how do I reference to the forked repo instead of this main one that has the fixes OR even better, download the main repo, make my own changes, and reference to my local copy instead? I am not using a package.json, not sure if I need to be for this? I just have one .js file that is currently using the require posted above.

I don't know where to start. Is it as easy as just adding the forked repo link to the require statement? That's where my head was going since I don't have a package.json or anything.


问:
Clear Hive Box without the encryptionCipher
I'm building a chat app for the web. I cache the chats with Hive and encrypt the Box with the UID of the logged in user.

If another user logs in, I want to clear the Box and fetch data from the cloud data store for the new user. However, assuming I do not know the UID of the previously logged in user, how do I clear the old Box? AFAIK, I need to open the Box and then clear it, and I cannot open the box without the previous encryptionCipher.