问:
AttributeError: 'VIzDoomGym' object has no attribute 'Observation Space'
I am following a tutorial on making an RL Agent Play Doom when I run the code:

```<code>from vizdoom import *
from gym import Env
from gym.spaces import Discrete, Box
from matplotlib import pyplot as plt
from stable_baselines3.common.callbacks import BaseCallback
from stable_baselines3.common import env_checker
from stable_baselines3 import PPO
import os
import random
import time
import numpy as np
import cv2

class VizDoomGym(Env):
    def _init_(self, render=False):
        super()._init_()
        self.game = DoomGame()
        self.game.load_config('github/scenarios/basic.cfg')

        if render == False:
            self.game.set_window_visible(False)
        else:
            self.game.set_window_visible(True)

        self.game.init()

        self.observation_space = Box(low=0, high=255, shape=(100,160,1), dtype=np.uint8)
        self.action_space = Discrete(3)

    def step(self, action):
        actions = np.identity(3, dtype=np.uint8)
        reward = self.game.make_action(actions[action],4)

        if self.game.get_state():
            state = self.game.get_state().screen_buffer
            state.self.grayscale(state)
            ammo = self.game.get_state().game_variables[0]
            info = ammo
        else:
            state = np.zeros(self.observation_space.shape)
            info = 0

        info = {"info":info}
        done = self.game.is_episode_finished()

        return state, reward, done, info
    def render():
        pass
    def reset(self):
        self.game.new_episode()
        state = self.game.get_state().screen_buffer

        return self.grayscale(state)

    def grayscale(self, observation):
        gray = cv2.cvtColor(np.moveaxis(observation, 0, -1), cv2.COLOR_BGR2GRAY)
        resize = cv2.resize(gray, (160, 100), interpolation=cv2.INTER_CUBIC)
        state = np.reshape(resize, (100, 160,1))
        return state
    def close():
        self.game.close()

CHECKPOINT_DIR = './train/train_basic'
LOG_DIR = './logs/log_basic'

env = VizDoomGym()

model = PPO('CnnPolicy', env, tensorboard_log=LOG_DIR, verbose=1, learning_rate=0.0001, n_steps=2048)
model.learn(total_timesteps=100000, callback=callback)

</code>```

I get the following error:

```<code>Traceback (most recent call last):
  File "DOOM.py", line 72, in <module>
    model = PPO('CnnPolicy', env, tensorboard_log=LOG_DIR, verbose=1, learning_rate=0.0001, n_steps=2048)
  File "C:\Users\lawri\AppData\Local\Programs\Python\Python37\lib\site-packages\stable_baselines3\ppo\ppo.py", line 130, in __init__
    spaces.MultiBinary,
  File "C:\Users\lawri\AppData\Local\Programs\Python\Python37\lib\site-packages\stable_baselines3\common\on_policy_algorithm.py", line 94, in __init__
    supported_action_spaces=supported_action_spaces,
  File "C:\Users\lawri\AppData\Local\Programs\Python\Python37\lib\site-packages\stable_baselines3\common\base_class.py", line 179, in __init__
    env = self._wrap_env(env, self.verbose, monitor_wrapper)
  File "C:\Users\lawri\AppData\Local\Programs\Python\Python37\lib\site-packages\stable_baselines3\common\base_class.py", line 228, in _wrap_env
    env = DummyVecEnv([lambda: env])
  File "C:\Users\lawri\AppData\Local\Programs\Python\Python37\lib\site-packages\stable_baselines3\common\vec_env\dummy_vec_env.py", line 27, in __init__
    VecEnv.__init__(self, len(env_fns), env.observation_space, env.action_space)
  File "C:\Users\lawri\AppData\Local\Programs\Python\Python37\lib\site-packages\gym\core.py", line 241, in __getattr__
    return getattr(self.env, name)
AttributeError: 'VizDoomGym' object has no attribute 'observation_space'
</code>```

The tutorial I am following is: https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&cad=rja&uact=8&ved=2ahUKEwigzcLRtPH7AhX-S0EAHWAABmkQwqsBegQICBAG&url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DeBCU-tqLGfQ&usg=AOvVaw1THV8bvNXYB2aoO3Vi8iUC

I am using Python 3.7.0 with stable baselines 3 [Extras] and Gym 0.26 and a CPU version of PyTorch. The GitHub for the tutorial is here: https://github.com/nicknochnack/DoomReinforcementLearning/blob/main/VizDoom-Basic-Tutorial.ipynb

I expected for it to start training the re-enforcement learning model, I have searched up similar errors to which I didn't get a clear answer.

Body:
I am following a tutorial on making an RL Agent Play Doom when I run the code:

from vizdoom import *
from gym import Env
from gym.spaces import Discrete, Box
from matplotlib import pyplot as plt
from stable_baselines3.common.callbacks import BaseCallback
from stable_baselines3.common import env_checker
from stable_baselines3 import PPO
import os
import random
import time
import numpy as np
import cv2

class VizDoomGym(Env):
    def _init_(self, render=False):
        super()._init_()
        self.game = DoomGame()
        self.game.load_config('github/scenarios/basic.cfg')

        if render == False:
            self.game.set_window_visible(False)
        else:
            self.game.set_window_visible(True)

        self.game.init()

        self.observation_space = Box(low=0, high=255, shape=(100,160,1), dtype=np.uint8)
        self.action_space = Discrete(3)

    def step(self, action):
        actions = np.identity(3, dtype=np.uint8)
        reward = self.game.make_action(actions[action],4)

        if self.game.get_state():
            state = self.game.get_state().screen_buffer
            state.self.grayscale(state)
            ammo = self.game.get_state().game_variables[0]
            info = ammo
        else:
            state = np.zeros(self.observation_space.shape)
            info = 0

        info = {"info":info}
        done = self.game.is_episode_finished()

        return state, reward, done, info
    def render():
        pass
    def reset(self):
        self.game.new_episode()
        state = self.game.get_state().screen_buffer

        return self.grayscale(state)

    def grayscale(self, observation):
        gray = cv2.cvtColor(np.moveaxis(observation, 0, -1), cv2.COLOR_BGR2GRAY)
        resize = cv2.resize(gray, (160, 100), interpolation=cv2.INTER_CUBIC)
        state = np.reshape(resize, (100, 160,1))
        return state
    def close():
        self.game.close()

CHECKPOINT_DIR = './train/train_basic'
LOG_DIR = './logs/log_basic'

env = VizDoomGym()

model = PPO('CnnPolicy', env, tensorboard_log=LOG_DIR, verbose=1, learning_rate=0.0001, n_steps=2048)
model.learn(total_timesteps=100000, callback=callback)

I get the following error:

Traceback (most recent call last):
  File "DOOM.py", line 72, in <module>
    model = PPO('CnnPolicy', env, tensorboard_log=LOG_DIR, verbose=1, learning_rate=0.0001, n_steps=2048)
  File "C:\Users\lawri\AppData\Local\Programs\Python\Python37\lib\site-packages\stable_baselines3\ppo\ppo.py", line 130, in __init__
    spaces.MultiBinary,
  File "C:\Users\lawri\AppData\Local\Programs\Python\Python37\lib\site-packages\stable_baselines3\common\on_policy_algorithm.py", line 94, in __init__
    supported_action_spaces=supported_action_spaces,
  File "C:\Users\lawri\AppData\Local\Programs\Python\Python37\lib\site-packages\stable_baselines3\common\base_class.py", line 179, in __init__
    env = self._wrap_env(env, self.verbose, monitor_wrapper)
  File "C:\Users\lawri\AppData\Local\Programs\Python\Python37\lib\site-packages\stable_baselines3\common\base_class.py", line 228, in _wrap_env
    env = DummyVecEnv([lambda: env])
  File "C:\Users\lawri\AppData\Local\Programs\Python\Python37\lib\site-packages\stable_baselines3\common\vec_env\dummy_vec_env.py", line 27, in __init__
    VecEnv.__init__(self, len(env_fns), env.observation_space, env.action_space)
  File "C:\Users\lawri\AppData\Local\Programs\Python\Python37\lib\site-packages\gym\core.py", line 241, in __getattr__
    return getattr(self.env, name)
AttributeError: 'VizDoomGym' object has no attribute 'observation_space'

The tutorial I am following is: https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&cad=rja&uact=8&ved=2ahUKEwigzcLRtPH7AhX-S0EAHWAABmkQwqsBegQICBAG&url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DeBCU-tqLGfQ&usg=AOvVaw1THV8bvNXYB2aoO3Vi8iUC

I am using Python 3.7.0 with stable baselines 3 [Extras] and Gym 0.26 and a CPU version of PyTorch. The GitHub for the tutorial is here: https://github.com/nicknochnack/DoomReinforcementLearning/blob/main/VizDoom-Basic-Tutorial.ipynb

I expected for it to start training the re-enforcement learning model, I have searched up similar errors to which I didn't get a clear answer.


来源: stackexchange

问:
How to update database in laravel without id column
i have laravel migration code like this

