问:
How do I get mobile status for discord bot by directly modifying IDENTIFY packet?
Apparently, discord bots can have mobile status as opposed to the desktop (online) status that one gets by default.

After a bit of digging I found out that such a status is achieved by modifying the IDENTIFY packet in discord.gateway.DiscordWebSocket.identify modifying the value of $browser to Discord Android or Discord iOS should theoretically get us the mobile status.

After modifying code snippets I found online which does this, I end up with this :

def get_mobile():
    """
    The Gateway's IDENTIFY packet contains a properties field, containing $os, $browser and $device fields.
    Discord uses that information to know when your phone client and only your phone client has connected to Discord,
    from there they send the extended presence object.
    The exact field that is checked is the $browser field. If it's set to Discord Android on desktop,
    the mobile indicator is is triggered by the desktop client. If it's set to Discord Client on mobile,
    the mobile indicator is not triggered by the mobile client.
    The specific values for the $os, $browser, and $device fields are can change from time to time.
    """
    import ast
    import inspect
    import re
    import discord

    def source(o):
        s = inspect.getsource(o).split("\n")
        indent = len(s[0]) - len(s[0].lstrip())

        return "\n".join(i[indent:] for i in s)

    source_ = source(discord.gateway.DiscordWebSocket.identify)
    patched = re.sub(
        r'([\'"]\$browser[\'"]:\s?[\'"]).+([\'"])',
        r"\1Discord Android\2",
        source_,
    )

    loc = {}
    exec(compile(ast.parse(patched), "<string>", "exec"), discord.gateway.__dict__, loc)
    return loc["identify"]
```
<p>Now all there is left to do is overwrite the <code>discord.gateway.DiscordWebSocket.identify</code> during runtime in the main file, something like this :</p>
<pre class="lang-py prettyprint-override"><code>import discord
import os
from discord.ext import commands
import mobile_status

discord.gateway.DiscordWebSocket.identify = mobile_status.get_mobile()
bot = commands.Bot(command_prefix="?")

@bot.event
async def on_ready():
    print(f"Sucessfully logged in as {bot.user}")

bot.run(os.getenv("DISCORD_TOKEN"))
</code>```

And we do get the mobile status successfully

But here's the problem, I wanted to directly modify the file (which held the function) rather than monkey-patching it during runtime. So I cloned the dpy lib locally and edited the file on my machine, it ended up looking like this :

    async def identify(self):
        """Sends the IDENTIFY packet."""
        payload = {
            'op': self.IDENTIFY,
            'd': {
                'token': self.token,
                'properties': {
                    '$os': sys.platform,
                    '$browser': 'Discord Android',
                    '$device': 'Discord Android',
                    '$referrer': '',
                    '$referring_domain': ''
                },
                'compress': True,
                'large_threshold': 250,
                'v': 3
            }
        }
     # ...
```
<p>(edited both <code>$browser</code> and <code>$device</code> to <code>Discord Android</code> just to be safe)</p>
<p>But this does not work and just gives me the regular desktop online icon.<br />
So the next thing I did is to inspect the <code>identify</code> function <em>after</em> it has been monkey-patched, so I could just look at the source code and see what went wrong earlier, but due to hard luck I got this error :</p>
```Traceback (most recent call last):
  File "c:\Users\Achxy\Desktop\fresh\file.py", line 8, in <module>
    print(inspect.getsource(discord.gateway.DiscordWebSocket.identify))
  File "C:\Users\Achxy\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 1024, in getsource
    lines, lnum = getsourcelines(object)
  File "C:\Users\Achxy\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 1006, in getsourcelines
    lines, lnum = findsource(object)
  File "C:\Users\Achxy\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 835, in findsource
    raise OSError('could not get source code')
OSError: could not get source code
```
<p>Code :</p>
<pre class="lang-py prettyprint-override"><code>import discord
import os
from discord.ext import commands
import mobile_status
import inspect

discord.gateway.DiscordWebSocket.identify = mobile_status.get_mobile()
print(inspect.getsource(discord.gateway.DiscordWebSocket.identify))
bot = commands.Bot(command_prefix="?")

@bot.event
async def on_ready():
    print(f"Sucessfully logged in as {bot.user}")

bot.run(os.getenv("DISCORD_TOKEN"))
</code>```

Since this same behavior was exhibited for every patched function (aforementioned one and the loc["identify"]) I could no longer use inspect.getsource(...) and then relied upon dis.dis which lead to much more disappointing results

The disassembled data looks exactly identical to the monkey-patched working version, so the directly modified version simply does not work despite function content being the exact same. (In regards to disassembled data)

Notes: Doing Discord iOS directly does not work either, changing the $device to some other value but keeping $browser does not work, I have tried all combinations, none of them work.

TL;DR: How to get mobile status for discord bot without monkey-patching it during runtime?

答:
The following works by subclassing the relevant class, and duplicating code with the relevant changes. We also have to subclass the Client class, to overwrite the place where the gateway/websocket class is used. This results in a lot of duplicated code, however it does work, and requires neither dirty monkey-patching nor editing the library source code.