```<code>public function up()
    {
        Schema::create('pakets', function (Blueprint $table) {
            $table->string('noResi')->primary();
            $table->unsignedBigInteger('idPengirim');
            $table->foreign('idPengirim')->references('id')->on('users')->onDelete('cascade');
            $table->unsignedBigInteger('jenisPaket');
            $table->foreign('jenisPaket')->references('id')->on('jenis_pakets')->onDelete('cascade');
            $table->float('berat');
            $table->float('volume');
            $table->string('namaPenerima');
            $table->string('noTelpPenerima');
            $table->string('alamatTujuan');
            $table->timestamps();
        });
    }
</code>```

i don't have id column, i replace it with "noResi" as primary key. But why when i want to update it show unknown column id?

I want it change data with noResi column, not id

ContentLicense: CC BY-SA 4.0

Body:
i have laravel migration code like this

public function up()
    {
        Schema::create('pakets', function (Blueprint $table) {
            $table->string('noResi')->primary();
            $table->unsignedBigInteger('idPengirim');
            $table->foreign('idPengirim')->references('id')->on('users')->onDelete('cascade');
            $table->unsignedBigInteger('jenisPaket');
            $table->foreign('jenisPaket')->references('id')->on('jenis_pakets')->onDelete('cascade');
            $table->float('berat');
            $table->float('volume');
            $table->string('namaPenerima');
            $table->string('noTelpPenerima');
            $table->string('alamatTujuan');
            $table->timestamps();
        });
    }

i don't have id column, i replace it with "noResi" as primary key. But why when i want to update it show unknown column id?

I want it change data with noResi column, not id


问:
FileNotFoundError at / [Errno 2] No such file or directory while saving an image
I want to create a qr-code generator for hashed values. However, it works pretty strange, because sometimes everything works good, but sometimes it gives me an error: FileNotFoundError at / [Errno 2] No such file or directory. For example, it can save a few qr-codes and then throw that error. Here is the code:

```<code>def qr_creator(request):
    for i in range(50):
        hash_uuid = uuid.uuid4
        hash = Hasher.encode(self=Hasher(), password=hash_uuid, salt=Hasher.salt(self=Hasher()))
        data = f"{hash}"
        img = make(data)
        img_name = f"{hash}.png"
        img.save(str(settings.MEDIA_ROOT) + '/qr_codes/' + img_name)
    return HttpResponse("Done!")
</code>```

As I understand, the problem lies in img_name as if I change it for example, like this: img_name = f"{hash}.png", everything works as it should be. But I need my qr-codes to be named strictly as hash values. So my question is how can I fix this so I can save my qr-codes with its values?

Thanks in advance

Body:
I want to create a qr-code generator for hashed values. However, it works pretty strange, because sometimes everything works good, but sometimes it gives me an error: FileNotFoundError at / [Errno 2] No such file or directory. For example, it can save a few qr-codes and then throw that error. Here is the code:

def qr_creator(request):
    for i in range(50):
        hash_uuid = uuid.uuid4
        hash = Hasher.encode(self=Hasher(), password=hash_uuid, salt=Hasher.salt(self=Hasher()))
        data = f"{hash}"
        img = make(data)
        img_name = f"{hash}.png"
        img.save(str(settings.MEDIA_ROOT) + '/qr_codes/' + img_name)
    return HttpResponse("Done!")

As I understand, the problem lies in img_name as if I change it for example, like this: img_name = f"{hash}.png", everything works as it should be. But I need my qr-codes to be named strictly as hash values. So my question is how can I fix this so I can save my qr-codes with its values?

Thanks in advance


问:
Telegram icon for font awesome not showing up
On my website built using Joomla 4, the following works fine (it displays the whatsapp icon):

```<code><span class="fa fa-whatsapp"> </span>
</code>```

But this doesn't (trying to display the telegram icon):

```<code><span class="fa fa-telegram"> </span>
</code>```

Although the same code for displaying telegram icon works on an older site built using Joomla 3.

I observed that, on old site, the following code is present in font-awesome.css and font-awesome.min.css. So I added the same code in the new site as well but it still doesn't work (just displays a box):

```<code>.fa-telegram:before {
    content: "\f2c6";
}
</code>```

Any idea why is this happening?

Body:
On my website built using Joomla 4, the following works fine (it displays the whatsapp icon):

But this doesn't (trying to display the telegram icon):

Although the same code for displaying telegram icon works on an older site built using Joomla 3.

I observed that, on old site, the following code is present in font-awesome.css and font-awesome.min.css. So I added the same code in the new site as well but it still doesn't work (just displays a box):

.fa-telegram:before {
    content: "\f2c6";
}

Any idea why is this happening?


问:
Launching Slack via C# code causes error during login with token on Web
I am trying to launch it via simple code when hyperlink is clicked and using its deeplink: slack:\\open

```<code>private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
    Hyperlink hyperlink = (Hyperlink)sender;

    Process.Start(new ProcessStartInfo(hyperlink.NavigateUri.AbsoluteUri));
}
</code>```

Error I am getting on Slack is below:

This can be reproduced if you ran Powershell as admin and launch the app and try to login to web it won't connect to desktop app.
I sure know there's a workaround if you click on "Copy Sign-In Key" but I want to avoid that error message.

Potential cause is that C# process launches Slack via System instead of using current User.
I am trying to explore using impersonation but could not seem to find the right code to be used.

Body:
I am trying to launch it via simple code when hyperlink is clicked and using its deeplink: slack:\\open

private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
    Hyperlink hyperlink = (Hyperlink)sender;

    Process.Start(new ProcessStartInfo(hyperlink.NavigateUri.AbsoluteUri));
}

Error I am getting on Slack is below:

This can be reproduced if you ran Powershell as admin and launch the app and try to login to web it won't connect to desktop app.
I sure know there's a workaround if you click on "Copy Sign-In Key" but I want to avoid that error message.

Potential cause is that C# process launches Slack via System instead of using current User.
I am trying to explore using impersonation but could not seem to find the right code to be used.


问:
Use another Activation Function in YOLOv7
How do you change the activation function in Yolov7? For example, the default activation function of yolov7 (except tiny) is SiLU according to YOLOv7 paper and I want to change to ReLU or other activation functions

I found a solution but it's for yolov5.


问:
Android Studio Build Wear OS module not building
So. In my Android Studio project there is both an App for mobile and a module for wear OS. Debugging works perfect. The app can communicate with the wear app when i install it via androids debugging.
But when i try to build signed app bundles, there is only one aab file. Then yea the wear app might be included that, so i try to upload it to playstore, but the playstore doesnt seem to recognize the wear module and doesnt even show an option to add wear screenshots, as if theres no wear module.
I cant seem to find a solution for day. And there is so little discussion on Stackoverflow and other places about Wear OS

I tried to select the either app or wearapp for creating aab but either way it just made one.

Secondly the package names and build versions are the same.


问:
Convert query from MySQL to PostgreSQL: unlucky employees
I am trying to get this query for a database question( Unlucky wmployees) to Postgres. I am having a hard time getting it right

```<code>CREATE PROCEDURE unluckyEmployees()
BEGIN
    SET @rn =0;
    SELECT dep_name, emp_number, total_salary FROM
    (SELECT dep_name, emp_number, total_salary, (@rn := @rn + 1) as seqnum  FROM
    (SELECT name AS dep_name, IF(e.id IS NULL, 0, COUNT(*)) AS emp_number,  IFNULL(SUM(salary), 0) AS total_salary
     FROM Department d LEFT JOIN Employee e ON e.Department = d.id
    GROUP BY d.id HAVING COUNT(*) < 6 ORDER BY SUM(salary) DESC, COUNT(*) DESC, d.id) t )tt  WHERE mod(seqnum, 2) = 1;
END
</code>```

I am hoping to get the query in postgres. Tried setting @rn to row_number() but still not working.

Body:
I am trying to get this query for a database question( Unlucky wmployees) to Postgres. I am having a hard time getting it right

CREATE PROCEDURE unluckyEmployees()
BEGIN
    SET @rn =0;
    SELECT dep_name, emp_number, total_salary FROM
    (SELECT dep_name, emp_number, total_salary, (@rn := @rn + 1) as seqnum  FROM
    (SELECT name AS dep_name, IF(e.id IS NULL, 0, COUNT(*)) AS emp_number,  IFNULL(SUM(salary), 0) AS total_salary
     FROM Department d LEFT JOIN Employee e ON e.Department = d.id
    GROUP BY d.id HAVING COUNT(*) < 6 ORDER BY SUM(salary) DESC, COUNT(*) DESC, d.id) t )tt  WHERE mod(seqnum, 2) = 1;
END

I am hoping to get the query in postgres. Tried setting @rn to row_number() but still not working.


问:
retrieving data from the intersection cells of a row and column in an excel file with python
enter image description herehow to get data from the intersection cells of a row and column in an excel file with python.
the first row in the excel table gives the time information
in the first column there is information about what day the project is.

I want to do.
if project 3. if it is during the day and the Decembers are between 00.00 and 01.00, I want to print the value 45

i don't know how I can get there, I'm waiting for your help, thank you very much


问:
Next-auth Credentials Provider authenticated state doesn't update
I'm using next-auth 4.18.4 and can't figure out how to set up the Credential provider properly. At this point, when the user logs in, the status remains unauthenticated, and only updates to authenticated when I refresh the page. This is what I have in api/auth/[...nextauth].ts:

import NextAuth from 'next-auth'
import CredentialsProvider from 'next-auth/providers/credentials'
import { verifyPassword } from '../../../lib/auth'
import conn from '../../../lib/db'

export default NextAuth({
  providers: [
    CredentialsProvider({
      async authorize(credentials) {
        const query = `SELECT * FROM users WHERE username = $1`
        const values = [ credentials.username ]
        let user
        try {
          const result = await conn.query(query, values)
          if (result.rows.length > 0) user = result.rows[0]
        } catch (err) {
          console.log(`Error fetching user from DB: ${err.stack}`)
          throw new Error(err)
        }

        if (!user) throw new Error('No user found!')

        const isValid = await verifyPassword(
          credentials?.password,
          user.password
        )

        if (!isValid) throw new Error('Could not log you in!')

        return {
          uid: user.id,
          username: user.username,
          profilePic: user.profile_pic
        }
      },
    }),
  ],
})

```
<p>This is my login page:</p>
<pre class="lang-js prettyprint-override"><code>import { useForm } from 'react-hook-form'
import { z } from 'zod'
import { zodResolver } from '@hookform/resolvers/zod'
import { signIn } from 'next-auth/react'
import { useRouter } from 'next/router'

import Input from "../components/input"

const validationSchema = z
  .object({
    userName: z
      .string()
      .min(1, { message: 'Username is required' })
      .regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[A-Za-z\d]{5,10}$/, {
        message: '5-10 upper and lowercase letters, and digits',
      }),
    password: z
      .string()
      .min(5, { message: 'Between 5-10 characters' })
      .regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[A-Za-z\d]{5,10}$/, {
        message: 'Upper and lowercase letters, and digits',
      })
  })

export default function Auth() {
  const {
    register,
    handleSubmit,
    watch,
    formState: { errors, isValid },
    setValue
  } = useForm({
    mode: 'all',
    resolver: zodResolver(validationSchema),
  })
  const router = useRouter()

  async function submitHandler(data: any) {
    const result = await signIn('credentials', {
      redirect: false, // don't redirect if user enters wrong credentials
      username: data.userName,
      password: data.password
    })
    // console.log(result) // testing

    // If the 'error' property is null (meaning log in was successful)
    if (!result?.error) {
      // Let's clear the input fields
      setValue('userName', '')
      setValue('password', '')
      // And redirect the user to the main page
      router.replace('/')
    } else {
      // If the 'error' property was false, let's print the login error
      console.log(`Error: ${JSON.stringify(result.error)}`)
    }
  }

  return (
    <div className='text-white max-w-4xl mx-auto pt-10 pb-20 px-2'>
      <h1 className='text-2xl text-center pb-8'>Log in</h1>

      <form
        onSubmit={handleSubmit(submitHandler)}
        className='space-y-4 flex flex-col items-center '
      >
        <Input
          id='userName'
          type='text'
          label='Username'
          register={register}
          registerOptions={{ required: true }}
          errors={errors}
          isRequired={true}
        />

        <Input
          id='password'
          type='password'
          label='Password'
          register={register}
          registerOptions={{ required: true }}
          errors={errors}
          isRequired={true}
        />

        <button
          type='submit'
          disabled={!isValid}
          className={`p-3 border-[1px] border-slate-500 rounded-md hover:enabled:bg-white hover:enabled:bg-opacity-20 disabled:cursor-not-allowed w-[90%]`}
        >
          {isValid ? 'Log In' : 'Please, fill the form'}
        </button>
      </form>
    </div>
  )
}
</code>```

And my index page:

import { useSession } from 'next-auth/react'

export default function Home() {
  const { data: session, status } = useSession()
  console.log(status);

  return (

Home Page

      {status === 'authenticated' ?
      (
Logged in!
)
      :
      (
Not logged in!
)
      }

  )
}
```
<p>And the session provider in <code>_app.ts</code>:</p>
<pre class="lang-js prettyprint-override"><code>import '../styles/globals.css'
import type { AppProps } from 'next/app'
import Layout from '../components/layout'
import { SessionProvider } from 'next-auth/react'

export default function App({
  Component,
  pageProps: { session, ...pageProps },
}) {
  return (
    <SessionProvider session={session}>
      <Layout>
        <Component {...pageProps} />
      </Layout>
    </SessionProvider>
  )
}
</code>```

By the way, I forgot to add that after logging in, I can see the next-auth.session cookie being created in the browser, but still, status doesn't change until I reload.

Body:
I'm using next-auth 4.18.4 and can't figure out how to set up the Credential provider properly. At this point, when the user logs in, the status remains unauthenticated, and only updates to authenticated when I refresh the page. This is what I have in api/auth/[...nextauth].ts:

import NextAuth from 'next-auth'
import CredentialsProvider from 'next-auth/providers/credentials'
import { verifyPassword } from '../../../lib/auth'
import conn from '../../../lib/db'

export default NextAuth({
  providers: [
    CredentialsProvider({
      async authorize(credentials) {
        const query = `SELECT * FROM users WHERE username = $1`
        const values = [ credentials.username ]
        let user
        try {
          const result = await conn.query(query, values)
          if (result.rows.length > 0) user = result.rows[0]
        } catch (err) {
          console.log(`Error fetching user from DB: ${err.stack}`)
          throw new Error(err)
        }

        if (!user) throw new Error('No user found!')

        const isValid = await verifyPassword(
          credentials?.password,
          user.password
        )

        if (!isValid) throw new Error('Could not log you in!')

        return {
          uid: user.id,
          username: user.username,
          profilePic: user.profile_pic
        }
      },
    }),
  ],
})

This is my login page:

import { useForm } from 'react-hook-form'
import { z } from 'zod'
import { zodResolver } from '@hookform/resolvers/zod'
import { signIn } from 'next-auth/react'
import { useRouter } from 'next/router'

import Input from "../components/input"

const validationSchema = z
  .object({
    userName: z
      .string()
      .min(1, { message: 'Username is required' })
      .regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[A-Za-z\d]{5,10}$/, {
        message: '5-10 upper and lowercase letters, and digits',
      }),
    password: z
      .string()
      .min(5, { message: 'Between 5-10 characters' })
      .regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[A-Za-z\d]{5,10}$/, {
        message: 'Upper and lowercase letters, and digits',
      })
  })

export default function Auth() {
  const {
    register,
    handleSubmit,
    watch,
    formState: { errors, isValid },
    setValue
  } = useForm({
    mode: 'all',
    resolver: zodResolver(validationSchema),
  })
  const router = useRouter()

  async function submitHandler(data: any) {
    const result = await signIn('credentials', {
      redirect: false, // don't redirect if user enters wrong credentials
      username: data.userName,
      password: data.password
    })
    // console.log(result) // testing

    // If the 'error' property is null (meaning log in was successful)
    if (!result?.error) {
      // Let's clear the input fields
      setValue('userName', '')
      setValue('password', '')
      // And redirect the user to the main page
      router.replace('/')
    } else {
      // If the 'error' property was false, let's print the login error
      console.log(`Error: ${JSON.stringify(result.error)}`)
    }
  }

  return (

Log in

      <form
        onSubmit={handleSubmit(submitHandler)}
        className='space-y-4 flex flex-col items-center '
      >
        <Input
          id='userName'
          type='text'
          label='Username'
          register={register}
          registerOptions={{ required: true }}
          errors={errors}
          isRequired={true}
        />

        <Input
          id='password'
          type='password'
          label='Password'
          register={register}
          registerOptions={{ required: true }}
          errors={errors}
          isRequired={true}
        />

        <button
          type='submit'
          disabled={!isValid}
          className={`p-3 border-[1px] border-slate-500 rounded-md hover:enabled:bg-white hover:enabled:bg-opacity-20 disabled:cursor-not-allowed w-[90%]`}
        >
          {isValid ? 'Log In' : 'Please, fill the form'}
        </button>
      </form>

  )
}

And my index page:

import { useSession } from 'next-auth/react'

export default function Home() {
  const { data: session, status } = useSession()
  console.log(status);

  return (

Home Page

      {status === 'authenticated' ?
      (
Logged in!
)
      :
      (
Not logged in!
)
      }

  )
}

And the session provider in _app.ts:

import '../styles/globals.css'
import type { AppProps } from 'next/app'
import Layout from '../components/layout'
import { SessionProvider } from 'next-auth/react'

export default function App({
  Component,
  pageProps: { session, ...pageProps },
}) {
  return (
    <SessionProvider session={session}>
      <Layout>
        <Component {...pageProps} />
      </Layout>
    </SessionProvider>
  )
}