However, it does come with many of the same problems as editing the library source code - mainly that as the library is updated, this code will become out of date (if you're using the archived and obsolete version of the library, you have bigger problems instead).

import asyncio
import sys

import aiohttp

import discord
from discord.gateway import DiscordWebSocket, _log
from discord.ext.commands import Bot

class MyGateway(DiscordWebSocket):

    async def identify(self):
        payload = {
            'op': self.IDENTIFY,
            'd': {
                'token': self.token,
                'properties': {
                    '$os': sys.platform,
                    '$browser': 'Discord Android',
                    '$device': 'Discord Android',
                    '$referrer': '',
                    '$referring_domain': ''
                },
                'compress': True,
                'large_threshold': 250,
                'v': 3
            }
        }

        if self.shard_id is not None and self.shard_count is not None:
            payload['d']['shard'] = [self.shard_id, self.shard_count]

        state = self._connection
        if state._activity is not None or state._status is not None:
            payload['d']['presence'] = {
                'status': state._status,
                'game': state._activity,
                'since': 0,
                'afk': False
            }

        if state._intents is not None:
            payload['d']['intents'] = state._intents.value

        await self.call_hooks('before_identify', self.shard_id, initial=self._initial_identify)
        await self.send_as_json(payload)
        _log.info('Shard ID %s has sent the IDENTIFY payload.', self.shard_id)

class MyBot(Bot):

    async def connect(self, *, reconnect: bool = True) -> None:
        """|coro|

        Creates a websocket connection and lets the websocket listen
        to messages from Discord. This is a loop that runs the entire
        event system and miscellaneous aspects of the library. Control
        is not resumed until the WebSocket connection is terminated.

        Parameters
        -----------
        reconnect: :class:`bool`
            If we should attempt reconnecting, either due to internet
            failure or a specific failure on Discord's part. Certain
            disconnects that lead to bad state will not be handled (such as
            invalid sharding payloads or bad tokens).

        Raises
        -------
        :exc:`.GatewayNotFound`
            If the gateway to connect to Discord is not found. Usually if this
            is thrown then there is a Discord API outage.
        :exc:`.ConnectionClosed`
            The websocket connection has been terminated.
        """

        backoff = discord.client.ExponentialBackoff()
        ws_params = {
            'initial': True,
            'shard_id': self.shard_id,
        }
        while not self.is_closed():
            try:
                coro = MyGateway.from_client(self, **ws_params)
                self.ws = await asyncio.wait_for(coro, timeout=60.0)
                ws_params['initial'] = False
                while True:
                    await self.ws.poll_event()
            except discord.client.ReconnectWebSocket as e:
                _log.info('Got a request to %s the websocket.', e.op)
                self.dispatch('disconnect')
                ws_params.update(sequence=self.ws.sequence, resume=e.resume, session=self.ws.session_id)
                continue
            except (OSError,
                    discord.HTTPException,
                    discord.GatewayNotFound,
                    discord.ConnectionClosed,
                    aiohttp.ClientError,
                    asyncio.TimeoutError) as exc:

                self.dispatch('disconnect')
                if not reconnect:
                    await self.close()
                    if isinstance(exc, discord.ConnectionClosed) and exc.code == 1000:
                        # clean close, don't re-raise this
                        return
                    raise

                if self.is_closed():
                    return

                # If we get connection reset by peer then try to RESUME
                if isinstance(exc, OSError) and exc.errno in (54, 10054):
                    ws_params.update(sequence=self.ws.sequence, initial=False, resume=True, session=self.ws.session_id)
                    continue

                # We should only get this when an unhandled close code happens,
                # such as a clean disconnect (1000) or a bad state (bad token, no sharding, etc)
                # sometimes, discord sends us 1000 for unknown reasons so we should reconnect
                # regardless and rely on is_closed instead
                if isinstance(exc, discord.ConnectionClosed):
                    if exc.code == 4014:
                        raise discord.PrivilegedIntentsRequired(exc.shard_id) from None
                    if exc.code != 1000:
                        await self.close()
                        raise

                retry = backoff.delay()
                _log.exception("Attempting a reconnect in %.2fs", retry)
                await asyncio.sleep(retry)
                # Always try to RESUME the connection
                # If the connection is not RESUME-able then the gateway will invalidate the session.
                # This is apparently what the official Discord client does.
                ws_params.update(sequence=self.ws.sequence, resume=True, session=self.ws.session_id)

bot = MyBot(command_prefix="?")

@bot.event
async def on_ready():
    print(f"Sucessfully logged in as {bot.user}")

bot.run("YOUR_BOT_TOKEN")
```
<p>Personally, I think that the following approach, which does include some runtime monkey-patching (but no AST manipulation) is cleaner for this purpose:</p>
<pre class="lang-py prettyprint-override"><code>import sys
from discord.gateway import DiscordWebSocket, _log
from discord.ext.commands import Bot

async def identify(self):
    payload = {
        'op': self.IDENTIFY,
        'd': {
            'token': self.token,
            'properties': {
                '$os': sys.platform,
                '$browser': 'Discord Android',
                '$device': 'Discord Android',
                '$referrer': '',
                '$referring_domain': ''
            },
            'compress': True,
            'large_threshold': 250,
            'v': 3
        }
    }

    if self.shard_id is not None and self.shard_count is not None:
        payload['d']['shard'] = [self.shard_id, self.shard_count]

    state = self._connection
    if state._activity is not None or state._status is not None:
        payload['d']['presence'] = {
            'status': state._status,
            'game': state._activity,
            'since': 0,
            'afk': False
        }

    if state._intents is not None:
        payload['d']['intents'] = state._intents.value

    await self.call_hooks('before_identify', self.shard_id, initial=self._initial_identify)
    await self.send_as_json(payload)
    _log.info('Shard ID %s has sent the IDENTIFY payload.', self.shard_id)

DiscordWebSocket.identify = identify
bot = Bot(command_prefix="?")

@bot.event
async def on_ready():
    print(f"Sucessfully logged in as {bot.user}")

bot.run("YOUR_DISCORD_TOKEN")
</code>```

As to why editing the library source code did not work for you, I can only assume that you have edited the wrong copy of the file, as people have commented.

Body:
Apparently, discord bots can have mobile status as opposed to the desktop (online) status that one gets by default.

After a bit of digging I found out that such a status is achieved by modifying the IDENTIFY packet in discord.gateway.DiscordWebSocket.identify modifying the value of $browser to Discord Android or Discord iOS should theoretically get us the mobile status.

After modifying code snippets I found online which does this, I end up with this :

def get_mobile():
    """
    The Gateway's IDENTIFY packet contains a properties field, containing $os, $browser and $device fields.
    Discord uses that information to know when your phone client and only your phone client has connected to Discord,
    from there they send the extended presence object.
    The exact field that is checked is the $browser field. If it's set to Discord Android on desktop,
    the mobile indicator is is triggered by the desktop client. If it's set to Discord Client on mobile,
    the mobile indicator is not triggered by the mobile client.
    The specific values for the $os, $browser, and $device fields are can change from time to time.
    """
    import ast
    import inspect
    import re
    import discord

    def source(o):
        s = inspect.getsource(o).split("\n")
        indent = len(s[0]) - len(s[0].lstrip())

        return "\n".join(i[indent:] for i in s)

    source_ = source(discord.gateway.DiscordWebSocket.identify)
    patched = re.sub(
        r'([\'"]\$browser[\'"]:\s?[\'"]).+([\'"])',
        r"\1Discord Android\2",
        source_,
    )

    loc = {}
    exec(compile(ast.parse(patched), "<string>", "exec"), discord.gateway.__dict__, loc)
    return loc["identify"]

Now all there is left to do is overwrite the discord.gateway.DiscordWebSocket.identify during runtime in the main file, something like this :

import discord
import os
from discord.ext import commands
import mobile_status

discord.gateway.DiscordWebSocket.identify = mobile_status.get_mobile()
bot = commands.Bot(command_prefix="?")

@bot.event
async def on_ready():
    print(f"Sucessfully logged in as {bot.user}")

bot.run(os.getenv("DISCORD_TOKEN"))

And we do get the mobile status successfully

But here's the problem, I wanted to directly modify the file (which held the function) rather than monkey-patching it during runtime. So I cloned the dpy lib locally and edited the file on my machine, it ended up looking like this :

    async def identify(self):
        """Sends the IDENTIFY packet."""
        payload = {
            'op': self.IDENTIFY,
            'd': {
                'token': self.token,
                'properties': {
                    '$os': sys.platform,
                    '$browser': 'Discord Android',
                    '$device': 'Discord Android',
                    '$referrer': '',
                    '$referring_domain': ''
                },
                'compress': True,
                'large_threshold': 250,
                'v': 3
            }
        }
     # ...

(edited both $browser and $device to Discord Android just to be safe)

But this does not work and just gives me the regular desktop online icon.

So the next thing I did is to inspect the identify function after it has been monkey-patched, so I could just look at the source code and see what went wrong earlier, but due to hard luck I got this error :

Traceback (most recent call last):
  File "c:\Users\Achxy\Desktop\fresh\file.py", line 8, in <module>
    print(inspect.getsource(discord.gateway.DiscordWebSocket.identify))
  File "C:\Users\Achxy\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 1024, in getsource
    lines, lnum = getsourcelines(object)
  File "C:\Users\Achxy\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 1006, in getsourcelines
    lines, lnum = findsource(object)
  File "C:\Users\Achxy\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 835, in findsource
    raise OSError('could not get source code')
OSError: could not get source code

Code :

import discord
import os
from discord.ext import commands
import mobile_status
import inspect

discord.gateway.DiscordWebSocket.identify = mobile_status.get_mobile()
print(inspect.getsource(discord.gateway.DiscordWebSocket.identify))
bot = commands.Bot(command_prefix="?")

@bot.event
async def on_ready():
    print(f"Sucessfully logged in as {bot.user}")

bot.run(os.getenv("DISCORD_TOKEN"))

Since this same behavior was exhibited for every patched function (aforementioned one and the loc["identify"]) I could no longer use inspect.getsource(...) and then relied upon dis.dis which lead to much more disappointing results

The disassembled data looks exactly identical to the monkey-patched working version, so the directly modified version simply does not work despite function content being the exact same. (In regards to disassembled data)

Notes: Doing Discord iOS directly does not work either, changing the $device to some other value but keeping $browser does not work, I have tried all combinations, none of them work.

TL;DR: How to get mobile status for discord bot without monkey-patching it during runtime?

Body:
The following works by subclassing the relevant class, and duplicating code with the relevant changes. We also have to subclass the Client class, to overwrite the place where the gateway/websocket class is used. This results in a lot of duplicated code, however it does work, and requires neither dirty monkey-patching nor editing the library source code.

However, it does come with many of the same problems as editing the library source code - mainly that as the library is updated, this code will become out of date (if you're using the archived and obsolete version of the library, you have bigger problems instead).

import asyncio
import sys

import aiohttp

import discord
from discord.gateway import DiscordWebSocket, _log
from discord.ext.commands import Bot

class MyGateway(DiscordWebSocket):

    async def identify(self):
        payload = {
            'op': self.IDENTIFY,
            'd': {
                'token': self.token,
                'properties': {
                    '$os': sys.platform,
                    '$browser': 'Discord Android',
                    '$device': 'Discord Android',
                    '$referrer': '',
                    '$referring_domain': ''
                },
                'compress': True,
                'large_threshold': 250,
                'v': 3
            }
        }

        if self.shard_id is not None and self.shard_count is not None:
            payload['d']['shard'] = [self.shard_id, self.shard_count]

        state = self._connection
        if state._activity is not None or state._status is not None:
            payload['d']['presence'] = {
                'status': state._status,
                'game': state._activity,
                'since': 0,
                'afk': False
            }

        if state._intents is not None:
            payload['d']['intents'] = state._intents.value

        await self.call_hooks('before_identify', self.shard_id, initial=self._initial_identify)
        await self.send_as_json(payload)
        _log.info('Shard ID %s has sent the IDENTIFY payload.', self.shard_id)

class MyBot(Bot):

    async def connect(self, *, reconnect: bool = True) -> None:
        """|coro|

        Creates a websocket connection and lets the websocket listen
        to messages from Discord. This is a loop that runs the entire
        event system and miscellaneous aspects of the library. Control
        is not resumed until the WebSocket connection is terminated.

        Parameters
        -----------
        reconnect: :class:`bool`
            If we should attempt reconnecting, either due to internet
            failure or a specific failure on Discord's part. Certain
            disconnects that lead to bad state will not be handled (such as
            invalid sharding payloads or bad tokens).

        Raises
        -------
        :exc:`.GatewayNotFound`
            If the gateway to connect to Discord is not found. Usually if this
            is thrown then there is a Discord API outage.
        :exc:`.ConnectionClosed`
            The websocket connection has been terminated.
        """

        backoff = discord.client.ExponentialBackoff()
        ws_params = {
            'initial': True,
            'shard_id': self.shard_id,
        }
        while not self.is_closed():
            try:
                coro = MyGateway.from_client(self, **ws_params)
                self.ws = await asyncio.wait_for(coro, timeout=60.0)
                ws_params['initial'] = False
                while True:
                    await self.ws.poll_event()
            except discord.client.ReconnectWebSocket as e:
                _log.info('Got a request to %s the websocket.', e.op)
                self.dispatch('disconnect')
                ws_params.update(sequence=self.ws.sequence, resume=e.resume, session=self.ws.session_id)
                continue
            except (OSError,
                    discord.HTTPException,
                    discord.GatewayNotFound,
                    discord.ConnectionClosed,
                    aiohttp.ClientError,
                    asyncio.TimeoutError) as exc:

                self.dispatch('disconnect')
                if not reconnect:
                    await self.close()
                    if isinstance(exc, discord.ConnectionClosed) and exc.code == 1000:
                        # clean close, don't re-raise this
                        return
                    raise

                if self.is_closed():
                    return

                # If we get connection reset by peer then try to RESUME
                if isinstance(exc, OSError) and exc.errno in (54, 10054):
                    ws_params.update(sequence=self.ws.sequence, initial=False, resume=True, session=self.ws.session_id)
                    continue

                # We should only get this when an unhandled close code happens,
                # such as a clean disconnect (1000) or a bad state (bad token, no sharding, etc)
                # sometimes, discord sends us 1000 for unknown reasons so we should reconnect
                # regardless and rely on is_closed instead
                if isinstance(exc, discord.ConnectionClosed):
                    if exc.code == 4014:
                        raise discord.PrivilegedIntentsRequired(exc.shard_id) from None
                    if exc.code != 1000:
                        await self.close()
                        raise

                retry = backoff.delay()
                _log.exception("Attempting a reconnect in %.2fs", retry)
                await asyncio.sleep(retry)
                # Always try to RESUME the connection
                # If the connection is not RESUME-able then the gateway will invalidate the session.
                # This is apparently what the official Discord client does.
                ws_params.update(sequence=self.ws.sequence, resume=True, session=self.ws.session_id)

bot = MyBot(command_prefix="?")

@bot.event
async def on_ready():
    print(f"Sucessfully logged in as {bot.user}")

bot.run("YOUR_BOT_TOKEN")

Personally, I think that the following approach, which does include some runtime monkey-patching (but no AST manipulation) is cleaner for this purpose:

import sys
from discord.gateway import DiscordWebSocket, _log
from discord.ext.commands import Bot

async def identify(self):
    payload = {
        'op': self.IDENTIFY,
        'd': {
            'token': self.token,
            'properties': {
                '$os': sys.platform,
                '$browser': 'Discord Android',
                '$device': 'Discord Android',
                '$referrer': '',
                '$referring_domain': ''
            },
            'compress': True,
            'large_threshold': 250,
            'v': 3
        }
    }

    if self.shard_id is not None and self.shard_count is not None:
        payload['d']['shard'] = [self.shard_id, self.shard_count]

    state = self._connection
    if state._activity is not None or state._status is not None:
        payload['d']['presence'] = {
            'status': state._status,
            'game': state._activity,
            'since': 0,
            'afk': False
        }

    if state._intents is not None:
        payload['d']['intents'] = state._intents.value

    await self.call_hooks('before_identify', self.shard_id, initial=self._initial_identify)
    await self.send_as_json(payload)
    _log.info('Shard ID %s has sent the IDENTIFY payload.', self.shard_id)

DiscordWebSocket.identify = identify
bot = Bot(command_prefix="?")

@bot.event
async def on_ready():
    print(f"Sucessfully logged in as {bot.user}")

bot.run("YOUR_DISCORD_TOKEN")

As to why editing the library source code did not work for you, I can only assume that you have edited the wrong copy of the file, as people have commented.


来源: stackexchange

问:
Cannot write to images directory | cloud hosting with Laravel forge
I have a problem when deploying Laravel an application using Laravel forge. I try to generate fake images using faker package in Laravel but,

```<code>    Cannot write to directory "/home/forge/my.domain/public/storage/images/products/cover_img"

  at vendor/fakerphp/faker/src/Faker/Provider/Image.php:98
     94▕     ) {
     95▕         $dir = null === $dir ? sys_get_temp_dir() : $dir; // GNU/Linux / OS X / Windows compatible
     96▕         // Validate directory path
     97▕         if (!is_dir($dir) || !is_writable($dir)) {
  ➜ 98▕             throw new \InvalidArgumentException(sprintf('Cannot write to directory "%s"', $dir));
     99▕         }
    100▕
    101▕         // Generate a random filename. Use the server address so that a file
    102▕         // generated at the same time on a different server won't have a collision.
</code>```

in the factory file,

```<code>'cover_img' => $this->faker->image(public_path('storage/images/products/cover_img'), 640, 480, null, false),
</code>```

This is my first time using cloud hosting. when using shared hosting I can give permission to create a folder or can create a folder manually. please help me to solve this problem.  Thank You!

***UPDATE ***

I change a few codes and again tried.

```<code>if(!File::exists(public_path().'/storage/images/products/cover_img'))
{   File::makeDirectory(public_path().'/storage/images/products/cover_img', 0777,true);
    }
</code>```

Now it has error when deploy using Laravel forge,

```<code>ErrorException

mkdir(): Permission denied
</code>```

If someone can help me to solve this I really appreciate it.

答:
Finally, I've figured out the issue, I think First I did the total wrong way because I tried to seed when deploying using forge with php artisan migrate:fresh --seed code. Then came that error. below has the wrong code.

```<code>cd /home/forge/dev.mydomain.com
git pull origin $FORGE_SITE_BRANCH
$FORGE_COMPOSER install --no-interaction --prefer-dist --optimize-autoloader

( flock -w 10 9 || exit 1
    echo 'Restarting FPM...'; sudo -S service $FORGE_PHP_FPM reload ) 9>/tmp/fpmlock

if [ -f artisan ]; then
    $FORGE_PHP artisan migrate --seed
fi
</code>```

So, finally, I did just deploy with default settings in the forge and I log in to serve using terminal, Then I run the php artisan migrate --seed command and I was successful without any error. This was the step I followed,

Generate SSH key using git bash

ssh-keygen

Added ssh key into the forge

run this command in git bash terminal

ssh forge@ip address in the server

then installed the oh my zsh using this code,

sh -c "$(curl -fsSL
https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"

then went to my directory in the host using terminal,

cd dev.maydomain.com

and final run seed,

php artisan migrate --seed

ContentLicense: CC BY-SA 4.0

Body:
I have a problem when deploying Laravel an application using Laravel forge. I try to generate fake images using faker package in Laravel but,

    Cannot write to directory "/home/forge/my.domain/public/storage/images/products/cover_img"

  at vendor/fakerphp/faker/src/Faker/Provider/Image.php:98
     94▕     ) {
     95▕         $dir = null === $dir ? sys_get_temp_dir() : $dir; // GNU/Linux / OS X / Windows compatible
     96▕         // Validate directory path
     97▕         if (!is_dir($dir) || !is_writable($dir)) {
  ➜ 98▕             throw new \InvalidArgumentException(sprintf('Cannot write to directory "%s"', $dir));
     99▕         }
    100▕
    101▕         // Generate a random filename. Use the server address so that a file
    102▕         // generated at the same time on a different server won't have a collision.

in the factory file,

'cover_img' => $this->faker->image(public_path('storage/images/products/cover_img'), 640, 480, null, false),

This is my first time using cloud hosting. when using shared hosting I can give permission to create a folder or can create a folder manually. please help me to solve this problem.  Thank You!

***UPDATE ***

I change a few codes and again tried.

if(!File::exists(public_path().'/storage/images/products/cover_img'))
{   File::makeDirectory(public_path().'/storage/images/products/cover_img', 0777,true);
    }

Now it has error when deploy using Laravel forge,

ErrorException

mkdir(): Permission denied

If someone can help me to solve this I really appreciate it.

Body:
Finally, I've figured out the issue, I think First I did the total wrong way because I tried to seed when deploying using forge with php artisan migrate:fresh --seed code. Then came that error. below has the wrong code.

cd /home/forge/dev.mydomain.com
git pull origin $FORGE_SITE_BRANCH
$FORGE_COMPOSER install --no-interaction --prefer-dist --optimize-autoloader

( flock -w 10 9 || exit 1
    echo 'Restarting FPM...'; sudo -S service $FORGE_PHP_FPM reload ) 9>/tmp/fpmlock

if [ -f artisan ]; then
    $FORGE_PHP artisan migrate --seed
fi

So, finally, I did just deploy with default settings in the forge and I log in to serve using terminal, Then I run the php artisan migrate --seed command and I was successful without any error. This was the step I followed,

Generate SSH key using git bash

ssh-keygen

Added ssh key into the forge

run this command in git bash terminal

ssh forge@ip address in the server

then installed the oh my zsh using this code,

sh -c "$(curl -fsSL
https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"

then went to my directory in the host using terminal,

cd dev.maydomain.com

and final run seed,

php artisan migrate --seed


问:
merge st_voronoi polygons by variable
I'd like to create polygons with st_voronoi and merge them by a variable

```<code>library(sf)
nc_centroids <- st_transform(nc_centroids,crs=32119)
nc_centroids$foo <- c(rep("green",50),rep("red",50))
nc <- st_transform(nc,crs=32119)
v <- st_voronoi(st_union(nc_centroids))
plot(v, col = 0)
plot(st_intersection(st_cast(v), st_union(nc)), col = 0)
plot(nc_centroids, add = TRUE)
</code>```

How might I merge the polygons in v by nc_centroids$foo to create two big polygons? I can think of some hacks, like using lapply to join the individual polygons of v, e.g., (v[[1]][[x]]). But surely there's something easier

答:
Please find below a reprex that details one possible approach.

Reprex

Code

library(sf)
library(dplyr)

nc <- st_read(system.file("shape/nc.shp", package="sf"))
nc_centroids <- st_centroid(nc)
nc_centroids <- st_transform(nc_centroids,crs=32119)
nc_centroids$foo <- c(rep("green",50),rep("red",50))
nc <- st_transform(nc,crs=32119)
v <- st_voronoi(st_union(nc_centroids))

v <- v %>%
  st_collection_extract(., "POLYGON") %>%
  st_as_sf()

v_result <- v %>%
  st_join(., nc_centroids, st_intersects) %>%
  group_by(foo) %>%
  summarize()

nc_result <- nc %>%
  st_join(., v_result) %>%
  group_by(foo) %>%
  summarize()
```
<ul>
<li>Output</li>
</ul>
<pre class="lang-r prettyprint-override"><code>plot(nc_result)
</code>```

Created on 2022-02-07 by the reprex package (v2.0.1)

Title: merge st_voronoi polygons by variable

Body:
I'd like to create polygons with st_voronoi and merge them by a variable

library(sf)
nc_centroids <- st_transform(nc_centroids,crs=32119)
nc_centroids$foo <- c(rep("green",50),rep("red",50))
nc <- st_transform(nc,crs=32119)
v <- st_voronoi(st_union(nc_centroids))
plot(v, col = 0)
plot(st_intersection(st_cast(v), st_union(nc)), col = 0)
plot(nc_centroids, add = TRUE)

How might I merge the polygons in v by nc_centroids$foo to create two big polygons? I can think of some hacks, like using lapply to join the individual polygons of v, e.g., (v[[1]][[x]]). But surely there's something easier

Body:
Please find below a reprex that details one possible approach.

Reprex

Code

library(sf)
library(dplyr)

nc <- st_read(system.file("shape/nc.shp", package="sf"))
nc_centroids <- st_centroid(nc)
nc_centroids <- st_transform(nc_centroids,crs=32119)
nc_centroids$foo <- c(rep("green",50),rep("red",50))
nc <- st_transform(nc,crs=32119)
v <- st_voronoi(st_union(nc_centroids))

v <- v %>%
  st_collection_extract(., "POLYGON") %>%
  st_as_sf()

v_result <- v %>%
  st_join(., nc_centroids, st_intersects) %>%
  group_by(foo) %>%
  summarize()

nc_result <- nc %>%
  st_join(., v_result) %>%
  group_by(foo) %>%
  summarize()

Output

plot(nc_result)

Created on 2022-02-07 by the reprex package (v2.0.1)


问:
ASP.NET Button click redirect to new page
I have created a Button programmatically.
I now want to redirect to a new aspx page on the click of this Button, such that we will enter into one of the methods of the new page (like page_load(), etc.)

Is this possible?

Eg:

```<code>Button oButton = new Button;
oButton.Text = "NextPage";
// Redirect to "Redirect.aspx" on click
</code>```

But I am not able to find an entry point in Redirect.aspx where I can do some changes to the UI components once we get redirected to "Redirect.aspx"

Regards,

Parag

答:
You can use query string parameters and depending on the value of param call the appropriate method in Page_Load of Redirect.aspx
e.g.

```<code>Redirect.aspx?val=1
</code>```

in Redirect.aspx

```<code>protected void Page_Load(...){
string var = Request.QueryString["val"];
if(var == "1")
some_method();
else
some_other_method();
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have created a Button programmatically.
I now want to redirect to a new aspx page on the click of this Button, such that we will enter into one of the methods of the new page (like page_load(), etc.)

Is this possible?

Eg:

Button oButton = new Button;
oButton.Text = "NextPage";
// Redirect to "Redirect.aspx" on click

But I am not able to find an entry point in Redirect.aspx where I can do some changes to the UI components once we get redirected to "Redirect.aspx"

Regards,

Parag

Body:
You can use query string parameters and depending on the value of param call the appropriate method in Page_Load of Redirect.aspx
e.g.

Redirect.aspx?val=1

in Redirect.aspx

protected void Page_Load(...){
string var = Request.QueryString["val"];
if(var == "1")
some_method();
else
some_other_method();
}


问:
webscraper got #AttributeError: 'NoneType' object has no attribute 'replace'
I'm trying to download all those hot custom bikes' images from this website.
bikeexif.com

I'm trying to make folders by every article's name.
But problem is, some of those article name has special character ':' which makes me wonder it caused problem or not.
So I tried replace it first as this '-' to see more clearly.

problem example # RED ZED: AC SANCTUARY’S 152 HP Z1000 RACER

After I run my code, I got

line 20, in
new_name = album_name.replace(':', '-')
AttributeError: 'NoneType' object has no attribute 'replace'

I still don't understand what to do. (I'm a newbie)

Anyone can help?

Thanks

```<code># -*- coding: utf-8 -*-
import requests
import parsel
import os
import time

for page in range(1, 309):
    print(f'======= Scraping data from page {page} =======')

    url = f'https://www.bikeexif.com/page/{page}'
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'}
    response = requests.get(url, headers=headers)
    response.encoding = 'utf-8'
    html_data = response.text
    selector = parsel.Selector(html_data)

    image_album_list = selector.xpath('//*[@id="main"]/div/div')
    for li in image_album_list:
        album_name = li.xpath('.//div/div/@h2').get()
        new_name = album_name.replace(':', '-')
        album_url = li.xpath('.//div/div/a/@href').get()
        print(album_name, album_url)

        if not os.path.exists('img\\' + new_name):
            os.mkdir('img\\' + new_name)

        response_image = requests.get(url=album_url, headers=headers).text
        selector_image = parsel.Selector(response_image)

        images_url_a = selector_image.xpath('//div[@class="image-container"]/img/@data-src').getall()
        # images_url_b = selector_image.xpath('//div[@class="image-container"]/img/@src').getall()
        for album_url in images_url_a:
            image_data = requests.get(url=album_url, headers=headers).content
            time.sleep(1)

            file_name = album_url.split('/')[-1]
            with open(f'img\\{new_name}\\' + file_name, mode='wb') as f:
                f.write(image_data)
                print(file_name)
</code>```

答:
To elaborate a bit on @mkrieger1's comment, what you should do depends on what you want to happen, and whether album_name=None is allowed for your data. Some examples:
If no-album-name is allowed, and you just want to print the results, you can simply replace that one album_name.replace() call with something like

```<code>if album_name is not None:
    new_name = album_name.replace(':', '-')
</code>```

If you're doing other processing you haven't talked about here, and having album_name is None gives a specific alternate path you should take to process otherwise "normal" data, you can follow the if album_name is not None: block above with an else: that assumes album_name is None.

If you just want to skip getting the album_url (and anything else you normally do) in response to album_name is None, put all the stuff you want to skip inside the above if album_name is not None: conditional and the code will silently ignore  those records.

If album_name is None is definitely an error / unexpected condition, read up on try/except blocks and figure out what sorts of error handling you want to do.

Body:
I'm trying to download all those hot custom bikes' images from this website.
bikeexif.com

I'm trying to make folders by every article's name.
But problem is, some of those article name has special character ':' which makes me wonder it caused problem or not.
So I tried replace it first as this '-' to see more clearly.

problem example # RED ZED: AC SANCTUARY’S 152 HP Z1000 RACER

After I run my code, I got

line 20, in
new_name = album_name.replace(':', '-')
AttributeError: 'NoneType' object has no attribute 'replace'

I still don't understand what to do. (I'm a newbie)

Anyone can help?

Thanks

# -*- coding: utf-8 -*-
import requests
import parsel
import os
import time

for page in range(1, 309):
    print(f'======= Scraping data from page {page} =======')

    url = f'https://www.bikeexif.com/page/{page}'
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'}
    response = requests.get(url, headers=headers)
    response.encoding = 'utf-8'
    html_data = response.text
    selector = parsel.Selector(html_data)

    image_album_list = selector.xpath('//*[@id="main"]/div/div')
    for li in image_album_list:
        album_name = li.xpath('.//div/div/@h2').get()
        new_name = album_name.replace(':', '-')
        album_url = li.xpath('.//div/div/a/@href').get()
        print(album_name, album_url)

        if not os.path.exists('img\\' + new_name):
            os.mkdir('img\\' + new_name)

        response_image = requests.get(url=album_url, headers=headers).text
        selector_image = parsel.Selector(response_image)

        images_url_a = selector_image.xpath('//div[@class="image-container"]/img/@data-src').getall()
        # images_url_b = selector_image.xpath('//div[@class="image-container"]/img/@src').getall()
        for album_url in images_url_a:
            image_data = requests.get(url=album_url, headers=headers).content
            time.sleep(1)

            file_name = album_url.split('/')[-1]
            with open(f'img\\{new_name}\\' + file_name, mode='wb') as f:
                f.write(image_data)
                print(file_name)

Body:
To elaborate a bit on @mkrieger1's comment, what you should do depends on what you want to happen, and whether album_name=None is allowed for your data. Some examples:
If no-album-name is allowed, and you just want to print the results, you can simply replace that one album_name.replace() call with something like

if album_name is not None:
    new_name = album_name.replace(':', '-')

If you're doing other processing you haven't talked about here, and having album_name is None gives a specific alternate path you should take to process otherwise "normal" data, you can follow the if album_name is not None: block above with an else: that assumes album_name is None.

If you just want to skip getting the album_url (and anything else you normally do) in response to album_name is None, put all the stuff you want to skip inside the above if album_name is not None: conditional and the code will silently ignore  those records.

If album_name is None is definitely an error / unexpected condition, read up on try/except blocks and figure out what sorts of error handling you want to do.


问:
A more efficient way of updating object field values in Java
I have a golf application and I want to update an Scorecard which has score, nettScore, points each for 18 holes, so 54 in total

I have spent a few days getting to the point I am at now, All works fine, but I feel there must be a more efficient way of doing this. So far I have this, (ent refers to an Entrant and e refers to an event)

```<code>public void update(long eventId, long memberId, ScoreCard scorecard) {
    Event e = eventRepo.findEventById(eventId);
    Member m = memberRepo.findMemberById(memberId);
    double courseHandicapDouble = m.getHandicap()/113*e.getCourse().getSlopeRating();
    int courseHcp = (int) Math.round(courseHandicapDouble);
    int stableFordTotal = 0;
    int medalTotal = 0;
    int nettTotal = 0;
    List<Entrants> en = entrantsRepo.findAllByEvent(e);
    for(Entrants ent : en) {
        if (ent.getMember().equals(m)) {
            //Hole 1
            //Set the entrants score to the value of hole1 score on the scorecard
            ent.getScoreCard().setH1Score(scorecard.getH1Score());
            //If the players course handicap is more than or equal to the stroke index for the hole, set nett score to score -1
            if(courseHcp >= e.getCourse().getHoles().get(0).getStrokeIndex()) {
                ent.getScoreCard().setH1NettScore(scorecard.getH1Score() - 1);
                //Set points for the first hole as per the setPoints helper method.
                    ent.getScoreCard().setH1Points(setPointsPar(ent.getScoreCard().getH1NettScore(), e.getCourse().getHoles().get(0).getPar()));
            } else {
                ent.getScoreCard().setH1NettScore(scorecard.getH1Score());
                ent.getScoreCard().setH1Points(setPointsPar(ent.getScoreCard().getH1NettScore(), e.getCourse().getHoles().get(0).getPar()));
            }
            //Update running total scores
            medalTotal += ent.getScoreCard().getH1Score();
            stableFordTotal += ent.getScoreCard().getH1Points();
            nettTotal += ent.getScoreCard().getH1NettScore();
//repeated 18 times for holes 2-18
</code>```

The helper method to work out the points is a simple switch method that gives points depending on the score and the par of the hole.

```<code>public int setPointsPar(int score, int par){
        int points = 0;
        if(par == 3) {
            switch (score) {
                case 1:
                    points = 4;
                    break;
                case 2:
                    points = 3;
                    break;
                case 3:
                    points = 2;
                    break;
                case 4:
                    points = 1;
                    break;
            }
        }

        if(par == 4) {
            switch (score) {
                case 1:
                    points = 5;
                    break;
                case 2:
                    points = 4;
                    break;
                case 3:
                    points = 3;
                    break;
                case 4:
                    points = 2;
                    break;
                case 5:
                    points = 1;
                    break;
            }
        }
            if(par == 5) {
                switch (score) {
                    case 1:
                        points = 6;
                        break;
                    case 2:
                        points = 5;
                        break;
                    case 3:
                        points = 4;
                        break;
                    case 4:
                        points = 3;
                        break;
                    case 5:
                        points = 2;
                        break;
                    case 6:
                        points = 1;
                        break;
                }
        }
        return points;
    }
</code>```

This part of the code is almost duplicated 18 times, the only difference being that h1Score is change to h2Score and h1NettScore to h2NettScore etc

```<code>//Hole 1
                //Set the entrants score to the value of hole1 score on the scorecard
                ent.getScoreCard().setH1Score(scorecard.getH1Score());
                //If the players course handicap is more than or equal to the stroke index for the hole, set nett score to score -1
                if(courseHcp >= e.getCourse().getHoles().get(0).getStrokeIndex()) {
                    ent.getScoreCard().setH1NettScore(scorecard.getH1Score() - 1);
                    //Set points for the first hole as per the setPoints helper method.
                        ent.getScoreCard().setH1Points(setPointsPar(ent.getScoreCard().getH1NettScore(), e.getCourse().getHoles().get(0).getPar()));
                } else {
                    ent.getScoreCard().setH1NettScore(scorecard.getH1Score());
                    ent.getScoreCard().setH1Points(setPointsPar(ent.getScoreCard().getH1NettScore(), e.getCourse().getHoles().get(0).getPar()));
                }
                //Update running total scores
                medalTotal += ent.getScoreCard().getH1Score();
                stableFordTotal += ent.getScoreCard().getH1Points();
                nettTotal += ent.getScoreCard().getH1NettScore();
</code>```

I can't think of any possible way to loop through the above so that all the 1s are changed to 2s, then 3s etc.

As I say, what I have works fine. It is more of a learning point for me as I like to write as efficiently as possible.

答:
Instead of 54 different fields, Scorecard should have a list of 18 Hole objects. The Hole instances should contain the required per-hole fields. I would suppose those to be something like par and strokes. The points would be a function of those values, perhaps something like Math.max(par - strokes + 2, 0)

You'd then loop over the list of Hole instances to compute the overall scores for the game, without repeating any code.

Body:
I have a golf application and I want to update an Scorecard which has score, nettScore, points each for 18 holes, so 54 in total

I have spent a few days getting to the point I am at now, All works fine, but I feel there must be a more efficient way of doing this. So far I have this, (ent refers to an Entrant and e refers to an event)

public void update(long eventId, long memberId, ScoreCard scorecard) {
    Event e = eventRepo.findEventById(eventId);
    Member m = memberRepo.findMemberById(memberId);
    double courseHandicapDouble = m.getHandicap()/113*e.getCourse().getSlopeRating();
    int courseHcp = (int) Math.round(courseHandicapDouble);
    int stableFordTotal = 0;
    int medalTotal = 0;
    int nettTotal = 0;
    List<Entrants> en = entrantsRepo.findAllByEvent(e);
    for(Entrants ent : en) {
        if (ent.getMember().equals(m)) {
            //Hole 1
            //Set the entrants score to the value of hole1 score on the scorecard
            ent.getScoreCard().setH1Score(scorecard.getH1Score());
            //If the players course handicap is more than or equal to the stroke index for the hole, set nett score to score -1
            if(courseHcp >= e.getCourse().getHoles().get(0).getStrokeIndex()) {
                ent.getScoreCard().setH1NettScore(scorecard.getH1Score() - 1);
                //Set points for the first hole as per the setPoints helper method.
                    ent.getScoreCard().setH1Points(setPointsPar(ent.getScoreCard().getH1NettScore(), e.getCourse().getHoles().get(0).getPar()));
            } else {
                ent.getScoreCard().setH1NettScore(scorecard.getH1Score());
                ent.getScoreCard().setH1Points(setPointsPar(ent.getScoreCard().getH1NettScore(), e.getCourse().getHoles().get(0).getPar()));
            }
            //Update running total scores
            medalTotal += ent.getScoreCard().getH1Score();
            stableFordTotal += ent.getScoreCard().getH1Points();
            nettTotal += ent.getScoreCard().getH1NettScore();
//repeated 18 times for holes 2-18

The helper method to work out the points is a simple switch method that gives points depending on the score and the par of the hole.

public int setPointsPar(int score, int par){
        int points = 0;
        if(par == 3) {
            switch (score) {
                case 1:
                    points = 4;
                    break;
                case 2:
                    points = 3;
                    break;
                case 3:
                    points = 2;
                    break;
                case 4:
                    points = 1;
                    break;
            }
        }

        if(par == 4) {
            switch (score) {
                case 1:
                    points = 5;
                    break;
                case 2:
                    points = 4;
                    break;
                case 3:
                    points = 3;
                    break;
                case 4:
                    points = 2;
                    break;
                case 5:
                    points = 1;
                    break;
            }
        }
            if(par == 5) {
                switch (score) {
                    case 1:
                        points = 6;
                        break;
                    case 2:
                        points = 5;
                        break;
                    case 3:
                        points = 4;
                        break;
                    case 4:
                        points = 3;
                        break;
                    case 5:
                        points = 2;
                        break;
                    case 6:
                        points = 1;
                        break;
                }
        }
        return points;
    }

This part of the code is almost duplicated 18 times, the only difference being that h1Score is change to h2Score and h1NettScore to h2NettScore etc

//Hole 1
                //Set the entrants score to the value of hole1 score on the scorecard
                ent.getScoreCard().setH1Score(scorecard.getH1Score());
                //If the players course handicap is more than or equal to the stroke index for the hole, set nett score to score -1
                if(courseHcp >= e.getCourse().getHoles().get(0).getStrokeIndex()) {
                    ent.getScoreCard().setH1NettScore(scorecard.getH1Score() - 1);
                    //Set points for the first hole as per the setPoints helper method.
                        ent.getScoreCard().setH1Points(setPointsPar(ent.getScoreCard().getH1NettScore(), e.getCourse().getHoles().get(0).getPar()));
                } else {
                    ent.getScoreCard().setH1NettScore(scorecard.getH1Score());
                    ent.getScoreCard().setH1Points(setPointsPar(ent.getScoreCard().getH1NettScore(), e.getCourse().getHoles().get(0).getPar()));
                }
                //Update running total scores
                medalTotal += ent.getScoreCard().getH1Score();
                stableFordTotal += ent.getScoreCard().getH1Points();
                nettTotal += ent.getScoreCard().getH1NettScore();

I can't think of any possible way to loop through the above so that all the 1s are changed to 2s, then 3s etc.

As I say, what I have works fine. It is more of a learning point for me as I like to write as efficiently as possible.


问:
Reference a sheet range dynamically inside formula by using a cell value
How can I reference a sheet range by using a cell value?

i.e

This is a working formula

```<code>=filter(dump!1:1000,dump!G:G = "Active")
</code>```

However, I need to reference the sheet's G:G range dynamically by using a cell value.
Let's assume my cell A1 contains "G:G" as the value inside it.

My formula would be something like

```<code>=filter(dump!1:1000,"dump!"&A2 = "Active")
</code>```

..but of course it doesn't work because I'm not using the syntax properly.

答:
use:

```<code>=FILTER(dump!1:1000, INDIRECT("dump!"&A1) = "Active")
</code>```

but keep in mind that G:G needs to have exactly 1000 rows otherwise you will face ARRAY_ error

Body:
How can I reference a sheet range by using a cell value?

i.e

This is a working formula

=filter(dump!1:1000,dump!G:G = "Active")

However, I need to reference the sheet's G:G range dynamically by using a cell value.
Let's assume my cell A1 contains "G:G" as the value inside it.

My formula would be something like

=filter(dump!1:1000,"dump!"&A2 = "Active")

..but of course it doesn't work because I'm not using the syntax properly.

Body:
use:

=FILTER(dump!1:1000, INDIRECT("dump!"&A1) = "Active")

but keep in mind that G:G needs to have exactly 1000 rows otherwise you will face ARRAY_ error


问:
Why is this not outside of the nav Bar
so I am pretty new to development and come across a problem, I think I am missing somthing but I can't tell. So I am building a nav bar and then a drop down menu. I believe that the li is in the ul so that why it is not coming out of it. So how could I fix this. If you know any website that would be good let me know thank you

Code:
https://codepen.io/Giannilmgc/pen/JjrgZdr?editors=1111
Output:
https://codepen.io/Giannilmgc/full/JjrgZdr

To see what wrong keep your cursor over the to do tab and scroll down

@import url("https://fonts.googleapis.com/css2?family=Inter:wght@300&display=swap");

/* Here is the body style where we change the background */
body {
  background: linear-gradient(135deg, #36454f 0%, #ffdd3c 100%);
  margin: 5px;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: auto;
  background-color: white;
  border-radius: 50px;
}

li {
  float: left;
  width: 16.667%;
  transition-duration: 1s;
}

li a {
  display: block;
  color: black;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  transition-duration: 1s;
}
li:hover {
  background-color: black;
}

li a:hover {
  background-color: #36454f;
  color: white;
}
#homepageLink {
  background-color: #cccccc;
}

.dropdown {
  position: relative;
  display: inline-block;
}

ul li ul {
  display: none;
  position: absolute;
  background-color: #cccccc;
  width: 20%;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 10;
  text-decoration: none;
  display: block;
}

.dropdown-content a:hover {
  background-color: #36454f;
  color: white;
}

.dropdown:hover .dropdown-content {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>

  <title> My Site </title>
  <link rel="stylesheet" href="CSS/Homepage-Css.css" />
</head>

<body>

  <body>

    <div>
      <ul>
        <li>HomePage</li>
        <li>Journal</li>
        <li>Calander </li>
        <li class="dropdown">To do
          <ul class="dropdown-content">
            Latin
            Scince
            Ela

          </ul>
        </li>
        <li>Service</li>
        <li>Contact</li>

      </ul>
    </div>

    <div class="time">
      <span id="display_ct"></span>
  </body>
  <!-- Adding Script to the bottom ... Very Imporantent  -->
  <script src="Javascript/Homepage-Java.js"></script></code>```

Thank you

答:
In the dropdown class you have set the position in relative. Change it to absolute and your drop down menu will come out.</p>
```<code>.dropdown {
  position: absolute;
  display: inline-block;
}
</code>```

Title: Why is this not outside of the nav Bar

Body:
so I am pretty new to development and come across a problem, I think I am missing somthing but I can't tell. So I am building a nav bar and then a drop down menu. I believe that the li is in the ul so that why it is not coming out of it. So how could I fix this. If you know any website that would be good let me know thank you

Code:
https://codepen.io/Giannilmgc/pen/JjrgZdr?editors=1111
Output:
https://codepen.io/Giannilmgc/full/JjrgZdr

To see what wrong keep your cursor over the to do tab and scroll down

@import url("https://fonts.googleapis.com/css2?family=Inter:wght@300&display=swap");

/* Here is the body style where we change the background */
body {
  background: linear-gradient(135deg, #36454f 0%, #ffdd3c 100%);
  margin: 5px;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: auto;
  background-color: white;
  border-radius: 50px;
}

li {
  float: left;
  width: 16.667%;
  transition-duration: 1s;
}

li a {
  display: block;
  color: black;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  transition-duration: 1s;
}
li:hover {
  background-color: black;
}

li a:hover {
  background-color: #36454f;
  color: white;
}
#homepageLink {
  background-color: #cccccc;
}

.dropdown {
  position: relative;
  display: inline-block;
}

ul li ul {
  display: none;
  position: absolute;
  background-color: #cccccc;
  width: 20%;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 10;
  text-decoration: none;
  display: block;
}

.dropdown-content a:hover {
  background-color: #36454f;
  color: white;
}

.dropdown:hover .dropdown-content {
  display: block;
}

  <title> My Site </title>
  <link rel="stylesheet" href="CSS/Homepage-Css.css" />

HomePage

Journal

Calander

To do

            Latin
            Scince
            Ela

Service

Contact

Thank you

Body:
In the dropdown class you have set the position in relative. Change it to absolute and your drop down menu will come out.

.dropdown {
  position: absolute;
  display: inline-block;
}


问:
Different scroll speeds for elements in array
I have different randomly-styled stars in an array and I would like them to each have different scroll speeds between -.2 and -.8. The idea is to have them do a parallax effect, and it'd be cool to have everything a little random.

This was the original scroll speed code using images:

```<code>var starsOne = document.querySelector("#starsOne");
function setTranslate(xPos, yPos, el) {
    el.style.transform = "translate3d(" + xPos + ", " + yPos + "px, 0)";
}
var xScrollPosition;
var yScrollPosition;
function scrollLoop() {
    xScrollPosition = window.scrollX;
    yScrollPosition = window.scrollY;
    setTranslate(0, yScrollPosition * -0.6, starsOne);
    requestAnimationFrame(scrollLoop);
}
window.addEventListener("load", scrollLoop, false);
</code>```

I've been trying to integrate the above code somehow for the array:

```<code>let starScrollMin = 2;
let starScrollMax = 8;
var starScrollSpeed = -Math.abs((Math.floor(Math.random() * (starScrollMax - starScrollMin + 1)) + starScrollMin) / 10);

function starScroll() {
        for (i = 0; i < starDivvyArr.length; i++) {
        yScrollPos = window.scrollY;
        starDivvyArr[i].style.transform = "translate3d(" + 0 + "px, " + yScrollPos * starScrollSpeed + "px, 0)";
        }
        requestAnimationFrame(starScroll);
}
    window.addEventListener("load", starScroll, false);

</code>```

If starScrollSpeed is global, then all the stars move in a big chunk. If it's within the starScroll() function, the values are at least different per star, but it gets crazy as it keeps randomizing and multiplying.

Any ideas on how to randomize the scroll speed for each star so it looks like a parallax effect, without them moving in one single chunk or going crazy? Or is it a safer bet to make a bunch of css lines and then randomly assign classes?

jsfiddle

答:
It's a bit unclear what exactly you're after.

If you're trying to  set a random scroll speed for each star, and not change it every time the startScroll triggers.
you could set a speed for each start separately inside the loop and use that in the startScroll function instead:

```<code>...
starDivvyArr[i].starScrollSpeed = -Math.abs((Math.floor(Math.random() * (starScrollMax - starScrollMin + 1)) + starScrollMin) / 10);
...
 starDivvyArr[i].style.transform = "translate3d(" + 0 + "px, " + yScrollPos * starDivvyArr[i].starScrollSpeed + "px, 0)";
</code>```

    var starCount = 25;
    let starContain = document.getElementById('starContain');

    /*Create star divs*/
    for (var i = 0; i < starCount; i++) {
      var starDiv = document.createElement("div");
      starDiv.className = 'star';
      starContain.append(starDiv);
    }

    /*Make an array from the star divs*/
    var starDivvy = document.querySelectorAll(".star");
    var starDivvyArr = Array.from(starDivvy);

    /*Create some possible styles*/
    var starColor = ['yellow', 'blue', 'white'];
    var starSizeMin = 5;
    var starSizeMax = 25;
    let starContainWidth = starContain.offsetWidth;
    let starContainHeight = starContain.offsetHeight;
    let starScrollMin = 2;
    let starScrollMax = 8;

    /*Give the star array some different styles*/
    for (i = 0; i < starDivvyArr.length; i++) {
      /*Change star color*/
      starDivvyArr[i].style.backgroundColor = starColor[Math.floor(Math.random() * starColor.length)];
      /*Change star position within container*/
      starDivvyArr[i].style.left = Math.floor((Math.random() * starContainWidth) + 1) + "px";
      starDivvyArr[i].style.top = Math.floor((Math.random() * starContainHeight) + 1) + "px";
      /*Change star size*/
      starDivvyArr[i].style.width = Math.floor(Math.random() * (starSizeMax - starSizeMin + 1)) + starSizeMin + "px";
      starDivvyArr[i].style.height = starDivvyArr[i].style.width;
      starDivvyArr[i].starScrollSpeed = -Math.abs((Math.floor(Math.random() * (starScrollMax - starScrollMin + 1)) + starScrollMin) / 10);
    }

    /*>>>>>>>POINT OF CONFUSION<<<<<<<*/
    /*Randomize scroll speed between -0.2 and -0.8*/

    /*Give the stars a scrolling function*/
    function starScroll() {
      for (i = 0; i < starDivvyArr.length; i++) {
        yScrollPos = window.scrollY;
        starDivvyArr[i].style.transform = "translate3d(" + 0 + "px, " + yScrollPos * starDivvyArr[i].starScrollSpeed + "px, 0)";
      }
      requestAnimationFrame(starScroll);
    }

    window.addEventListener("load", starScroll, false);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>*{
  margin:0 auto;
}

section{
  width:100vw;
  height:150vh;
}

.section1{
  background-color:#000;
}

.section2{
  background-color:#202;
}

h2{
  text-align:center;
  color:#ccc;
}

#starContain{
    width:100vw;
    height:500px;
    position:absolute;
    top:50vh;
    z-index:2;
    background-color:rgba(255,255,255,0.2);
}

.star{
    background-color:green;
    position:absolute;
    z-index:100;
    border-radius:50%;
}</code>```

    Section 1

    Section 2

```

Body:
I have different randomly-styled stars in an array and I would like them to each have different scroll speeds between -.2 and -.8. The idea is to have them do a parallax effect, and it'd be cool to have everything a little random.

This was the original scroll speed code using images:

var starsOne = document.querySelector("#starsOne");
function setTranslate(xPos, yPos, el) {
    el.style.transform = "translate3d(" + xPos + ", " + yPos + "px, 0)";
}
var xScrollPosition;
var yScrollPosition;
function scrollLoop() {
    xScrollPosition = window.scrollX;
    yScrollPosition = window.scrollY;
    setTranslate(0, yScrollPosition * -0.6, starsOne);
    requestAnimationFrame(scrollLoop);
}
window.addEventListener("load", scrollLoop, false);

I've been trying to integrate the above code somehow for the array:

let starScrollMin = 2;
let starScrollMax = 8;
var starScrollSpeed = -Math.abs((Math.floor(Math.random() * (starScrollMax - starScrollMin + 1)) + starScrollMin) / 10);

function starScroll() {
        for (i = 0; i < starDivvyArr.length; i++) {
        yScrollPos = window.scrollY;
        starDivvyArr[i].style.transform = "translate3d(" + 0 + "px, " + yScrollPos * starScrollSpeed + "px, 0)";
        }
        requestAnimationFrame(starScroll);
}
    window.addEventListener("load", starScroll, false);

If starScrollSpeed is global, then all the stars move in a big chunk. If it's within the starScroll() function, the values are at least different per star, but it gets crazy as it keeps randomizing and multiplying.

Any ideas on how to randomize the scroll speed for each star so it looks like a parallax effect, without them moving in one single chunk or going crazy? Or is it a safer bet to make a bunch of css lines and then randomly assign classes?

jsfiddle

Body:
It's a bit unclear what exactly you're after.

If you're trying to  set a random scroll speed for each star, and not change it every time the startScroll triggers.
you could set a speed for each start separately inside the loop and use that in the startScroll function instead:

...
starDivvyArr[i].starScrollSpeed = -Math.abs((Math.floor(Math.random() * (starScrollMax - starScrollMin + 1)) + starScrollMin) / 10);
...
 starDivvyArr[i].style.transform = "translate3d(" + 0 + "px, " + yScrollPos * starDivvyArr[i].starScrollSpeed + "px, 0)";

    var starCount = 25;
    let starContain = document.getElementById('starContain');

    /*Create star divs*/
    for (var i = 0; i < starCount; i++) {
      var starDiv = document.createElement("div");
      starDiv.className = 'star';
      starContain.append(starDiv);
    }

    /*Make an array from the star divs*/
    var starDivvy = document.querySelectorAll(".star");
    var starDivvyArr = Array.from(starDivvy);

    /*Create some possible styles*/
    var starColor = ['yellow', 'blue', 'white'];
    var starSizeMin = 5;
    var starSizeMax = 25;
    let starContainWidth = starContain.offsetWidth;
    let starContainHeight = starContain.offsetHeight;
    let starScrollMin = 2;
    let starScrollMax = 8;

    /*Give the star array some different styles*/
    for (i = 0; i < starDivvyArr.length; i++) {
      /*Change star color*/
      starDivvyArr[i].style.backgroundColor = starColor[Math.floor(Math.random() * starColor.length)];
      /*Change star position within container*/
      starDivvyArr[i].style.left = Math.floor((Math.random() * starContainWidth) + 1) + "px";
      starDivvyArr[i].style.top = Math.floor((Math.random() * starContainHeight) + 1) + "px";
      /*Change star size*/
      starDivvyArr[i].style.width = Math.floor(Math.random() * (starSizeMax - starSizeMin + 1)) + starSizeMin + "px";
      starDivvyArr[i].style.height = starDivvyArr[i].style.width;
      starDivvyArr[i].starScrollSpeed = -Math.abs((Math.floor(Math.random() * (starScrollMax - starScrollMin + 1)) + starScrollMin) / 10);
    }

    /*>>>>>>>POINT OF CONFUSION<<<<<<<*/
    /*Randomize scroll speed between -0.2 and -0.8*/

    /*Give the stars a scrolling function*/
    function starScroll() {
      for (i = 0; i < starDivvyArr.length; i++) {
        yScrollPos = window.scrollY;
        starDivvyArr[i].style.transform = "translate3d(" + 0 + "px, " + yScrollPos * starDivvyArr[i].starScrollSpeed + "px, 0)";
      }
      requestAnimationFrame(starScroll);
    }

    window.addEventListener("load", starScroll, false);

*{
  margin:0 auto;
}

section{
  width:100vw;
  height:150vh;
}

.section1{
  background-color:#000;
}

.section2{
  background-color:#202;
}

h2{
  text-align:center;
  color:#ccc;
}

#starContain{
    width:100vw;
    height:500px;
    position:absolute;
    top:50vh;
    z-index:2;
    background-color:rgba(255,255,255,0.2);
}

.star{
    background-color:green;
    position:absolute;
    z-index:100;
    border-radius:50%;
}

<main>
  <section class="section1">
    <h2>
    Section 1
    </h2>
  </section>

  <div id="starContain">

  </div>

  <section class="section2">
    <h2>
    Section 2
    </h2>
  </section>
</main>


问:
MS Access DSUM issue
I have a text box in a form that sums up an "encumbered" column with the where condition matches the ID number in that table and the ID shown in the form. I get a #Name error but all of the naming is correct.

=DSum("EncAmount",[tblEncumbrances],"[BID]='" & [frmProcurementEdit]![BudgetItemID] & "''")

tblEncumbrances is the table name, EncAmount is the column whose sum I need to add up. FrmProcurementEdit is the form that the textbox is on and BudgetItemID (Also on the form) needs to match BID(In tblEncumbrances)

Am I missing something here? Any help would be greatly appreciated!!

答: =DSum("[EncAmount]","tblEncumbrances","[BID]='" & [BudgetItemID] & "'")</p>

Title: MS Access DSUM issue


问:
C++: Is it a bad idea to use the value of a function returning shared_ptr directly?
For example:

```<code>boost::shared_ptr<int> test() {
    boost::shared_ptr<int> x(new int(3));
    return x;
}

void function() {
    int y = *test();
    ...
}
</code>```

Is it also a bad idea to use shared_ptr to avoid copying the whole object? Like a vector of matrices/images for example.

答:
In the general case, no. Your example copies the contents of the shared_ptr, and then the original value is deleted.

Now, the bigger issue here is that it's fantastically inefficient to do a dynamic memory allocation for an int, but I'm assuming you're not doing that in real code. :)

Body:
For example:

boost::shared_ptr<int> test() {
    boost::shared_ptr<int> x(new int(3));
    return x;
}

void function() {
    int y = *test();
    ...
}

Is it also a bad idea to use shared_ptr to avoid copying the whole object? Like a vector of matrices/images for example.


问:
Is conversion of a function pointer to a uintptr_t / intptr_t invalid?
Microsoft extensions to C and C++:

To perform the same cast and also maintain ANSI compatibility, you can cast the function pointer
to a uintptr_t before you cast it to a data pointer:

```<code>int ( * pfunc ) ();
int *pdata;
pdata = ( int * ) (uintptr_t) pfunc;
</code>```

Rationale for C, Revision 5.10, April-2003:

Even with an explicit cast, it is invalid to convert a function pointer to an object pointer
or a pointer to void, or vice versa.

C11:

7.20.1.4 Integer types capable of holding object pointers

Does it mean that pdata = ( int * ) (uintptr_t) pfunc; in invalid?

As Steve Summit says:

The C standard is written to assume that pointers to different object types, and especially pointers to function as opposed to object types, might have different representations.

While pdata = ( int * ) pfunc; leads to UB, it seems that pdata = ( int * ) (uintptr_t) pfunc; leads to IB. This is because "Any pointer type may be converted to an integer type" and "An integer may be converted to any pointer type" and uintptr_t is integer type.

答:
Is conversion of a function pointer to a uintptr_t / intptr_t invalid?

No.  It may be valid.  It may be undefined behavior.

Conversion of a function pointer to ìnt* is not defined.  Nor to any  object pointer.  Nor to void *.

pdata = ( int * ) pfunc; is undefined behavior.

Conversion of a function pointer to an integer type is allowed, with restrictions:

Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type. C17dr 6.3.2.3 6

Also integer to a pointer type is allowed.

An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.  C17dr 6.3.2.3 6

void * to integer to void * is defined.  Object pointer to/from void* is defined.  Then the optional (u)intptr_t types are sufficient for round-trip success.  Yet we are concerned about a function pointer. Often enough function pointers are wider than an int *.

Thus converting a function pointer to int * only makes sense through an integer type, wider the better.

VS may recommend through the optional type uintptr_t and is likely sufficient if information is lossless on other platforms.  Yet uintmax_t may afford less loss of information, especially in the function pointer to integer step, so I pedantically suggest:

```<code>pdata = ( int * ) (uintmax_t) pfunc;
</code>```

Regardless of the steps taken, code is likely to become implementation specific and deserves guards.

```<code>#ifdef this && that
  pdata = ( int * ) (uintmax_t) pfunc;
#else
  #error TBD code
#endif
</code>```

Body:
Microsoft extensions to C and C++:

To perform the same cast and also maintain ANSI compatibility, you can cast the function pointer
to a uintptr_t before you cast it to a data pointer:

int ( * pfunc ) ();
int *pdata;
pdata = ( int * ) (uintptr_t) pfunc;

Rationale for C, Revision 5.10, April-2003:

Even with an explicit cast, it is invalid to convert a function pointer to an object pointer
or a pointer to void, or vice versa.

C11:

7.20.1.4 Integer types capable of holding object pointers

Does it mean that pdata = ( int * ) (uintptr_t) pfunc; in invalid?

As Steve Summit says:

The C standard is written to assume that pointers to different object types, and especially pointers to function as opposed to object types, might have different representations.

While pdata = ( int * ) pfunc; leads to UB, it seems that pdata = ( int * ) (uintptr_t) pfunc; leads to IB. This is because "Any pointer type may be converted to an integer type" and "An integer may be converted to any pointer type" and uintptr_t is integer type.

Body:
Is conversion of a function pointer to a uintptr_t / intptr_t invalid?

No.  It may be valid.  It may be undefined behavior.

Conversion of a function pointer to ìnt* is not defined.  Nor to any  object pointer.  Nor to void *.

pdata = ( int * ) pfunc; is undefined behavior.

Conversion of a function pointer to an integer type is allowed, with restrictions:

Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type. C17dr 6.3.2.3 6

Also integer to a pointer type is allowed.

An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.  C17dr 6.3.2.3 6

void * to integer to void * is defined.  Object pointer to/from void* is defined.  Then the optional (u)intptr_t types are sufficient for round-trip success.  Yet we are concerned about a function pointer. Often enough function pointers are wider than an int *.

Thus converting a function pointer to int * only makes sense through an integer type, wider the better.

VS may recommend through the optional type uintptr_t and is likely sufficient if information is lossless on other platforms.  Yet uintmax_t may afford less loss of information, especially in the function pointer to integer step, so I pedantically suggest:

pdata = ( int * ) (uintmax_t) pfunc;

Regardless of the steps taken, code is likely to become implementation specific and deserves guards.

#ifdef this && that
  pdata = ( int * ) (uintmax_t) pfunc;
#else
  #error TBD code
#endif


问:
Deploy angular application on nginx server with Docker Welcome to nginx
I developed an Angular 7 application and now I'm going to deploy it on production server on an nginx server. I'm pretty new to frontend deployment on nginx server, so probably I'm missing something easy to find. I decided to use Docker to manager the deployment.

The application name is MyWalletFe.

nginx server configuration file

Path: ./conf/default.conf

```<code>server {
    listen 80;

    location / {
        root /usr/share/nginx/html;
        index index.html index.htm;
        try_files $uri $uri/ /index.html;
    }

}
</code>```

Dockerfile

```<code># build
FROM node:alpine as builder
WORKDIR /app
COPY package.json .
RUN npm install
COPY . .
RUN npm run build

# deploy
FROM nginx
EXPOSE 80
COPY ./conf/default.conf /etc/nginx/conf.d/default.conf
COPY --from=builder /app/dist/ /usr/share/nginx/html
</code>```

Where I copy my nginx configuration file in the default location, then I copy the output of npm run build from previous stage in the /usr/share/nging/html.

Output

I always get the default nginx webpage:

And the reason why this happens is that the folder /app/dist contains a subfolder with the name of the app, MyWalletFe, which contains all the file of the Angular application (the image is taken after run locally npm run build to show the folder structure):

while on the production server in folder /usr/share/nginx/html there is still the default index.html with this page that is served.

```<code>root@3b7da83d2bca:/usr/share/nginx/html# ls -l
total 12
-rw-r--r-- 1 root root  494 Mar  3 14:32 50x.html
drwxr-xr-x 2 root root 4096 Apr 13 20:32 MyWalletFE
-rw-r--r-- 1 root root  612 Mar  3 14:32 index.html
</code>```

I think that for this to work the content of MyWalletFe folder should be copied to the parent folder (/usr/share/nginx/html); in this case default.conf or Dockerfile contain some errors.

Is there something that is configured in a wrong way? In Resources section I've added the article which I followed.

Resources

Angular in Docker with Nginx

答:
Sometimes the cause can be the most stupid thing, having something like this in my angular.json:

```<code>  "projects": {
    "my-app": {
      "architect": {
        "build": {
          "options": {
            "outputPath": "dist/my-app",
</code>```

that was causing my app was copied to /usr/share/nginx/html/my-app

I hope you don't waste several hours breaking your mind like me :||

Body:
I developed an Angular 7 application and now I'm going to deploy it on production server on an nginx server. I'm pretty new to frontend deployment on nginx server, so probably I'm missing something easy to find. I decided to use Docker to manager the deployment.

The application name is MyWalletFe.

nginx server configuration file

Path: ./conf/default.conf

server {
    listen 80;

    location / {
        root /usr/share/nginx/html;
        index index.html index.htm;
        try_files $uri $uri/ /index.html;
    }

}

Dockerfile

# build
FROM node:alpine as builder
WORKDIR /app
COPY package.json .
RUN npm install
COPY . .
RUN npm run build

# deploy
FROM nginx
EXPOSE 80
COPY ./conf/default.conf /etc/nginx/conf.d/default.conf
COPY --from=builder /app/dist/ /usr/share/nginx/html

Where I copy my nginx configuration file in the default location, then I copy the output of npm run build from previous stage in the /usr/share/nging/html.

Output

I always get the default nginx webpage:

And the reason why this happens is that the folder /app/dist contains a subfolder with the name of the app, MyWalletFe, which contains all the file of the Angular application (the image is taken after run locally npm run build to show the folder structure):

while on the production server in folder /usr/share/nginx/html there is still the default index.html with this page that is served.

root@3b7da83d2bca:/usr/share/nginx/html# ls -l
total 12
-rw-r--r-- 1 root root  494 Mar  3 14:32 50x.html
drwxr-xr-x 2 root root 4096 Apr 13 20:32 MyWalletFE
-rw-r--r-- 1 root root  612 Mar  3 14:32 index.html

I think that for this to work the content of MyWalletFe folder should be copied to the parent folder (/usr/share/nginx/html); in this case default.conf or Dockerfile contain some errors.

Is there something that is configured in a wrong way? In Resources section I've added the article which I followed.

Resources

Angular in Docker with Nginx

Body:
Sometimes the cause can be the most stupid thing, having something like this in my angular.json:

  "projects": {
    "my-app": {
      "architect": {
        "build": {
          "options": {
            "outputPath": "dist/my-app",

that was causing my app was copied to /usr/share/nginx/html/my-app

I hope you don't waste several hours breaking your mind like me :||


问:
Field-level authorization with Amplify GrraphQL
I'm having trouble sorting out field-level authorization. I would like to have a particular field in a model be read-only.

Here's a simplified version of the schema:

```<code>type Thing
  @model
  @auth(
    rules: [
      {
        allow: groups
        groups: ["Admins"]
        operations: [read, create, update]
      }
      { allow: private, operations: [read]}
    ]
  ) {
  id: ID!
  foo: String
  bar: String
  baz: ID
    @auth(
      rules: [
        { allow: groups, groups: ["Admins"], operations: [read] }
      ]
    )
}
</code>```

My expectation is that all users would be able to read foo, bar, and baz, but only members of Admins would be able to update foo and bar, but that not even Admins would be allowed to update baz. I'm finding, however, that Admins are still able to write to baz, which I do not want.

I would think that field-level rules would have precedence over model-level rules.

Is such a thing possible?

答:
It does appear to be possible, from the docs:

When an authorization rule is added to a field, it'll strictly define the authorization rules applied on the field. Field-level authorization rules do not inherit model-level authorization rules. Meaning, only the specified field-level authorization rule is applied.

It seems like if you add a field-level rule the model ignores whatever authorizations you have at the model-level.  There are several examples here for good reference: https://docs.amplify.aws/cli-legacy/graphql-transformer/auth/#field-level-authorization

As far as the issue you are seeing, not sure, seems like you've set it up correctly, maybe there's another issue here?

Body:
I'm having trouble sorting out field-level authorization. I would like to have a particular field in a model be read-only.

Here's a simplified version of the schema:

type Thing
  @model
  @auth(
    rules: [
      {
        allow: groups
        groups: ["Admins"]
        operations: [read, create, update]
      }
      { allow: private, operations: [read]}
    ]
  ) {
  id: ID!
  foo: String
  bar: String
  baz: ID
    @auth(
      rules: [
        { allow: groups, groups: ["Admins"], operations: [read] }
      ]
    )
}

My expectation is that all users would be able to read foo, bar, and baz, but only members of Admins would be able to update foo and bar, but that not even Admins would be allowed to update baz. I'm finding, however, that Admins are still able to write to baz, which I do not want.

I would think that field-level rules would have precedence over model-level rules.

Is such a thing possible?


问:
How to start Electron.NET blazor app on windows start?
I am working on a project that uses Electron.NET and Blazor. I am looking for a solution how to start it automatically on OS(Win || MAC || Linux) start.
ElectronNET.API -> Version="9.31.2"
.NET Version = netcoreapp3.1</p>

答:
There is a folder in Windows 10/11 located at %AppData%\Microsoft\Windows\Start Menu\Programs\Startup.  If you put a shortcut to your app in there it will run at startup for the current user.

If you want to run at startup for all users you will need:

admin escalation

create a task in Windows Task Scheduler with the trigger When the computer starts

I don't know how to do any of that on a Mac/Linux, but likely the basic process will be the same:

find an o/s specific way of starting a program

get your app to detect the platform it's running on

invoke said process putting shortcuts, links or config entries in the right places

I don't think Electron/ElectronNET has any specific helpers for this sort of thing.

There is an npm library called auto-launch that you would use if you were building Electron rather than ElectronNET. See NPM - auto-launch and also this article on how to use it in Electron. You might be able to port something into your app from there.


问:
Color changeable SVG?
I wish to build a website where icon colors can be easily changed with the only change of the css. I've been given a set of custom icons in form of svg files.

I've already experimented with background color, filters and alike (see https://codesandbox.io/s/exciting-montalcini-xfufu?file=/index.html).

Which is the best technique to use? Should I generate a font from the SVGs?

Title: Color changeable SVG?

Body:
First, open your SVG file and change the style of the .cls-1 path:

.cls-1 { fill: currentColor; }

Now place the SVG inside your HTML code. The color of the shield will follow the current font color. The <use> tag will allow you to duplicate it easily. Just make sure to hide the original instance of the SVG with style="display: none;".

svg {
  width: 42px;
  height: 50px;
}

.green-icon { color: green; }
.red-icon { color: red; }
.blue-icon { color: blue; }

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 768.42 907.1" style="display: none;"><defs><style>.cls-1{fill:currentColor;}.cls-2{fill:#fff;}</style></defs><g id="Livello_2" data-name="Livello 2"><g id="Layer_1" data-name="Layer 1"><path class="cls-1" d="M766.27,141.2c-157.6,0-279.1-44.3-382.5-141.2C282,97.7,160.47,141.2,2.07,141.2c0,253.7-53.4,618.2,382.5,765.9C820.47,758.6,766.27,394.9,766.27,141.2Z"/><path class="cls-2" d="M449.87,436.6a43.42,43.42,0,0,1,28.9-7.1l113.9-114-63.8-63.8L415,365.7a42.67,42.67,0,0,1-7.4,29.2Z"/><polygon class="cls-2" points="251.17 575.4 246.97 571.3 225.37 588.8 188.97 646.1 198.37 655.4 255.67 619 273.17 597.5 268.97 593.3 341.47 520.8 323.47 503.1 251.17 575.4"/><path class="cls-2" d="M350.27,374.5a88.86,88.86,0,0,0-108.9-109.8l50.4,50.3-13.2,49.3-49.4,13.2-50.3-50.3a88.86,88.86,0,0,0,113.5,107.7l.3.3,207.1,207.1a42,42,0,0,0,59.4-59.4Zm182.8,261a16,16,0,1,1,16.1-16A16,16,0,0,1,533.07,635.5Z"/></g></g></svg>

<svg class="green-icon" viewBox="0 0 768.42 907.1"><use href="#Layer_1"></use></svg>
<svg class="red-icon" viewBox="0 0 768.42 907.1"><use href="#Layer_1"></use></svg>
<svg class="blue-icon" viewBox="0 0 768.42 907.1"><use href="#Layer_1"></use></svg>

(This solution is based on this article from CSS Tricks.)


问:
Spin up elasticsearch container locally on linux
I have been reading about running elasticsearch while following this page but when I reach on the step of running this command :

```<code>docker run -p 127.0.0.1:9200:9200 -p 127.0.0.1:9300:9300 -e "discovery.type=single-node" docker.elastic.co/elasticsearch/elasticsearch:7.17.0
</code>```

Nothing happens, it just finsihes and nothing happens what could be wrong ?

The first command works well :

```<code>docker pull docker.elastic.co/elasticsearch/elasticsearch:7.17.0
</code>```

But spinning doesn't work

答:
Reason as to why it was not working it's because I was using a wrong version for my OS.

I had get a suitable version for my OS here :
Link

Body:
I have been reading about running elasticsearch while following this page but when I reach on the step of running this command :

docker run -p 127.0.0.1:9200:9200 -p 127.0.0.1:9300:9300 -e "discovery.type=single-node" docker.elastic.co/elasticsearch/elasticsearch:7.17.0

Nothing happens, it just finsihes and nothing happens what could be wrong ?

The first command works well :

docker pull docker.elastic.co/elasticsearch/elasticsearch:7.17.0

But spinning doesn't work


问:
Override PropertyNamingPolicy for specific API calls
My ASP.Net Core API is using default JSON property naming policy (camel case), but some API calls consumed by external modules expects the API results in Pascal Case.

Is there a way to override the default policy at individual API call level? I mean, only for 1 or 2 calls.

答:
Yes it is possible by specifying the PropertyNamingPolicy in the JsonSerializerOptions. You can do this globally or when you are creating a JsonResult object. Since you want this only on specific calls I think the second option is what you are looking for.
Here is the sample code form the official documentation for this case.

```<code>[HttpGet]
public IActionResult Get() =>
    new JsonResult(
        _todoItemStore.GetList(),
        new JsonSerializerOptions
        {
            PropertyNamingPolicy = null
        });
</code>```

Body:
Yes it is possible by specifying the PropertyNamingPolicy in the JsonSerializerOptions. You can do this globally or when you are creating a JsonResult object. Since you want this only on specific calls I think the second option is what you are looking for.
Here is the sample code form the official documentation for this case.

[HttpGet]
public IActionResult Get() =>
    new JsonResult(
        _todoItemStore.GetList(),
        new JsonSerializerOptions
        {
            PropertyNamingPolicy = null
        });


问:
A SQL Server function to generate of sequential numbers
I would like to have a SQL Server function dbo.GetNextNumber(), which would generate sequential numbers for each call. As far as I understand this is impossible with a native T-SQL function as SQL Server insists the functions has to be deterministic. But, if you could show me a native T-SQL function that does this would really make my day.

I thought perhaps this could be possible to write using a CLR function. As CLR functions are static, the sequence numbers need to be stored in the calling context of the set operation, as storing it as a static variable would result in several connections using the same sequence, resulting in not-so-sequential numbers. I do not know enough about embedded CLR to see if set operation's (select, update, delete, insert) calling context is reachable from the CLR side.

At the end of the day, the following query

```<code>select dbo.GetNextNumber() from sysobjects
</code>```

must return the result

```<code>1
2
3
4
5
</code>```

It is OK if another function call to reset the context is necessary like

```<code>exec dbo.ResetSequenceNumbers()
</code>```

To prevent some misunderstandings and reduce the chances of wasting your time answering wrong question, please note that I am not looking for an ID generation function for a table and I am aware of some hacks (albeit using a proc not a function) that involves some temp tables with identity columns. The ROW_NUMBER() function is close but it also does not cut.

Thanks a lot for any responses

Kemal

P.S. It is amazing that SQL Server does have a built-in function for that. A function (provided that it cannot be used in joins and where clauses) is really easy to do and extremely useful, but for some reason it is not included.

答:
SQL Server Denali has a new sequence structure for developers
It is easy to manage and maintain sequence numbers in SQL Server after Denali
You can find details in Sequence Numbers in SQL Server

For other versions than Denali, you can use Sequence Tables.
Here is a sample for Sequence Table in SQL Server
For reading sequence number from sequence table, you should insert dummy records from this auto identity enabled sql table

Body:
I would like to have a SQL Server function dbo.GetNextNumber(), which would generate sequential numbers for each call. As far as I understand this is impossible with a native T-SQL function as SQL Server insists the functions has to be deterministic. But, if you could show me a native T-SQL function that does this would really make my day.

I thought perhaps this could be possible to write using a CLR function. As CLR functions are static, the sequence numbers need to be stored in the calling context of the set operation, as storing it as a static variable would result in several connections using the same sequence, resulting in not-so-sequential numbers. I do not know enough about embedded CLR to see if set operation's (select, update, delete, insert) calling context is reachable from the CLR side.

At the end of the day, the following query

select dbo.GetNextNumber() from sysobjects

must return the result

1
2
3
4
5

It is OK if another function call to reset the context is necessary like

exec dbo.ResetSequenceNumbers()

To prevent some misunderstandings and reduce the chances of wasting your time answering wrong question, please note that I am not looking for an ID generation function for a table and I am aware of some hacks (albeit using a proc not a function) that involves some temp tables with identity columns. The ROW_NUMBER() function is close but it also does not cut.

Thanks a lot for any responses

Kemal

P.S. It is amazing that SQL Server does have a built-in function for that. A function (provided that it cannot be used in joins and where clauses) is really easy to do and extremely useful, but for some reason it is not included.


问:
What is the difference between Greedy-Search and Uniform-Cost-Search?
When searching in a tree, my understanding of uniform cost search is that for a given node A, having child nodes B,C,D with associated costs of (10, 5, 7), my algorithm will choose C, as it has a lower cost. After expanding C, I see nodes E, F, G with costs of (40, 50, 60). It will choose 40, as it has the minimum value from both 3.

Now, isn't it just the same as doing a Greedy-Search, where you always choose what seems to be the best action?

Also, when defining costs from going from certain nodes to others, should we consider the whole cost from the beginning of the tree to the current node, or just the cost itself from going from node n to node n'?

Thanks

答:
Greedy search (for most of this answer, think of greedy best-first search when I say greedy search) is an informed search algorithm, which means the function that is evaluated to choose which node to expand has the form of f(n) = h(n), where h is the heuristic function for a given node n that returns the estimated value from this node n to a goal state. If you're trying to travel to a place, one example of a heuristic function is one that returns the estimated distance from node n to your destination.

Uniform-cost search, on the other hand, is an uninformed search algorithm, also known as a blind search strategy. This means that the value of the function f for a given node n, f(n), for uninformed search algorithms, takes into consideration g(n), the total action cost from the root node to the node n, that is, the path cost. It doesn't have any information about the problem apart from the problem description, so that's all it can know. You don't have any information that can help you decide how close one node is to a goal state, only to the root node. You can watch the nodes expanding here (Animation of the Uniform Cost Algorithm) and see how the cost from node n to the root is used to choose which nodes to expand.

Greedy search, just like any greedy algorithm, takes locally optimal solutions and uses a function that returns an estimated value from a given node n to the goal state. You can watch the nodes expanding here (Greedy Best First Search | Quick Explanation with Visualization) and see how the return of the heuristic function from node n to the goal state is used to choose which nodes to expand.

By the way, sometimes, the path chosen by greedy search is not a global optimum. In the example in the video, for example, node A is never expanded because there are always nodes with smaller values of h(n). But what if A has such a high value, and the values for the next nodes are very small and therefore a global optimum? That can happen. A bad heuristic function can cause this. Getting stuck in a loop is also possible. A*, which is also a greedy search algorithm, fixes this by making use of both the path cost (which implies knowing nodes already visited) and a heuristic function, that is, f(n) = g(n) + h(n).

It's possible that to this point, it's still not clear to you HOW uniform-cost knows there is another path that looks better locally but not globally. It should become clear after telling you that if all paths have the same cost, uniform cost search is the same thing as the breadth-first search (BFS). It would expand all nodes just like BFS.

ContentLicense: CC BY-SA 2.5