By the way, I forgot to add that after logging in, I can see the next-auth.session cookie being created in the browser, but still, status doesn't change until I reload.


问:
Pictures occupying more space than their actual size in RAM - Torch Data Loader
I am a Google Colab Pro user,which provides me 80GB amount of RAM. I'm trying to make a dataset for classification task. The total size of train and validation files is around 4GB. However, even though i have 80GB RAM (79GB avaliable when start-up). torch.utils.data.DataLoader crashes because of not adequate of RAM. How i can fix this problem. Thank you in advance.

Calling the function in main .py file

```<code>target_names = ['class 0', 'class 1']

samples_train, labels_train, samples_val, labels_val, num_train_instances, num_val_instances = data_load(num_workers=0)
</code>```

Imported file(data_Load)

```<code>import torch
import torchvision
from torchvision import transforms
from torch.autograd import Variable
from tqdm import tqdm
import time

def data_load(num_workers = 0):
    # load data

    data_transform = transforms.Compose([
                #transforms.Grayscale(1),
                transforms.Resize((256,256)),
                transforms.ToTensor(),
                transforms.RandomHorizontalFlip(p=0.5)

            ])

    # B-mode data loader
    train_data_Bmode = torchvision.datasets.ImageFolder(root='./data1/train', transform=data_transform)
    #print(train_data_Bmode.class_to_idx)
    train_data_Bmode_loader = torch.utils.data.DataLoader(train_data_Bmode, batch_size=16,  shuffle=False, num_workers=num_workers,pin_memory = True,drop_last=True)
    num_train_instances = len(train_data_Bmode)
    print("num_train_instances",num_train_instances)
    #print(type(train_data_Bmode_loader))

    val_data_Bmode = torchvision.datasets.ImageFolder(root='./data1/val', transform=data_transform)
    val_data_Bmode_loader = torch.utils.data.DataLoader(val_data_Bmode, batch_size=16, shuffle=False, num_workers=num_workers, pin_memory = True,drop_last=True)
    num_val_instances = len(val_data_Bmode)
    print("num_val_instances",num_val_instances)

</code>```

Body:
I am a Google Colab Pro user,which provides me 80GB amount of RAM. I'm trying to make a dataset for classification task. The total size of train and validation files is around 4GB. However, even though i have 80GB RAM (79GB avaliable when start-up). torch.utils.data.DataLoader crashes because of not adequate of RAM. How i can fix this problem. Thank you in advance.

Calling the function in main .py file

target_names = ['class 0', 'class 1']

samples_train, labels_train, samples_val, labels_val, num_train_instances, num_val_instances = data_load(num_workers=0)

Imported file(data_Load)

import torch
import torchvision
from torchvision import transforms
from torch.autograd import Variable
from tqdm import tqdm
import time

def data_load(num_workers = 0):
    # load data

    data_transform = transforms.Compose([
                #transforms.Grayscale(1),
                transforms.Resize((256,256)),
                transforms.ToTensor(),
                transforms.RandomHorizontalFlip(p=0.5)

            ])

    # B-mode data loader
    train_data_Bmode = torchvision.datasets.ImageFolder(root='./data1/train', transform=data_transform)
    #print(train_data_Bmode.class_to_idx)
    train_data_Bmode_loader = torch.utils.data.DataLoader(train_data_Bmode, batch_size=16,  shuffle=False, num_workers=num_workers,pin_memory = True,drop_last=True)
    num_train_instances = len(train_data_Bmode)
    print("num_train_instances",num_train_instances)
    #print(type(train_data_Bmode_loader))

    val_data_Bmode = torchvision.datasets.ImageFolder(root='./data1/val', transform=data_transform)
    val_data_Bmode_loader = torch.utils.data.DataLoader(val_data_Bmode, batch_size=16, shuffle=False, num_workers=num_workers, pin_memory = True,drop_last=True)
    num_val_instances = len(val_data_Bmode)
    print("num_val_instances",num_val_instances)


问:
Rust fmt configuration for vertical chaining
The following is what I desire to format to:

```<code>async fn main() {
    let req = reqwest::get("http://wttr.in/brisbane")
        .await
        .expect("Failed to get weather data")
        .text()
        .await;
}
</code>```

This is what I get (unless it does not fit on the one line, then it will format it like above):

```<code>    let req = reqwest::get("http://wttr.in/brisbane").await.expect("Failed to get weather data").text().await;
</code>```

I want it to always format vertically, regardless of width. How can I do this?

Body:
The following is what I desire to format to:

async fn main() {
    let req = reqwest::get("http://wttr.in/brisbane")
        .await
        .expect("Failed to get weather data")
        .text()
        .await;
}

This is what I get (unless it does not fit on the one line, then it will format it like above):

    let req = reqwest::get("http://wttr.in/brisbane").await.expect("Failed to get weather data").text().await;

I want it to always format vertically, regardless of width. How can I do this?


问:
QgsField won't accept parameter typeName
I'm trying to create new vector layer with the same fields as contained in original layer.

original_layer_fields_list = original_layer.fields().toList()
new_layer = QgsVectorLayer("Point", "new_layer", "memory")
pr = new_layer.dataProvider()
```
<p>However, when I try:</p>
<pre class="lang-py prettyprint-override"><code>for fld in original_layer_fields_list:
    type_name = fld.typeName()
    pr.addAttributes([QgsField(name = fld.name(), typeName = type_name)])
    new_layer.updateFields()

QgsProject.instance().addMapLayer(new_layer)
</code>```

I get a layer with no fields in attribute table.

If I try something like:

for fld in original_layer_fields_list:
    if fld.type() == 2:
        pr.addAttributes([QgsField(name = fld.name(), type = QVariant.Int)])
        new_layer.updateFields()

QgsProject.instance().addMapLayer(new_layer)
```

... it works like charm.

Anyway ... I'd rather like the first solution to work in case if one wants to automate the process and not check for every field type and then find an appropriate code. Besides - I really am not able to find any documentation about codes for data types. I managed to find this post https://gis.stackexchange.com/questions/353975/get-only-fields-with-datatype-int-in-pyqgis where in comments Kadir pointed on this sourcecode (https://codebrowser.dev/qt5/qtbase/src/corelib/kernel/qvariant.h.html#QVariant::Type).

I'd really be thankful for any kind of direction.

Body:
I'm trying to create new vector layer with the same fields as contained in original layer.

original_layer_fields_list = original_layer.fields().toList()
new_layer = QgsVectorLayer("Point", "new_layer", "memory")
pr = new_layer.dataProvider()

However, when I try:

for fld in original_layer_fields_list:
    type_name = fld.typeName()
    pr.addAttributes([QgsField(name = fld.name(), typeName = type_name)])
    new_layer.updateFields()

QgsProject.instance().addMapLayer(new_layer)

I get a layer with no fields in attribute table.

If I try something like:

for fld in original_layer_fields_list:
    if fld.type() == 2:
        pr.addAttributes([QgsField(name = fld.name(), type = QVariant.Int)])
        new_layer.updateFields()

QgsProject.instance().addMapLayer(new_layer)

... it works like charm.

Anyway ... I'd rather like the first solution to work in case if one wants to automate the process and not check for every field type and then find an appropriate code. Besides - I really am not able to find any documentation about codes for data types. I managed to find this post https://gis.stackexchange.com/questions/353975/get-only-fields-with-datatype-int-in-pyqgis where in comments Kadir pointed on this sourcecode (https://codebrowser.dev/qt5/qtbase/src/corelib/kernel/qvariant.h.html#QVariant::Type).

I'd really be thankful for any kind of direction.


问:
How to create routes to plugins after initialization
guys. I'm working on a modular admin system, based on Codeigniter 4 (as backend) and Vue.JS as frontend.

The main requirement for Codeigniter is that the system be completely modular, that is, by deleting a folder – you can remove, say, blog (news) management, or vice versa - add a file module and manage files (let's say – it's plugins, a bit like wordpress).

The main problem is that I want to make a SPA (single page app), and vue router requires a list of routes when it's init. At the login stage, I know that there are only standard (mandatory) pages: login, forgot (password reset), dashboard, settings (user settings). The backend will show other plugins only after successful authorization (example): news, pages manager, items (manage shop items) etc. And each of them can have several more routes for managing inside: create (add new record to database), edit, delete, view (card of record).

Is it possible to implement this with Vue router so that we get a SPA? Or can SPA be implemented only with a static (when it is clear how many pages there will be) project?

For better understanding, my plugins have all the necessary structure and are completely independent. Previously, when I didn’t use the Vue.js router, PHP went through all the plugin folders and collected a link (it creates array with links and at the header template I go through this array) to them for the menu , let's say from a file menu.php, in which was link (for example only):

```<code><?php

    $menu['main'][] = array(
                'type' => 'item',  // item or sub-item for menu
        'link' => MODULES_URL.'pages/items',  // link to main page of plugin (by default list of records for this plugin)
        'title' => 'Pages Manager',  // name of page
        'active' =>  ($this->uri->segment(3) == 'pages'), // is active link? for menu
        'icon' => 'fa fa-pencil-square' // icon for menu
    );

?>
</code>```

Body:
guys. I'm working on a modular admin system, based on Codeigniter 4 (as backend) and Vue.JS as frontend.

The main requirement for Codeigniter is that the system be completely modular, that is, by deleting a folder – you can remove, say, blog (news) management, or vice versa - add a file module and manage files (let's say – it's plugins, a bit like wordpress).

The main problem is that I want to make a SPA (single page app), and vue router requires a list of routes when it's init. At the login stage, I know that there are only standard (mandatory) pages: login, forgot (password reset), dashboard, settings (user settings). The backend will show other plugins only after successful authorization (example): news, pages manager, items (manage shop items) etc. And each of them can have several more routes for managing inside: create (add new record to database), edit, delete, view (card of record).

Is it possible to implement this with Vue router so that we get a SPA? Or can SPA be implemented only with a static (when it is clear how many pages there will be) project?

For better understanding, my plugins have all the necessary structure and are completely independent. Previously, when I didn’t use the Vue.js router, PHP went through all the plugin folders and collected a link (it creates array with links and at the header template I go through this array) to them for the menu , let's say from a file menu.php, in which was link (for example only):

<?php

    $menu['main'][] = array(
                'type' => 'item',  // item or sub-item for menu
        'link' => MODULES_URL.'pages/items',  // link to main page of plugin (by default list of records for this plugin)
        'title' => 'Pages Manager',  // name of page
        'active' =>  ($this->uri->segment(3) == 'pages'), // is active link? for menu
        'icon' => 'fa fa-pencil-square' // icon for menu
    );

?>


问:
How do I pass an audio file into the microphone?
I know the question does not seems to make sense but let me explain.

So I have a voice changer software that Change the voice in real time. If i open the audacity and choose the micro of that software I can speak and record with the voice changed.

Now what I want is, I have a audio file already recorded and I want to pass that file into that same microphone (to simulate me speaking) and save the output with the voice changed in another file. I made some attemps using pyaudio but no success.

The idea here is to use a tts module in python to read a dataset I have with multiple lines, save the output in a file and then pass that output to the microphone to change the voice and save in another file. That way I can automate a creation of a new dataset with a new speaker to train a new tts. But the problem is I missing the way to pass a file to the microphone to simulate me speaking to it but instead using an audio file already recorded.

Sorry of it was confused. I made my best to explain. Hope someone can help me.

Thank you in advanced!

This is what I have but no success.

```<code>
import pyaudio
import wave

# Open the audio file

wf = wave.open("my_audio_file.wav", "rb")

 # Open the output file

wf_out = wave.open("my_output_file.wav", "wb")

# Set the output file's format and parameters to match the input file

wf_out.setframerate(wf.getframerate())
wf_out.setsampwidth(wf.getsampwidth())
wf_out.setnchannels(wf.getnchannels())

# Open the microphone using pyaudio

p = pyaudio.PyAudio()

# Create a stream to send the audio data to the microphone

stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
channels=wf.getnchannels(),
rate=wf.getframerate(),
 output=True)

# Start streaming the audio data to the microphone

stream.start_stream()

# Send the audio data to the stream and output file

data = wf.readframes(1024)

while data != "":
stream.write(data)
wf_out.writeframes(data)
data = wf.readframes(1024)

# Stop the stream
stream.stop_stream()

# Close the stream, microphone, and output file
stream.close()
p.terminate()
wf_out.close()
</code>```

Body:
I know the question does not seems to make sense but let me explain.

So I have a voice changer software that Change the voice in real time. If i open the audacity and choose the micro of that software I can speak and record with the voice changed.

Now what I want is, I have a audio file already recorded and I want to pass that file into that same microphone (to simulate me speaking) and save the output with the voice changed in another file. I made some attemps using pyaudio but no success.

The idea here is to use a tts module in python to read a dataset I have with multiple lines, save the output in a file and then pass that output to the microphone to change the voice and save in another file. That way I can automate a creation of a new dataset with a new speaker to train a new tts. But the problem is I missing the way to pass a file to the microphone to simulate me speaking to it but instead using an audio file already recorded.

Sorry of it was confused. I made my best to explain. Hope someone can help me.

Thank you in advanced!

This is what I have but no success.

import pyaudio
import wave

# Open the audio file

wf = wave.open("my_audio_file.wav", "rb")

 # Open the output file

wf_out = wave.open("my_output_file.wav", "wb")

# Set the output file's format and parameters to match the input file

wf_out.setframerate(wf.getframerate())
wf_out.setsampwidth(wf.getsampwidth())
wf_out.setnchannels(wf.getnchannels())

# Open the microphone using pyaudio

p = pyaudio.PyAudio()

# Create a stream to send the audio data to the microphone

stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
channels=wf.getnchannels(),
rate=wf.getframerate(),
 output=True)

# Start streaming the audio data to the microphone

stream.start_stream()

# Send the audio data to the stream and output file

data = wf.readframes(1024)

while data != "":
stream.write(data)
wf_out.writeframes(data)
data = wf.readframes(1024)

# Stop the stream
stream.stop_stream()

# Close the stream, microphone, and output file
stream.close()
p.terminate()
wf_out.close()


问:
how do i Make the Fill/NoFill and Colour buttons display the currently selected state and colour in some way using a method
I want to change my ui.addbutton "fill color" so that it has a background color of what the user selects using the doSetFillColor method:

```<code>import ecs100.*;
import java.awt.Color;
import javax.swing.JColorChooser;

public void setupGUI(){
    UI.addButton("Clear", UI::clearGraphics);
    UI.addButton("Line", this::doSetLine);
    UI.addButton("Rect", this::doRect);
    UI.addButton("Oval", this::doOval);
    UI.addTextField("Enter Text", this::doCaption);
    UI.addButton("Image", this::doImage);
    UI.addButton("Eraser", this::doSetEraser);
    UI.addButton("Freehand", this::doFreehand);
    UI.addButton("Fill or No Fill", this::doSetFill);
    UI.addButton("Fill Color", this::doSetFillColor);
    UI.addButton("Line Color", this::doSetLineColor);
    UI.addSlider("Line Width", 1, 19, this.width, this::doSetLineWidth);
    UI.addSlider("Text Size", 1, 40, this.textSize, this::doSetTextSize);
    UI.setMouseMotionListener(this::doMouse);
    UI.addButton("Quit", UI::quit);
    UI.setDivider(0.0);  // Hide the text area.
}

public void doSetFillColor(){
    this.FillColor = JColorChooser.showDialog(null, "", this.FillColor);
    UI.setColor(this.FillColor);
}
</code>```

I have tried everything but it usually doesn't change the color of the button image is here

Body:
I want to change my ui.addbutton "fill color" so that it has a background color of what the user selects using the doSetFillColor method:

import ecs100.*;
import java.awt.Color;
import javax.swing.JColorChooser;

public void setupGUI(){
    UI.addButton("Clear", UI::clearGraphics);
    UI.addButton("Line", this::doSetLine);
    UI.addButton("Rect", this::doRect);
    UI.addButton("Oval", this::doOval);
    UI.addTextField("Enter Text", this::doCaption);
    UI.addButton("Image", this::doImage);
    UI.addButton("Eraser", this::doSetEraser);
    UI.addButton("Freehand", this::doFreehand);
    UI.addButton("Fill or No Fill", this::doSetFill);
    UI.addButton("Fill Color", this::doSetFillColor);
    UI.addButton("Line Color", this::doSetLineColor);
    UI.addSlider("Line Width", 1, 19, this.width, this::doSetLineWidth);
    UI.addSlider("Text Size", 1, 40, this.textSize, this::doSetTextSize);
    UI.setMouseMotionListener(this::doMouse);
    UI.addButton("Quit", UI::quit);
    UI.setDivider(0.0);  // Hide the text area.
}

public void doSetFillColor(){
    this.FillColor = JColorChooser.showDialog(null, "", this.FillColor);
    UI.setColor(this.FillColor);
}

I have tried everything but it usually doesn't change the color of the button image is here


问:
Creating a Certificate Signing Request failed
I am trying to create a Certificate Signing Request in Rust programmatically with the binding library https://docs.rs/openssl/latest/openssl/index.html.

The following statement creates a CSR with openssl library:

```<code>openssl ecparam -name prime256v1 \
                -genkey \
                -noout \
                -out server.key.pem
status=$?
if [ $status -eq 1 ]; then
    echo "Creating private key failed"
    exit 1
fi

openssl req \
       -key server.key.pem \
       -subj "/CN=server.acme.io/C=CH/L=Zurich/ST=ZH/O=acme/OU=acme" \
       -new -sha256 \
       -out server.csr
status=$?
if [ $status -eq 1 ]; then
    echo "CSR creation failed"
    exit 1
fi
</code>```

Unfortunately, the following code snippet using the Rust binding library does not work:

```<code>use openssl::nid::Nid;
use openssl::ec::{EcGroup, EcKey};
use openssl::error::ErrorStack;
use openssl::x509::{X509NameBuilder, X509ReqBuilder};
use openssl::hash::MessageDigest;
use openssl::pkey::{PKey};

fn main() -> Result<(), ErrorStack> {
    let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1)?;
    let ec = EcKey::generate(&group)?;
    let private_key = PKey::from_ec_key(ec)?;

    let mut name = X509NameBuilder::new()?;
    name.append_entry_by_nid(Nid::COUNTRYNAME, "CH")?;
    name.append_entry_by_nid(Nid::STATEORPROVINCENAME, "ZH")?;
    name.append_entry_by_nid(Nid::LOCALITYNAME, "Zurich")?;
    name.append_entry_by_nid(Nid::ORGANIZATIONALUNITNAME, "ACME")?;
    name.append_entry_by_nid(Nid::ORGANIZATIONNAME, "ACME")?;
    name.append_entry_by_nid(Nid::COMMONNAME, "acme.io")?;

    let mut req = X509ReqBuilder::new()?;
    req.set_subject_name(name.build().as_ref())?;
    req.sign(private_key.as_ref(), MessageDigest::sha256())?;

    Ok(())
}
</code>```

It shows the error message:

```<code>Error: ErrorStack([Error { code: 109052126, library: "asn1 encoding routines", function: "asn1_template_ex_i2d", reason: "illegal zero content", file: "crypto/asn1/tasn_enc.c", line: 374 }, Error { code: 109838595, library: "asn1 encoding routines", function: "ASN1_item_sign_ctx", reason: "internal error", file: "crypto/asn1/a_sign.c", line: 265 }])
</code>```

What am I doing wrong? All the required fields are filled with values.

Body:
I am trying to create a Certificate Signing Request in Rust programmatically with the binding library https://docs.rs/openssl/latest/openssl/index.html.

The following statement creates a CSR with openssl library:

openssl ecparam -name prime256v1 \
                -genkey \
                -noout \
                -out server.key.pem
status=$?
if [ $status -eq 1 ]; then
    echo "Creating private key failed"
    exit 1
fi

openssl req \
       -key server.key.pem \
       -subj "/CN=server.acme.io/C=CH/L=Zurich/ST=ZH/O=acme/OU=acme" \
       -new -sha256 \
       -out server.csr
status=$?
if [ $status -eq 1 ]; then
    echo "CSR creation failed"
    exit 1
fi

Unfortunately, the following code snippet using the Rust binding library does not work:

use openssl::nid::Nid;
use openssl::ec::{EcGroup, EcKey};
use openssl::error::ErrorStack;
use openssl::x509::{X509NameBuilder, X509ReqBuilder};
use openssl::hash::MessageDigest;
use openssl::pkey::{PKey};

fn main() -> Result<(), ErrorStack> {
    let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1)?;
    let ec = EcKey::generate(&group)?;
    let private_key = PKey::from_ec_key(ec)?;

    let mut name = X509NameBuilder::new()?;
    name.append_entry_by_nid(Nid::COUNTRYNAME, "CH")?;
    name.append_entry_by_nid(Nid::STATEORPROVINCENAME, "ZH")?;
    name.append_entry_by_nid(Nid::LOCALITYNAME, "Zurich")?;
    name.append_entry_by_nid(Nid::ORGANIZATIONALUNITNAME, "ACME")?;
    name.append_entry_by_nid(Nid::ORGANIZATIONNAME, "ACME")?;
    name.append_entry_by_nid(Nid::COMMONNAME, "acme.io")?;

    let mut req = X509ReqBuilder::new()?;
    req.set_subject_name(name.build().as_ref())?;
    req.sign(private_key.as_ref(), MessageDigest::sha256())?;

    Ok(())
}

It shows the error message:

Error: ErrorStack([Error { code: 109052126, library: "asn1 encoding routines", function: "asn1_template_ex_i2d", reason: "illegal zero content", file: "crypto/asn1/tasn_enc.c", line: 374 }, Error { code: 109838595, library: "asn1 encoding routines", function: "ASN1_item_sign_ctx", reason: "internal error", file: "crypto/asn1/a_sign.c", line: 265 }])

What am I doing wrong? All the required fields are filled with values.


问:
Is there any way to further improve this security configuration of Apache 2 sever on Ubuntu?
I am setting up an Apache 2 server on Ubuntu.

```<code>Ubuntu Version: 20.04.5 LTS (GNU/Linux 5.4.0-135-generic x86_64)
Server version: Apache/2.4.41 (Ubuntu)
</code>```

The web application "currently" does not accept upload nor runs any cgi script, nor does request or provide any authentication from any users, nor does have an sql database.

I would like to know if there is any additional directive to add to any of the following configuration files to improve further the security.

The files in their respective directories are:

```<code># apache2.conf
# security.conf
# 000-default.conf
# example.com-ssl.conf
</code>```

apache2.conf

```<code># shm and runtimes  directory
DefaultRuntimeDir ${APACHE_RUN_DIR}

# PidFile
PidFile ${APACHE_PID_FILE}

# Timeout
Timeout 300

# KeepAlive
KeepAlive On

# MaxKeepAliveRequests
MaxKeepAliveRequests 100

# KeepAliveTimeout
KeepAliveTimeout 5

# Added by me for better caching performance
<FilesMatch "\.(html|css|gif|jpg|jpeg|js|png|svg|webp)$">
     Header set Cache-Control "max-age=31536000, public"
</FilesMatch>

# Added by me to hide last modified and just use the e-tag
Header unset Last-Modified

# These need to be set in /etc/apache2/envvars
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}

# HostnameLookups
HostnameLookups Off

# ErrorLog
ErrorLog ${APACHE_LOG_DIR}/error.log

# LogLevel
LogLevel warn

# Include module configuration:
IncludeOptional mods-enabled/*.load
IncludeOptional mods-enabled/*.conf

# Include list of ports to listen on
Include ports.conf

# Sets the default direct sec
<Directory />
    Options FollowSymLinks
    AllowOverride None
    Require all denied
</Directory>

<Directory /usr/share>
    AllowOverride None
    Require all granted
</Directory>

<Directory /var/www/>
    Options -Indexes -FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

#AccessFileName .htaccess

# The following lines prevent .htaccess and .htpasswd access
<FilesMatch "^\.ht">
    Require all denied
</FilesMatch>

# The format directories
LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent

# Include generic snippets of statements
IncludeOptional conf-enabled/*.conf

# Include the virtual host configurations:
IncludeOptional sites-enabled/*.conf
</code>```

security.conf

```<code># ServerTokens
ServerTokens Prod

# Server Signature
ServerSignature Off

# Allow TRACE
TraceEnable Off

# Header X content
Header set X-Content-Type-Options: "nosniff"

# Header X frame
Header set X-Frame-Options: "sameorigin"
</code>```

000-default.conf

```<code><VirtualHost *:80>
    # Server Name
    ServerName example.com

    # Server Alias
    ServerAlias www.example.com

    # Server Admin
    ServerAdmin admin@example.com

    # Document root directory
    DocumentRoot /var/www/html

    # Redirect all http traffic
    Redirect permanent / https://example.com

    # logs
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # No CGI allowed for the time being.
    #Include conf-available/serve-cgi-bin.conf
</VirtualHost>
</code>```

example.com-ssl.conf

```<code><VirtualHost *:443>
    # Https 2
    Protocols h2 http/1.1

    # Sever Name
    ServerName example.com

    # Server Alias
    ServerAlias www.example.com

    # Server Admin
    ServerAdmin admin@example.com

    # Document root directory
    DocumentRoot /var/www/html

    # SSL
    SSLEngine on
    SSLCertificateFile /etc/ssl/example.com.crt
    SSLCertificateKeyFile /etc/ssl/example.com.key
    SSLCertificateChainFile /etc/ssl/example.com.ca-bundle

    # Logs
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # No CGI allowed for the time being
    #Include conf-available/serve-cgi-bin.conf
</VirtualHost>
</code>```

Here after is also the list of apache 2 module which are currently enabled:

```<code>access_compat.load
alias.conf
alias.load
auth_basic.load
authn_core.load
authn_file.load
authz_core.load
authz_host.load
authz_user.load
autoindex.conf
autoindex.load
deflate.conf
deflate.load
dir.conf
dir.load
env.load
filter.load
headers.load
http2.conf
http2.load
mime.conf
mime.load
mpm_event.conf
mpm_event.load
negotiation.conf
negotiation.load
reqtimeout.conf
reqtimeout.load
rewrite.load
setenvif.conf
setenvif.load
socache_shmcb.load
ssl.conf
ssl.load
status.conf
status.load
</code>```

Is there any way to further improve the directives?

FYI: I still did not tackle the DOS and DDOS attack as well as still did not create a separate user (Other then root), as well as did not enabled the UFW.

Body:
I am setting up an Apache 2 server on Ubuntu.

Ubuntu Version: 20.04.5 LTS (GNU/Linux 5.4.0-135-generic x86_64)
Server version: Apache/2.4.41 (Ubuntu)

The web application "currently" does not accept upload nor runs any cgi script, nor does request or provide any authentication from any users, nor does have an sql database.

I would like to know if there is any additional directive to add to any of the following configuration files to improve further the security.

The files in their respective directories are:

# apache2.conf
# security.conf
# 000-default.conf
# example.com-ssl.conf

apache2.conf

# shm and runtimes  directory
DefaultRuntimeDir ${APACHE_RUN_DIR}

# PidFile
PidFile ${APACHE_PID_FILE}

# Timeout
Timeout 300

# KeepAlive
KeepAlive On

# MaxKeepAliveRequests
MaxKeepAliveRequests 100

# KeepAliveTimeout
KeepAliveTimeout 5

# Added by me for better caching performance
<FilesMatch "\.(html|css|gif|jpg|jpeg|js|png|svg|webp)$">
     Header set Cache-Control "max-age=31536000, public"
</FilesMatch>

# Added by me to hide last modified and just use the e-tag
Header unset Last-Modified

# These need to be set in /etc/apache2/envvars
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}

# HostnameLookups
HostnameLookups Off

# ErrorLog
ErrorLog ${APACHE_LOG_DIR}/error.log

# LogLevel
LogLevel warn

# Include module configuration:
IncludeOptional mods-enabled/*.load
IncludeOptional mods-enabled/*.conf

# Include list of ports to listen on
Include ports.conf

# Sets the default direct sec
<Directory />
    Options FollowSymLinks
    AllowOverride None
    Require all denied
</Directory>

<Directory /usr/share>
    AllowOverride None
    Require all granted
</Directory>

<Directory /var/www/>
    Options -Indexes -FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

#AccessFileName .htaccess

# The following lines prevent .htaccess and .htpasswd access
<FilesMatch "^\.ht">
    Require all denied
</FilesMatch>

# The format directories
LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent

# Include generic snippets of statements
IncludeOptional conf-enabled/*.conf

# Include the virtual host configurations:
IncludeOptional sites-enabled/*.conf

security.conf

# ServerTokens
ServerTokens Prod

# Server Signature
ServerSignature Off

# Allow TRACE
TraceEnable Off

# Header X content
Header set X-Content-Type-Options: "nosniff"

# Header X frame
Header set X-Frame-Options: "sameorigin"

000-default.conf

<VirtualHost *:80>
    # Server Name
    ServerName example.com

    # Server Alias
    ServerAlias www.example.com

    # Server Admin
    ServerAdmin admin@example.com

    # Document root directory
    DocumentRoot /var/www/html

    # Redirect all http traffic
    Redirect permanent / https://example.com

    # logs
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # No CGI allowed for the time being.
    #Include conf-available/serve-cgi-bin.conf
</VirtualHost>

example.com-ssl.conf

<VirtualHost *:443>
    # Https 2
    Protocols h2 http/1.1

    # Sever Name
    ServerName example.com

    # Server Alias
    ServerAlias www.example.com

    # Server Admin
    ServerAdmin admin@example.com

    # Document root directory
    DocumentRoot /var/www/html

    # SSL
    SSLEngine on
    SSLCertificateFile /etc/ssl/example.com.crt
    SSLCertificateKeyFile /etc/ssl/example.com.key
    SSLCertificateChainFile /etc/ssl/example.com.ca-bundle

    # Logs
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # No CGI allowed for the time being
    #Include conf-available/serve-cgi-bin.conf
</VirtualHost>

Here after is also the list of apache 2 module which are currently enabled:

access_compat.load
alias.conf
alias.load
auth_basic.load
authn_core.load
authn_file.load
authz_core.load
authz_host.load
authz_user.load
autoindex.conf
autoindex.load
deflate.conf
deflate.load
dir.conf
dir.load
env.load
filter.load
headers.load
http2.conf
http2.load
mime.conf
mime.load
mpm_event.conf
mpm_event.load
negotiation.conf
negotiation.load
reqtimeout.conf
reqtimeout.load
rewrite.load
setenvif.conf
setenvif.load
socache_shmcb.load
ssl.conf
ssl.load
status.conf
status.load

Is there any way to further improve the directives?

FYI: I still did not tackle the DOS and DDOS attack as well as still did not create a separate user (Other then root), as well as did not enabled the UFW.


问:
Unable to start Java debug remote application
I am trying to start Remote Java application but when I run it in debug mode, it exits silently without any error message for first time and when I debug it again it throws Cannot connect to VM Connection refused error.

How to start debug mode successfully ?

I have started tomcat on port 1045 and connection from eclipse gets established successfully on port 1045

Output of netstat is :

TCP 127.0.0.1:1045 127.0.0.1:53184 Established 14760
TCP 127.0.0.1:53184 127.0.0.1:1045 Established 6996

But eclipse does not start debug mode. What is missing ?


问:
Basic Hook vs Trampoline Hook
I've been learning about hooking functions of processes which has been fun and I have managed to hook a process by doing the following:

Create jump to my own code in the function I've hooked

Jump to my own code

Jump back to the instruction after my jump in the hooked function

However, I've come across the trampoline hook and I understand what it's doing but I don't quite understand the benefit of using it over the basic hook I have mentioned above. I don't suppose someone could let me know the benefits of using a trampoline hook over the basic hook or point me in the right direction?

Any help is greatly appreciated

Title: Basic Hook vs Trampoline Hook


问:
spark3 executor native memory management
i have a spark sql job execute on spark3 version. i config my job

```<code>    set spark.executor.memory=8G;
    set spark.executor.cores=3;
    set spark.yarn.executor.memoryOverhead=3072;
</code>```

and i didn't use the off-heap memory.
but encounter error:Container killed by YARN for exceeding physical memory limits. 12.1 GB of 11 GB physical memory used. Consider boosting spark.yarn.executor.memoryOverhead。
i open the executor rss report config. the memory report below:

enter image description here

what make me confuse is why rss memory is not sum of on-heap memory、off-memory、direct-pool memory、mapped-pool memory。
is there any else component that not include here and how to fix it?

Body:
i have a spark sql job execute on spark3 version. i config my job

    set spark.executor.memory=8G;
    set spark.executor.cores=3;
    set spark.yarn.executor.memoryOverhead=3072;

and i didn't use the off-heap memory.
but encounter error:Container killed by YARN for exceeding physical memory limits. 12.1 GB of 11 GB physical memory used. Consider boosting spark.yarn.executor.memoryOverhead。
i open the executor rss report config. the memory report below:

enter image description here

what make me confuse is why rss memory is not sum of on-heap memory、off-memory、direct-pool memory、mapped-pool memory。
is there any else component that not include here and how to fix it?


问:
XML Spreadsheet Numberformat query
XML spreadsheet 2003 has the following Numberformat. When i try to download the excel file(Button click) from markup language, am getting File corrupt error. If i remove the line file is opening well.

Also XML escape characters are not getting recognized by excel when they are used in formulas, however when these are used directly, they are correctly rendering in excel.

```<code><Style ss:ID="s121">
   <Alignment ss:Horizontal="Left" ss:Vertical="Center" ss:WrapText="1"/>
   <NumberFormat
    ss:Format="_-"$"* #,##0.00_-;\-"$"* #,##0.00_-;_-"$"* "-"??_-;_-@_-"/>
  </Style>
</code>```

I removed Numberformat markup then file opens correctly but in the cell formatting does not apply

Title: XML Spreadsheet Numberformat query

Body:
XML spreadsheet 2003 has the following Numberformat. When i try to download the excel file(Button click) from markup language, am getting File corrupt error. If i remove the line file is opening well.

Also XML escape characters are not getting recognized by excel when they are used in formulas, however when these are used directly, they are correctly rendering in excel.

I removed Numberformat markup then file opens correctly but in the cell formatting does not apply


问:
Why can't Rust infer this generic iterator?
I have written this code in rust. I want to have a trait with functions that return iterators, I don't want them to be necessarily vectors since it would be nice if they could be implemented as lazy iterators.

trait Molecule {
    fn atoms<I: Iterator<Item = Atom>>(&self) -> I;
}

fn print_names<M: Molecule>(molecule: M) {
    molecule.atoms().for_each(|atom| {
        println!("Atom: {}", atom.get_name().unwrap_or("Unknown"));
    });
}
```
<p>However this doesn't work. I get the following error:</p>
```error[E0282]: type annotations needed
  --> src/molecules/mod.rs:14:11
   |
14 |     molecule.atoms().for_each(|atom| {
   |              ^^^^^ cannot infer type of the type parameter `I` declared on the associated function `atoms`
   |
help: consider specifying the generic argument
   |
14 |     molecule.atoms::().for_each(|atom| {
   |                   +++++
```

Why doesn't this work? Any type that implements Iterator<Type = Atom> will have a function for_each that takes as input an Atom lambda, right?

I think I heard somewhere something about this being very hard/impossible to implement, but sadly I can't find it. I will probably change the generic iterator to a Vec but it would be nice to understand why the compiler can't infer this.

Body:
I have written this code in rust. I want to have a trait with functions that return iterators, I don't want them to be necessarily vectors since it would be nice if they could be implemented as lazy iterators.

trait Molecule {
    fn atoms<I: Iterator<Item = Atom>>(&self) -> I;
}

fn print_names<M: Molecule>(molecule: M) {
    molecule.atoms().for_each(|atom| {
        println!("Atom: {}", atom.get_name().unwrap_or("Unknown"));
    });
}

However this doesn't work. I get the following error:

error[E0282]: type annotations needed
  --> src/molecules/mod.rs:14:11
   |
14 |     molecule.atoms().for_each(|atom| {
   |              ^^^^^ cannot infer type of the type parameter `I` declared on the associated function `atoms`
   |
help: consider specifying the generic argument
   |
14 |     molecule.atoms::().for_each(|atom| {
   |                   +++++

Why doesn't this work? Any type that implements Iterator<Type = Atom> will have a function for_each that takes as input an Atom lambda, right?

I think I heard somewhere something about this being very hard/impossible to implement, but sadly I can't find it. I will probably change the generic iterator to a Vec but it would be nice to understand why the compiler can't infer this.


问:
SqlException: A connection was successfully established with the server, but then an error occurred during the login process
I upgraded my WebApi project from NET6 to NET7. I use EF Core 7 in my project.

I knew that there was a breaking change involving SQL Server and certificates. So I changed my connection string in the project's appsettings.json to:

```<code>"ConnectionStrings": {
  "DB": "data source=myserver;initial catalog=mydb;MultipleActiveResultSets=True;App=MyApp;Trusted_Connection=True;TrustServerCertificate=Yes;Encrypt=false;"
}
</code>```

I added Trusted_Connection, TrustServerCertificate and Encrypt to test if the connection will work.

The website was published to IIS (where the ASP.NET Core Runtime 7.0.0 is installed).

However I'm getting the following exception on a GET request:

SqlException: A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.)

And the following on another GET request:

{"type":"https://tools.ietf.org/html/rfc7231#section-6.6.1","title":"An error occurred while processing your request.","status":500,"traceId":"00-f7ac7c853fbfe3ef43a3d8b567fadbdb-a30b994f51839fcb-00"}

The above changes to the above connection string should have fixed this problem. But the problem persists and I don't know that else I can change to get the website to work again.

The SQL Server either has a self-signed certificate or no certificate at all. All I need is to get the code to work with the current setup.

What am I missing?

Body:
I upgraded my WebApi project from NET6 to NET7. I use EF Core 7 in my project.

I knew that there was a breaking change involving SQL Server and certificates. So I changed my connection string in the project's appsettings.json to:

"ConnectionStrings": {
  "DB": "data source=myserver;initial catalog=mydb;MultipleActiveResultSets=True;App=MyApp;Trusted_Connection=True;TrustServerCertificate=Yes;Encrypt=false;"
}

I added Trusted_Connection, TrustServerCertificate and Encrypt to test if the connection will work.

The website was published to IIS (where the ASP.NET Core Runtime 7.0.0 is installed).

However I'm getting the following exception on a GET request:

SqlException: A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.)

And the following on another GET request:

{"type":"https://tools.ietf.org/html/rfc7231#section-6.6.1","title":"An error occurred while processing your request.","status":500,"traceId":"00-f7ac7c853fbfe3ef43a3d8b567fadbdb-a30b994f51839fcb-00"}

The above changes to the above connection string should have fixed this problem. But the problem persists and I don't know that else I can change to get the website to work again.

The SQL Server either has a self-signed certificate or no certificate at all. All I need is to get the code to work with the current setup.

What am I missing?


问:
Why reading a string from cmd.exe is limited to 256 characters instead of expected 8192 chars
I'am developing a Chess engine in windows 10 in C with W64ming  that interfaces a standard GUI (eg Arena Chess) using stdin/stdout according to the UCI protocol.

My problem is that with my program (runned in cmd.exe) I cannot insert more than 256 characters (instead of the expected 8192 that should be allowed in Windows 10).

So when I try to write or paste the string

position startpos moves d2d4 g8f6 c2c4 e7e6 g1f3 b7b6 g2g3 c8a6 b2b3 f8b4 c1d2 b4e7 f1g2 c7c6 d2c3 d7d5 f3e5 f6d7 e5d7 b8d7 a2a4 d5c4 g2c6 a8c8 c6b5 a6b5 a4b5 d8c7 e1g1 d7f6 b3c4 c7c4 d1d2 f6e4 d2c1 e4c3 b1c3 c4d4 a1a7 e6e5 f1d1 d4c3 c1b1 e7c5 a7f7 e8f7 g3g4 c8f8 b1f5 f7g8 e2e4 f8f5 g4f5 c5d4 g1g2s c3c2 d1d4 e5d4 g2f3

is blocked/truncated as

position startpos moves d2d4 g8f6 c2c4 e7e6 g1f3 b7b6 g2g3 c8a6 b2b3 f8b4 c1d2 b4e7 f1g2 c7c6 d2c3 d7d5 f3e5 f6d7 e5d7 b8d7 a2a4 d5c4 g2c6 a8c8 c6b5 a6b5 a4b5 d8c7 e1g1 d7f6 b3c4 c7c4 d1d2 f6e4 d2c1 e4c3 b1c3 c4d4 a1a7 e6e5 f1d1 d4c3 c1b1 e7c5 a7f7 e8f7

Here's a  simple C program that isolate and shows the above problem reading data from stdin using fgets:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUFFERSIZE 8192

void UCILoop() {

    static char lineIn[BUFFERSIZE];
    setbuf(stdin, NULL);
    setbuf(stdout, NULL);

    while (1==1) {
        memset(&lineIn[0], 0, BUFFERSIZE);

        fflush(stdout);

        if (!fgets(lineIn, BUFFERSIZE, stdin))
            continue;

        if (lineIn[0] == '\n')
            continue;

        printf("%s\n", lineIn);
    }
}

int main() {
    UCILoop();
}
</code>```

The strange things (for me) is that running an another  pre compiled chess engine (eg Stockfish) in the same enviroment (cmd.exe) it doesn't show the problem.

How can I solve this? Any help is appreciated!! Tks!

Body:
I'am developing a Chess engine in windows 10 in C with W64ming  that interfaces a standard GUI (eg Arena Chess) using stdin/stdout according to the UCI protocol.

My problem is that with my program (runned in cmd.exe) I cannot insert more than 256 characters (instead of the expected 8192 that should be allowed in Windows 10).

So when I try to write or paste the string

position startpos moves d2d4 g8f6 c2c4 e7e6 g1f3 b7b6 g2g3 c8a6 b2b3 f8b4 c1d2 b4e7 f1g2 c7c6 d2c3 d7d5 f3e5 f6d7 e5d7 b8d7 a2a4 d5c4 g2c6 a8c8 c6b5 a6b5 a4b5 d8c7 e1g1 d7f6 b3c4 c7c4 d1d2 f6e4 d2c1 e4c3 b1c3 c4d4 a1a7 e6e5 f1d1 d4c3 c1b1 e7c5 a7f7 e8f7 g3g4 c8f8 b1f5 f7g8 e2e4 f8f5 g4f5 c5d4 g1g2s c3c2 d1d4 e5d4 g2f3

is blocked/truncated as

position startpos moves d2d4 g8f6 c2c4 e7e6 g1f3 b7b6 g2g3 c8a6 b2b3 f8b4 c1d2 b4e7 f1g2 c7c6 d2c3 d7d5 f3e5 f6d7 e5d7 b8d7 a2a4 d5c4 g2c6 a8c8 c6b5 a6b5 a4b5 d8c7 e1g1 d7f6 b3c4 c7c4 d1d2 f6e4 d2c1 e4c3 b1c3 c4d4 a1a7 e6e5 f1d1 d4c3 c1b1 e7c5 a7f7 e8f7

Here's a  simple C program that isolate and shows the above problem reading data from stdin using fgets:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUFFERSIZE 8192

void UCILoop() {

    static char lineIn[BUFFERSIZE];
    setbuf(stdin, NULL);
    setbuf(stdout, NULL);

    while (1==1) {
        memset(&lineIn[0], 0, BUFFERSIZE);

        fflush(stdout);

        if (!fgets(lineIn, BUFFERSIZE, stdin))
            continue;

        if (lineIn[0] == '\n')
            continue;

        printf("%s\n", lineIn);
    }
}

int main() {
    UCILoop();
}

The strange things (for me) is that running an another  pre compiled chess engine (eg Stockfish) in the same enviroment (cmd.exe) it doesn't show the problem.

How can I solve this? Any help is appreciated!! Tks!