问:
How to take the hash of ELF binary in linux kernel?
I am implementing binary attestation from inside the kernel. I am reading the file using the kernel_read_from_file() function. The function definition is as follows:

```<code>int kernel_read_file_from_path(const char *path, void **buf, loff_t *size,
               loff_t max_size, enum kernel_read_file_id id)
</code>```

The function is storing the file content in buf. The code is working fine when I read files with .c or .h extension. But for ELF binaries:

```<code>Value stored in buf = ELF
</code>```

What am I missing here? How can I read ELF binary from inside the kernel?

Here's the relevant code:

#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/file.h>
// #include "sha256.h"

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Robert W. Oliver II");
MODULE_DESCRIPTION("A simple example Linux module.");
MODULE_VERSION("0.01");

static int __init lkm_example_init(void)
{
  void *data;
  loff_t size;
  int ret;
  char path1[50] = "/etc/bash.bashrc";
    char path2[50] = "/bin/sh";

  ret = kernel_read_file_from_path(path1, &data, &size, 0, READING_POLICY);
  printk(KERN_INFO "Hello, World!\n");
  printk(KERN_INFO "%lld\n", size);
  printk(KERN_INFO "%s", (char*)data);

  ret = kernel_read_file_from_path(path2, &data, &size, 0, READING_POLICY);
  printk(KERN_INFO "%lld\n", size);
  printk(KERN_INFO "%s", (char*)data);
  // vfree(data);
  return 0;
}
static void __exit lkm_example_exit(void)
{
  printk(KERN_INFO "Goodbye, World!\n");
}
module_init(lkm_example_init);
module_exit(lkm_example_exit);
```
<p>And here's the Makefile:</p>
```# Save file as read_elf.c
obj-m += read_elf.o
# This line tells makefile that the given object files are part of module

all:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
```

答:
What am I missing here? How can I read ELF binary from inside the kernel?

You are missing the fact that an ELF file is not a text file, it's a binary file. However, you are trying to print it as a string (%s specifier in printk), which will only print the first few characters and stop at the first zero byte (\0) thinking it's the string terminator.

As it turns out, as @Tsyvarev notes in the comments above, ELF files always start with the bytes 7f 45 4c 46, which in ASCII are ELF (that first byte 7f is not printable). That's what you see in your buffer after reading.

If you take a look at size after reading you will indeed see that it's bigger than 4, meaning the file was correctly read. Though you might still want to check for errors and also make sure you read the entire file.

Body:
I am implementing binary attestation from inside the kernel. I am reading the file using the kernel_read_from_file() function. The function definition is as follows:

int kernel_read_file_from_path(const char *path, void **buf, loff_t *size,
               loff_t max_size, enum kernel_read_file_id id)

The function is storing the file content in buf. The code is working fine when I read files with .c or .h extension. But for ELF binaries:

Value stored in buf = ELF

What am I missing here? How can I read ELF binary from inside the kernel?

Here's the relevant code:

#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/file.h>
// #include "sha256.h"

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Robert W. Oliver II");
MODULE_DESCRIPTION("A simple example Linux module.");
MODULE_VERSION("0.01");

static int __init lkm_example_init(void)
{
  void *data;
  loff_t size;
  int ret;
  char path1[50] = "/etc/bash.bashrc";
    char path2[50] = "/bin/sh";

  ret = kernel_read_file_from_path(path1, &data, &size, 0, READING_POLICY);
  printk(KERN_INFO "Hello, World!\n");
  printk(KERN_INFO "%lld\n", size);
  printk(KERN_INFO "%s", (char*)data);

  ret = kernel_read_file_from_path(path2, &data, &size, 0, READING_POLICY);
  printk(KERN_INFO "%lld\n", size);
  printk(KERN_INFO "%s", (char*)data);
  // vfree(data);
  return 0;
}
static void __exit lkm_example_exit(void)
{
  printk(KERN_INFO "Goodbye, World!\n");
}
module_init(lkm_example_init);
module_exit(lkm_example_exit);

And here's the Makefile:

# Save file as read_elf.c
obj-m += read_elf.o
# This line tells makefile that the given object files are part of module

all:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean


来源: stackexchange

问:
Discord.py | Command That Randomly Gives Role
I am trying to make a command that rarely gives a role (with a cooldown). However, when I try to run my code, it does not work, can anyone help to improve my code?

```<code>import discord
from discord.ext import commands
from discord.utils import get
import random

bot = commands.Bot(command_prefix=">")

...

@bot.event
async def on_command_error(ctx, error):
    if isinstance(error,commands.CommandOnCooldown):
        msg = 'wait for a while {:.2f}s'.format(error.retry_after)
        await ctx.send(msg)

@bot.command(pass_context=True)
@commands.cooldown(1, 86400, commands.BucketType.user)
@commands.has_role("Mod")
async def addrole(ctx):
    if random.randint(1, 10000) < 2:
        member = ctx.message.author
        role = get(member.server.roles, name="Mod")
        await bot.add_roles(member, role)

    else:
        await bot.channel.send("you did not get mod")

bot.run(TOKEN HERE)
</code>```

I am trying to make it a 0.01% chance of them getting the role. Thanks!

答:
I recommend using the role id instead of the role name. That way, if the name of the role changes, your code still functions. I've added comments below in my answer for you.</p>
```<code>@bot.command(pass_context=True)
@commands.cooldown(1, 86400, commands.BucketType.user)
@commands.has_role("Mod")
async def addrole(ctx):
    if random.randint(1, 10000) < 2:
        member = ctx.message.author
        role = ctx.guild.get_role(#the role id as an int) ###get the mod role from the server using the role id#
        await member.add_roles(role)
        await ctx.send("WINNER WINNER CHICKEN DINNER!") ###you're using ctx so passing the context is sufficient here

    else:
        await ctx.send("you did not get mod") ##you're using ctx so passing the context is sufficient here
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to make a command that rarely gives a role (with a cooldown). However, when I try to run my code, it does not work, can anyone help to improve my code?

import discord
from discord.ext import commands
from discord.utils import get
import random

bot = commands.Bot(command_prefix=">")

...

@bot.event
async def on_command_error(ctx, error):
    if isinstance(error,commands.CommandOnCooldown):
        msg = 'wait for a while {:.2f}s'.format(error.retry_after)
        await ctx.send(msg)

@bot.command(pass_context=True)
@commands.cooldown(1, 86400, commands.BucketType.user)
@commands.has_role("Mod")
async def addrole(ctx):
    if random.randint(1, 10000) < 2:
        member = ctx.message.author
        role = get(member.server.roles, name="Mod")
        await bot.add_roles(member, role)

    else:
        await bot.channel.send("you did not get mod")

bot.run(TOKEN HERE)

I am trying to make it a 0.01% chance of them getting the role. Thanks!

Body:
I recommend using the role id instead of the role name. That way, if the name of the role changes, your code still functions. I've added comments below in my answer for you.

@bot.command(pass_context=True)
@commands.cooldown(1, 86400, commands.BucketType.user)
@commands.has_role("Mod")
async def addrole(ctx):
    if random.randint(1, 10000) < 2:
        member = ctx.message.author
        role = ctx.guild.get_role(#the role id as an int) ###get the mod role from the server using the role id#
        await member.add_roles(role)
        await ctx.send("WINNER WINNER CHICKEN DINNER!") ###you're using ctx so passing the context is sufficient here

    else:
        await ctx.send("you did not get mod") ##you're using ctx so passing the context is sufficient here


问:
Firebase auth not successful
I've been trying so make auth with firebase and all went pretty well. But at the moment i tested it, it didn't work. The problem is that the function called createUserWithEmailAndPassowrd is not successful. I think the firebase it's connected to android studio, because the analytics works perfectly. Could you give me a hand please?

Here is the code:

```<code>package com.example.authtest

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.ktx.Firebase

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val etEmail = findViewById<EditText>(R.id.EmailEt)
        val etPwd = findViewById<EditText>(R.id.PasswordEt)
        val registerBtn = findViewById<Button>(R.id.RegisterBtn)
        val logInBtn = findViewById<Button>(R.id.LogInBtn)
        val tvMessage = findViewById<TextView>(R.id.MessageTv)

        val auth = FirebaseAuth.getInstance()

        registerBtn.setOnClickListener {
            if (etEmail.text.isNotEmpty() && etPwd.text.isNotEmpty()) {
                auth.createUserWithEmailAndPassword(etEmail.toString(),etPwd.toString()).addOnCompleteListener {
                    if (it.isSuccessful) {
                        tvMessage.text = "Registered as: " + it.result?.user?.email ?: ""
                    } else {
                        tvMessage.text = "Error registering your account!"
                    }
                }
            }
        }

        logInBtn.setOnClickListener {
            if (etEmail.text.isNotEmpty() && etPwd.text.isNotEmpty()) {
                auth.signInWithEmailAndPassword(etEmail.toString(),etPwd.toString()).addOnCompleteListener {
                    if (it.isSuccessful) {
                        tvMessage.text = "Logged in as: " + it.result?.user?.email ?: ""
                    } else {
                        tvMessage.text = "Incorrect username/password!"
                    }
                }
            }
        }
    }
}
</code>```

Thanks in advance!

答:
Try posting the code where you have defined the function.

----OR-----

The function in my code is defined like this:

```<code>        loginButton.setOnClickListener{
            val emailID:String=loginEmail.text.toString().trim{it <=' '}
            val pass:String=loginPassword.text.toString().trim{it <=' '}
             when{
                 TextUtils.isEmpty(emailID)->{
                     Toast.makeText(this@Login,"Enter Email ID! ", LENGTH_SHORT).show()
                 }

                 TextUtils.isEmpty(pass)-> {
                     Toast.makeText(this@Login, "Enter Password! ", LENGTH_SHORT).show()
                 }

                 else->{
                     FirebaseAuth.getInstance().signInWithEmailAndPassword(emailID,pass).addOnCompleteListener{ task->

                         if(task.isSuccessful){

                             //Store user id in a variable to pass on main activity:
                             val firebaseUser: FirebaseUser = task.result!!.user!!

                             Toast.makeText(this@Login,"Logged In Successfully" ,LENGTH_SHORT).show()

                             val intent = Intent(this@Login,MainActivity::class.java)
                             intent.flags= Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
                             intent.putExtra("user_id",firebaseUser)
                             intent.putExtra("email_id",emailID)
                             startActivity(intent)
                             finish()

                         }else{
                             Toast.makeText(this@Login,task.exception!!.message.toString(),
                                 LENGTH_SHORT).show()
                         }
                     }
                 }
             }

        }
</code>```

OR checkout this repo. It has login, register functions defined, which work perfectly.

Title: Firebase auth not successful

Body:
I've been trying so make auth with firebase and all went pretty well. But at the moment i tested it, it didn't work. The problem is that the function called createUserWithEmailAndPassowrd is not successful. I think the firebase it's connected to android studio, because the analytics works perfectly. Could you give me a hand please?

Here is the code:

package com.example.authtest

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.ktx.Firebase

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val etEmail = findViewById<EditText>(R.id.EmailEt)
        val etPwd = findViewById<EditText>(R.id.PasswordEt)
        val registerBtn = findViewById<Button>(R.id.RegisterBtn)
        val logInBtn = findViewById<Button>(R.id.LogInBtn)
        val tvMessage = findViewById<TextView>(R.id.MessageTv)

        val auth = FirebaseAuth.getInstance()

        registerBtn.setOnClickListener {
            if (etEmail.text.isNotEmpty() && etPwd.text.isNotEmpty()) {
                auth.createUserWithEmailAndPassword(etEmail.toString(),etPwd.toString()).addOnCompleteListener {
                    if (it.isSuccessful) {
                        tvMessage.text = "Registered as: " + it.result?.user?.email ?: ""
                    } else {
                        tvMessage.text = "Error registering your account!"
                    }
                }
            }
        }

        logInBtn.setOnClickListener {
            if (etEmail.text.isNotEmpty() && etPwd.text.isNotEmpty()) {
                auth.signInWithEmailAndPassword(etEmail.toString(),etPwd.toString()).addOnCompleteListener {
                    if (it.isSuccessful) {
                        tvMessage.text = "Logged in as: " + it.result?.user?.email ?: ""
                    } else {
                        tvMessage.text = "Incorrect username/password!"
                    }
                }
            }
        }
    }
}

Thanks in advance!

Body:
Try posting the code where you have defined the function.

----OR-----

The function in my code is defined like this:

        loginButton.setOnClickListener{
            val emailID:String=loginEmail.text.toString().trim{it <=' '}
            val pass:String=loginPassword.text.toString().trim{it <=' '}
             when{
                 TextUtils.isEmpty(emailID)->{
                     Toast.makeText(this@Login,"Enter Email ID! ", LENGTH_SHORT).show()
                 }

                 TextUtils.isEmpty(pass)-> {
                     Toast.makeText(this@Login, "Enter Password! ", LENGTH_SHORT).show()
                 }

                 else->{
                     FirebaseAuth.getInstance().signInWithEmailAndPassword(emailID,pass).addOnCompleteListener{ task->

                         if(task.isSuccessful){

                             //Store user id in a variable to pass on main activity:
                             val firebaseUser: FirebaseUser = task.result!!.user!!

                             Toast.makeText(this@Login,"Logged In Successfully" ,LENGTH_SHORT).show()

                             val intent = Intent(this@Login,MainActivity::class.java)
                             intent.flags= Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
                             intent.putExtra("user_id",firebaseUser)
                             intent.putExtra("email_id",emailID)
                             startActivity(intent)
                             finish()

                         }else{
                             Toast.makeText(this@Login,task.exception!!.message.toString(),
                                 LENGTH_SHORT).show()
                         }
                     }
                 }
             }

        }

OR checkout this repo. It has login, register functions defined, which work perfectly.


问:
mxmlc compiles differently under linux and windows?
I have a project which has several components loaded by a single preloader swf.

The preloader swf is strictly AS3 (No flex) and uses Loaders to load two different swfs which both use the flex library (Statically compiled, not rsl).

When I compile all three under linux and run the resulting preloader, one of the swfs fails to load properly, and the exception below (at the bottom of this post) is thrown.

If I compile the same component using the same ant task in windows, the component loads just fine without error. The windows file is also 683 bytes smaller.

This is true using the flex SDK 3.2.0 and 3.3.0 under linux and windows.

Have you seen this type of behavior? Can you offer any suggestions for why it might be happening, or how to determine what is wrong?

```<code>TypeError: Error #1009: Cannot access a property or method of a null object reference.
at mx.managers::FocusManager/activate()
at mx.managers::SystemManager/activateForm()
at mx.managers::SystemManager/activate()
at mx.core::Application/initManagers()
at mx.core::Application/initialize()
at OC_Footer/initialize()
at mx.managers::SystemManager/http://www.adobe.com/2006/flex/mx/internal::childAdded()
at mx.managers::SystemManager/initializeTopLevelWindow()
at mx.managers::SystemManager/http://www.adobe.com/2006/flex/mx/internal::docFrameHandler()
at mx.managers::SystemManager/docFrameListener()
</code>```

答:
I'm not sure I've solved the real problem (Why the compilation was different under different OS's), but I have found that the newer version of the flex SDK does not exhibit the same issues.

I created a bug for the issue here:

https://bugs.adobe.com/jira/browse/SDK-20147

The short of it is, build 3958 (The one default with flexbuilder at the time that I created the bug -- This may still be true)  appears to have a number of minor bugs. Upgrading the flex SDK to build 4852 alleviates the symptoms, and I can build projects successfully in a number of environments.

OwnerDisplayName: Aaron H.

ContentLicense: CC BY-SA 2.5

Body:
I have a project which has several components loaded by a single preloader swf.

The preloader swf is strictly AS3 (No flex) and uses Loaders to load two different swfs which both use the flex library (Statically compiled, not rsl).

When I compile all three under linux and run the resulting preloader, one of the swfs fails to load properly, and the exception below (at the bottom of this post) is thrown.

If I compile the same component using the same ant task in windows, the component loads just fine without error. The windows file is also 683 bytes smaller.

This is true using the flex SDK 3.2.0 and 3.3.0 under linux and windows.

Have you seen this type of behavior? Can you offer any suggestions for why it might be happening, or how to determine what is wrong?

TypeError: Error #1009: Cannot access a property or method of a null object reference.
at mx.managers::FocusManager/activate()
at mx.managers::SystemManager/activateForm()
at mx.managers::SystemManager/activate()
at mx.core::Application/initManagers()
at mx.core::Application/initialize()
at OC_Footer/initialize()
at mx.managers::SystemManager/http://www.adobe.com/2006/flex/mx/internal::childAdded()
at mx.managers::SystemManager/initializeTopLevelWindow()
at mx.managers::SystemManager/http://www.adobe.com/2006/flex/mx/internal::docFrameHandler()
at mx.managers::SystemManager/docFrameListener()

LastEditorDisplayName: Aaron H.


问:
SqlAlchemy Oracle DataTime format
I use SqlAlchemy to query an Oracle database and store results in csv files.

I would like to specify a global format for dates to be written like this :

```<code>'DD-MM-YYYY HH24:MI:SS'.
</code>```

I have set NLS_DATE_FORMAT this way on the system.

For exemple :

```<code>datetime.datetime(2016, 12, 22, 13, 12, 35)
</code>```

Would end up :

```<code>2004-12-22 13:12:35
</code>```

I would like :

```<code>22-12-2004 13:12:35
</code>```

As I process hundreds of tables, I cannot apply 'strftime' "manually".

答:
maybe I have the similar purpose as you.

I just want print(row) has formatted datetime,

rather than datatime.datetime(y,m,d.. things.

I have tried several ways (about handle datetime):

sql level convert use func date_format // sql dialects related

SELECT *, date_format(last_login, '%m-%d-%Y') FROM devices;

// func.date_format, func.to_char

convert RowProxy to normal dict //different access style

a custom JSON.encoder //only for json stringify

https://stackoverflow.com/a/22238613/4896468

inherit RowProxy //less invasive I think

just explain the inherit way here:

① the result

orig row

```<code>>>> type(row)
<class 'aiomysql.sa.result.RowProxy'>

>>> row
(4982, '203233D81914', False, datetime.datetime(2021, 6, 28, 19, 30, 6))

>>> row.last_login
datetime.datetime(2021, 6, 28, 19, 30, 6)
</code>```

my row

```<code>>>> my_row = my_proxy(row)
>>> my_row
(4982, '203233D81914', False, '2021-06-28 19:30:06')

>>> my_row.last_login
'2021-06-28 19:30:06'
</code>```

② the code

inherit RowProxy, and override (any of them on demand)

__repr__ (for print)

__getattr__ (for .xxx fileds access)

from datetime import datetime

class my_proxy(proxy_type):
  # refer orig RowProxy implement
  def __init__(self, row):
    self._result_proxy = row._result_proxy
    self._row = row._row
    self._processors = row._processors
    self._keymap = row._keymap
  # for print
  def __repr__(self):
    # return ' xx:'+ repr(self.as_tuple())
    return repr(tuple(v.strftime('%F %T') if type(v)==datetime else v for v in self.as_tuple()))
  # for field access
  def __getattr__(self, name):
    try:
      # return self[name]
      v = self[name]
      return v.strftime('%F %T') if type(v)==datetime else v
    except KeyError as e:
      raise AttributeError(e.args[0])

```

proxy_type = type(row)

which is aiomysql.sa.result.RowProxy

code based on

aiomysql               0.0.22

SQLAlchemy             1.4.31

especially the __init__ function:

　github:aiomysql/sa/result.py#L22

different version may differ.

ContentLicense: CC BY-SA 3.0

Title: SqlAlchemy Oracle DataTime format

Body:
I use SqlAlchemy to query an Oracle database and store results in csv files.

I would like to specify a global format for dates to be written like this :

'DD-MM-YYYY HH24:MI:SS'.

I have set NLS_DATE_FORMAT this way on the system.

For exemple :

datetime.datetime(2016, 12, 22, 13, 12, 35)

Would end up :

2004-12-22 13:12:35

I would like :

22-12-2004 13:12:35

As I process hundreds of tables, I cannot apply 'strftime' "manually".

Body:
maybe I have the similar purpose as you.

I just want print(row) has formatted datetime,

rather than datatime.datetime(y,m,d.. things.

I have tried several ways (about handle datetime):

sql level convert use func date_format // sql dialects related

SELECT *, date_format(last_login, '%m-%d-%Y') FROM devices;

// func.date_format, func.to_char

convert RowProxy to normal dict //different access style

a custom JSON.encoder //only for json stringify

https://stackoverflow.com/a/22238613/4896468

inherit RowProxy //less invasive I think

just explain the inherit way here:

① the result

orig row

>>> type(row)
<class 'aiomysql.sa.result.RowProxy'>

>>> row
(4982, '203233D81914', False, datetime.datetime(2021, 6, 28, 19, 30, 6))

>>> row.last_login
datetime.datetime(2021, 6, 28, 19, 30, 6)

my row

>>> my_row = my_proxy(row)
>>> my_row
(4982, '203233D81914', False, '2021-06-28 19:30:06')

>>> my_row.last_login
'2021-06-28 19:30:06'

② the code

inherit RowProxy, and override (any of them on demand)

__repr__ (for print)

__getattr__ (for .xxx fileds access)

from datetime import datetime

class my_proxy(proxy_type):
  # refer orig RowProxy implement
  def __init__(self, row):
    self._result_proxy = row._result_proxy
    self._row = row._row
    self._processors = row._processors
    self._keymap = row._keymap
  # for print
  def __repr__(self):
    # return ' xx:'+ repr(self.as_tuple())
    return repr(tuple(v.strftime('%F %T') if type(v)==datetime else v for v in self.as_tuple()))
  # for field access
  def __getattr__(self, name):
    try:
      # return self[name]
      v = self[name]
      return v.strftime('%F %T') if type(v)==datetime else v
    except KeyError as e:
      raise AttributeError(e.args[0])

proxy_type = type(row)

which is aiomysql.sa.result.RowProxy

code based on

aiomysql               0.0.22

SQLAlchemy             1.4.31

especially the __init__ function:

　github:aiomysql/sa/result.py#L22

different version may differ.


问:
URL redirects to public/public if using www
If I go to website.com then my website works correctly.

If I go to www.website.com then I get redirected to www.website.com/public/public which 404s.

If I then go to www.website.com/public it works correctly (but I don't want the added /public)

I want it so that both website.com and www.website.com use the same page.
without any publics added/needed in the URL.
Here is the .htaccess which is in the root laravel folder (inside public_html)

```<code><IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On
    RewriteCond %{REQUEST_URI} !^/public/
    RewriteRule ^(.*)$ public/$1 [L]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ / [L,R=301]
    #RewriteBase /laravel/

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

</IfModule>
AddType x-httpd-php72 .php
</code>```

The reason I'm using the rewrite rules are so that I can access assets without using /public e.g /public/css/app.css is /css/app.css

答: I fixed it. The issue was my env had http://website.com rather than http://www.website.com.</p>

Body:
If I go to website.com then my website works correctly.

If I go to www.website.com then I get redirected to www.website.com/public/public which 404s.

If I then go to www.website.com/public it works correctly (but I don't want the added /public)

I want it so that both website.com and www.website.com use the same page.
without any publics added/needed in the URL.
Here is the .htaccess which is in the root laravel folder (inside public_html)

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On
    RewriteCond %{REQUEST_URI} !^/public/
    RewriteRule ^(.*)$ public/$1 [L]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ / [L,R=301]
    #RewriteBase /laravel/

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

</IfModule>
AddType x-httpd-php72 .php

The reason I'm using the rewrite rules are so that I can access assets without using /public e.g /public/css/app.css is /css/app.css


问:
How to replace text between multiple tags based on character length
I am dealing with dirty text data (and not with valid html). I am doing natural language processing and short code snippets shouldn't be removed because they can contain valuable information while long code snippets don't.

Thats why I would like to remove text between code tags only if the content that will be removed has character length > n.

Let's say the number of allowed characters between two code tags is n <= 5. Then everything between those tags that is longer than 5 characters will be removed.

My approach so far deletes all of the code characters:

```<code>text = "This is a string <code>1234</code> another string <code>123</code> another string <code>123456789</code> another string."
text = re.sub("<code>.*?</code>", '', text)
print(text)

Output: This is a string  another string  another string  another string.
</code>```

The desired output:

```<code>"This is a string <code>1234</code> another string <code>123</code> another string another string."
</code>```

Is there a way to count the text length for all of the appearing <code ...  tags before it will actually be removed?

答:
In Python, BeautifulSoup is often used to manipulate HTML/XML contents. If you use this library, you can use something like

from bs4 import BeautifulSoup
soup = BeautifulSoup(content,"html.parser")
text = "This is a string 1234 another string 123 another string 123456789 another string."
soup = BeautifulSoup(text,"html.parser")
for code in soup.find_all("code"):
    if len(code.encode_contents()) > 5: # Check the inner HTML length
        code.extract()                  # Remove the node found

print(str(soup))
# => This is a string 1234 another string 123 another string  another string.
```
<p>Note that here, the length of the inner HTML part is taken into account, not the inner <em>text</em>.</p>
<p>With regex, you can use a negated character class pattern, <code>[^<]</code>, to match any char other than <code><</code>, and apply a limiting quantifier to it. If all longer than 5 chars should be removed, use <code>{6,}</code> quantifier:</p>
<pre class="lang-py prettyprint-override"><code>import re
text = "This is a string <code>1234</code> another string <code>123</code> another string <code>123456789</code> another string."
text = re.sub(r'<code>[^>]{6,}</code>', '', text)
print(text)
# => This is a string <code>1234</code> another string <code>123</code> another string  another string.
</code>```

See this Python demo.

Body:
I am dealing with dirty text data (and not with valid html). I am doing natural language processing and short code snippets shouldn't be removed because they can contain valuable information while long code snippets don't.

Thats why I would like to remove text between code tags only if the content that will be removed has character length > n.

Let's say the number of allowed characters between two code tags is n <= 5. Then everything between those tags that is longer than 5 characters will be removed.

My approach so far deletes all of the code characters:

text = "This is a string 1234 another string 123 another string 123456789 another string."
text = re.sub(".*?", '', text)
print(text)

Output: This is a string  another string  another string  another string.

The desired output:

"This is a string 1234 another string 123 another string another string."

Is there a way to count the text length for all of the appearing <code ...  tags before it will actually be removed?

Body:
In Python, BeautifulSoup is often used to manipulate HTML/XML contents. If you use this library, you can use something like

from bs4 import BeautifulSoup
soup = BeautifulSoup(content,"html.parser")
text = "This is a string <code>1234</code> another string <code>123</code> another string <code>123456789</code> another string."
soup = BeautifulSoup(text,"html.parser")
for code in soup.find_all("code"):
    if len(code.encode_contents()) > 5: # Check the inner HTML length
        code.extract()                  # Remove the node found

print(str(soup))
# => This is a string <code>1234</code> another string <code>123</code> another string  another string.

Note that here, the length of the inner HTML part is taken into account, not the inner text.

With regex, you can use a negated character class pattern, [^<], to match any char other than <, and apply a limiting quantifier to it. If all longer than 5 chars should be removed, use {6,} quantifier:

import re
text = "This is a string <code>1234</code> another string <code>123</code> another string <code>123456789</code> another string."
text = re.sub(r'<code>[^>]{6,}</code>', '', text)
print(text)
# => This is a string <code>1234</code> another string <code>123</code> another string  another string.

See this Python demo.


问:
How to change the color of a button?
I'm new to android programming. How do I change the color of a button?</p>

```<code><Button
    android:id="@+id/btn"
    android:layout_width="55dp"
    android:layout_height="50dp"
    android:layout_gravity="center"
    android:text="Button Text"
    android:paddingBottom="20dp"/>
</code>```

答:
Button background color in xml

```<code><Button
    android:id="@+id/button"
    android:background="#0000FF"
    android:textColor="#FFFFFF"/>
</code>```

Change button background color programmatically

```<code>Button button = findViewById(R.id.button);
button.setBackgroundColor(Color.BLUE);
</code>```

Custom button background

shape.xml   [res --> drawble]

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="5dp" />
    <gradient
        android:angle="0"
        android:endColor="#0000FF"
        android:startColor="#00FFFF" />
    <stroke
        android:width="1dp"
        android:color="#000000" />
</shape>
</code>```

Add this line

```<code>android:background="@drawable/shape"
</code>```

full code

```<code><Button
    android:id="@+id/button"
    android:background="@drawable/shape"
    android:textColor="#FFFFFF"/>
</code>```

Material Design Button

Change button background color

```<code>app:backgroundTint="#0000FF"
</code>```

Button Stroke color

```<code>app:strokeColor="#000000"
</code>```

Button Stroke width

```<code>app:strokeWidth="2dp"
</code>```

Full code

```<code><Button
    android:id="@+id/button"
    android:textColor="#FFFFFF"
    app:backgroundTint="#0000FF"
    app:strokeColor="#000000"
    app:strokeWidth="2dp"/>
</code>```

Hope you helpful!

Title: How to change the color of a button?

Body:
I'm new to android programming. How do I change the color of a button?

<Button
    android:id="@+id/btn"
    android:layout_width="55dp"
    android:layout_height="50dp"
    android:layout_gravity="center"
    android:text="Button Text"
    android:paddingBottom="20dp"/>

Body:
Button background color in xml

<Button
    android:id="@+id/button"
    android:background="#0000FF"
    android:textColor="#FFFFFF"/>

Change button background color programmatically

Button button = findViewById(R.id.button);
button.setBackgroundColor(Color.BLUE);

Custom button background

shape.xml   [res --> drawble]

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="5dp" />
    <gradient
        android:angle="0"
        android:endColor="#0000FF"
        android:startColor="#00FFFF" />
    <stroke
        android:width="1dp"
        android:color="#000000" />
</shape>

Add this line

android:background="@drawable/shape"

full code

<Button
    android:id="@+id/button"
    android:background="@drawable/shape"
    android:textColor="#FFFFFF"/>

Material Design Button

Change button background color

app:backgroundTint="#0000FF"

Button Stroke color

app:strokeColor="#000000"

Button Stroke width

app:strokeWidth="2dp"

Full code

<Button
    android:id="@+id/button"
    android:textColor="#FFFFFF"
    app:backgroundTint="#0000FF"
    app:strokeColor="#000000"
    app:strokeWidth="2dp"/>

Hope you helpful!


问:
LIKE with multiple character conditions using percentage
I've got a query that returns the name of a country, where the name must include all of the vowels (a,e,i,o,u).

I'd like to transform this:

```<code>SELECT name FROM world
WHERE name LIKE '%a%'
AND name LIKE '%e%'
AND name LIKE '%i%'
AND name LIKE '%o%'
AND name LIKE '%u%'
</code>```

into a 2 line query. I tried this, but it didn't work:

```<code>SELECT name FROM world
WHERE name LIKE '%a%e%i%o%u%'
</code>```

I though %a%e%i%o%u% should've done it, but I guess I haven't fully grasped the concept yet.

答:
SELECT name FROM world
WHERE name LIKE '%a%' AND
name  LIKE '%e%' AND
name  LIKE '%i%' AND
name  LIKE '%o%' AND
name  LIKE '%u%' AND
name NOT LIKE '% %'</p>

Body:
I've got a query that returns the name of a country, where the name must include all of the vowels (a,e,i,o,u).

I'd like to transform this:

SELECT name FROM world
WHERE name LIKE '%a%'
AND name LIKE '%e%'
AND name LIKE '%i%'
AND name LIKE '%o%'
AND name LIKE '%u%'

into a 2 line query. I tried this, but it didn't work:

SELECT name FROM world
WHERE name LIKE '%a%e%i%o%u%'

I though %a%e%i%o%u% should've done it, but I guess I haven't fully grasped the concept yet.


问:
igraph, Python - directed girth seems to not work
I'm working with randomly generated digraphs. I need to verify that the graphs I have have a girth of at least, say 3.

The solution I used is the following:

I generate a random adjacency matrix

I create an igraph.Graph instance from the matrix

I call .girth() method to check the girth is correct.

If correct, I keep my process; otherwise I return to step 1.

However; sometimes I have graphs that definitly should not pass the girth check but they do. For instance: Graph with girth 2.
have an girth 2: there are two pairs of vertices (a,b) with a,b, and b,a in the arcs.

My theory is that igraph do not understand these pair of vertices as a proper cycle; if that is the case how do I fix this?

For the record: here how goes my random generation:

```<code>M = np.zeros((n,n))
    for i in range(n):
        pick_list = [j for j in range(n) if j!=i]
        x = random.sample(pick_list, outdegree)
        for j in x:
            M[i][j] = 1
</code>```

答:
So apparently the .girth() does not work properly for digraph.
I did this to solve my problem:

```<code>    D_k = copy.deepcopy(D)

    for k in range(2, girth):
        D_k = D_k.dot(D)
        if sum([D_k[i][i] for i in range(n)]) != 0: # equivalent to: trace of D_k
            return False
    return True
</code>```

A bad solution but at least it is correct.

Body:
I'm working with randomly generated digraphs. I need to verify that the graphs I have have a girth of at least, say 3.

The solution I used is the following:

I generate a random adjacency matrix

I create an igraph.Graph instance from the matrix

I call .girth() method to check the girth is correct.

If correct, I keep my process; otherwise I return to step 1.

However; sometimes I have graphs that definitly should not pass the girth check but they do. For instance: Graph with girth 2.
have an girth 2: there are two pairs of vertices (a,b) with a,b, and b,a in the arcs.

My theory is that igraph do not understand these pair of vertices as a proper cycle; if that is the case how do I fix this?

For the record: here how goes my random generation:

M = np.zeros((n,n))
    for i in range(n):
        pick_list = [j for j in range(n) if j!=i]
        x = random.sample(pick_list, outdegree)
        for j in x:
            M[i][j] = 1

Body:
So apparently the .girth() does not work properly for digraph.
I did this to solve my problem:

    D_k = copy.deepcopy(D)

    for k in range(2, girth):
        D_k = D_k.dot(D)
        if sum([D_k[i][i] for i in range(n)]) != 0: # equivalent to: trace of D_k
            return False
    return True

A bad solution but at least it is correct.


问:
Why we need IEnumerable<string> before get method?
I just started learning web API using ASP.NET. I created a new project from visual studio and trying to understand MVC folder structure and API calls.

Here what I want to know is: why do we need IEnumerable<string> before the get method.

In myValuesController.cs,

```<code>        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }
</code>```

According to the Microsoft Documentation, this exposes the enumerator, which supports a simple iteration over a collection of a specified type but think if I have an integer in my database do I need to convert it into string as well?

答: If your GET-endpoint should return a collection of numbers instead of a single number, you surely need to return some kind of list, be it IEnumerable or List or whatever.</p>

Body:
I just started learning web API using ASP.NET. I created a new project from visual studio and trying to understand MVC folder structure and API calls.

Here what I want to know is: why do we need IEnumerable<string> before the get method.

In myValuesController.cs,

        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

According to the Microsoft Documentation, this exposes the enumerator, which supports a simple iteration over a collection of a specified type but think if I have an integer in my database do I need to convert it into string as well?


问:
How to exclude logging an Guzzle's 404 error in Laravel?
I use the Laravel framework. When I get an exception GuzzleHttp\\Exception\\ClientException(code: 404), this event is added to laravel.log. How can I disable adding the event about that error to laravel.log?

答:
You can remove it from the exceptions handler file according to the docs, if can be found in your App\Exceptions\Handler so for example:-

use GuzzleHttp\Exception\ClientException; // here, import the target class
...
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* @var string[]
*/
protected $dontReport = [
        ClientException::class, // here, add the class to the don't report list
];

...
}
```
<p>to manipulate a custom error condition, you can register it in the register method in the Handler file like:-</p>
<pre class="lang-php prettyprint-override"><code>**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        // check if the ClientExeption is a 404
        $this->reportable(function (ClientException $e) {
            if ($e->getCode() == 404) {
                return false; // or anything else for that matter
            }
        });
    }
</code>```

Body:
You can remove it from the exceptions handler file according to the docs, if can be found in your App\Exceptions\Handler so for example:-

use GuzzleHttp\Exception\ClientException; // here, import the target class
...
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* @var string[]
*/
protected $dontReport = [
        ClientException::class, // here, add the class to the don't report list
];

...
}

to manipulate a custom error condition, you can register it in the register method in the Handler file like:-

**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        // check if the ClientExeption is a 404
        $this->reportable(function (ClientException $e) {
            if ($e->getCode() == 404) {
                return false; // or anything else for that matter
            }
        });
    }


问:
In Haxe, how do I check for a key that's been pressed twice?
I've searched on Google for an answer, but I couldn't find anything that helped me. Basically, I want a function that activates when you press the R button twice.</p>

答: You could store pressed key and time, on next press check if it same and not long time pass activate, otherwise update last pressed key and time</p>


问:
Set master branch to latest tag
This is an example of how my git repo is right now:

```<code>v1.0    v1.1    v1.2
  |       |       |
  a   -   b   -   c
  |               |
master           HEAD
</code>```

I usually commit, tag and push tags like this:

```<code>git commit -a -m "Commit msg"
git tag -a v1.3 -m "Tag msg"
git push --tags
</code>```

The main problem I have is that the master branch doesn't move to the latest tag, so I'm always in a Detached HEAD state. Is there any way to fix this so the master branch will be always pointing to the latest pushed tag?

答:
I resolved the problem like this:

git checkout -B master HEAD
git push --force origin master
```

Title: Set master branch to latest tag

Body:
This is an example of how my git repo is right now:

v1.0    v1.1    v1.2
  |       |       |
  a   -   b   -   c
  |               |
master           HEAD

I usually commit, tag and push tags like this:

git commit -a -m "Commit msg"
git tag -a v1.3 -m "Tag msg"
git push --tags

The main problem I have is that the master branch doesn't move to the latest tag, so I'm always in a Detached HEAD state. Is there any way to fix this so the master branch will be always pointing to the latest pushed tag?


问:
How can I sign an Oracle VirtualBox virtual appliance (.OVA)
I want to sign an Oracle VirtualBox Virtual Appliance, an OVA file. I am looking for instructions.

I have had extensive conversations with Comodo and Sectigo. They don't know how and had trouble even understanding the question.

When I load my VM in VirtualBox it says that it is unsigned but gives no information as to how to correct that.
I have a code signing certificate, and I have no trouble signing and timestamping an executable file:

signtool sign /t http://timestamp.comodoca.com t_hello.exe
Done Adding Additional Store
Successfully signed: t_hello.exe

Attempting with an .ova file gives an error:

signtool sign /t http://timestamp.comodoca.com ACoreTpl.ova
Done Adding Additional Store
SignTool Error: This file format cannot be signed because it is not recognized.
SignTool Error: An error occurred while attempting to sign: ACoreTpl.ova

I took a shot at downloading a tool from VMWare, but it did not work on my VirtualBox appliance. It just gave error messages.

Unless the error message is meaningless and just hardcoded in VirtualBox, there is code inspecting something. I really don't want to go fishing through the code, but at this point it seems like I might have to.

The purpose of this exercise is so that I can publish a working system as a virtual appliance that is 'known good' and can be verified as the real thing when it loads.

答:
[Note: There are images in the document I pasted this from, but they would not paste in here.]
I was able to muddle through a work-around. The workaround involves getting a tool from VMWare (ovftool.exe), which seems a bit strange. It allows the import of the OVA, showing the certificate and marking it as 'safe'. It still has a couple of issues. One is an annoying warning message issued while creating the signed file, for which I was unable to find a cure. The other is that it does not seem to contact a timeserver to timestamp the file. Presumably that means that when the signing certificate expires, you get warnings again when loading.

I would still like to know how you are supposed to do it properly according to Oracle. Surely, Oracle is not using VMWare's software to sign their Virtual Appliances.

This is my journey under Windows 10. At the end, I have a publishable appliance.

You need a virtual appliance (*.ova)

You need a signing certificate.

You need to have OpenSSL installed.

You need the program ovftool.exe from VMWare

To get the .ova file, you need to export one of your VMs as a virtual appliance:

Open the export virtual appliance dialog:

File->Export Appliance [Alternatively E]

Choose the virtual machine to export. Fill in whatever Virtual system settings apply.

For appliance settings, set the Format to Open Virtualization Format 1.0

Make sure the 'Write Manifest file' checkbox is checked.

Click on the  button to write file.

You should have the signing certificate installed in the certificate store. If you don't have this already, you need to consult your certificate provider.

To get the signing certificate in a usable form, you have to jump through a few hoops to get an old-timey Privacy Enhanced Mail (PEM) file.

You need to get the certificate into a file first.

Start the Certificate Manager by running certmgr.msc

Open Personal->Certificates and right-click on your signing certificate

Open the All tasks menu and choose Export

This should open the Certificate Export Wizard

Click [Next]

Choose the radio button marked "Yes, export the private key"

Click [Next]

Choose "Personal Information Exchange - PKCS (.PFX)"

Check "Include all certificates in the certification path if possible"

Check "Export all extended properties"

Check "Enable certificate privacy"

Click [Next]

Check the Password checkbox, and enter and confirm a password [using password "IMPPass" in this example]

Change the Encryption dropdown to AES256-SHA256

Click [Next]

Assign the filename and path for the exported certificate. In this example, I called it "MyCert". Note that you don't put the file extension on the name here. The Certificate Export Wizard adds it when it writes the file. You should save it on the path where you saved the OVA file.

Click [Next]

Review settings and Click

It should pop up a message box saying the export was successful. Dismiss it by clicking on the  button.

You need to do the next steps at the command line.

Open a console window.

Change to the directory where you have saved your OVA and PFX files.

cd c:<yoursavelocation>

You now need to convert the certificate to a form that can be used (.pem). To do this, you need to use OpenSSL. Here is the form of the command:

openssl pkcs12 -in MyCert.pfx -out MyCert.pem

Respond to the prompts for Import Password and PEM pass phrase:

```<code>Enter Import Password: IMPPass

Enter PEM pass phrase: PEMPass

Verifying - Enter PEM pass phrase: PEMPass
</code>```

Finally, you can sign the exported OVA with ovftool with a command like this:

ovftool --privateKey=MyCert.pem --shaAlgorithm=SHA1 DamnSmall.ova DSL.ova

Opening OVA source: DamnSmall.ova

Opening OVA target: DSL.ova

Writing OVA package: DSL.ova

Transfer Completed

The manifest validates

Enter passphrase for MyCert.pem: PEMPass

A warning is issued here, but it will not interfere with the signing.

Warning:

No supported manifest(sha1, sha256, sha512) entry found for: 'DamnSmall-disk001.vmdk'.
Completed successfully

At this point, there should be a signed file called DSL.ova. It will indicate that when imported in VirtualBox.

To test, import the newly created and signed OVA file. Open the import dialog:

File->Import Appliance or alternatively  I

Enter the path and name of the signed Virtual Appliance.
Click [Next]

The Appliance settings dialog should have text in the bottom left corner indicating that you have signed the appliance, and that it is trusted.

Appliance is signed

Body:
[Note: There are images in the document I pasted this from, but they would not paste in here.]
I was able to muddle through a work-around. The workaround involves getting a tool from VMWare (ovftool.exe), which seems a bit strange. It allows the import of the OVA, showing the certificate and marking it as 'safe'. It still has a couple of issues. One is an annoying warning message issued while creating the signed file, for which I was unable to find a cure. The other is that it does not seem to contact a timeserver to timestamp the file. Presumably that means that when the signing certificate expires, you get warnings again when loading.

I would still like to know how you are supposed to do it properly according to Oracle. Surely, Oracle is not using VMWare's software to sign their Virtual Appliances.

This is my journey under Windows 10. At the end, I have a publishable appliance.

You need a virtual appliance (*.ova)

You need a signing certificate.

You need to have OpenSSL installed.

You need the program ovftool.exe from VMWare

To get the .ova file, you need to export one of your VMs as a virtual appliance:

Open the export virtual appliance dialog:

File->Export Appliance [Alternatively E]

Choose the virtual machine to export. Fill in whatever Virtual system settings apply.

For appliance settings, set the Format to Open Virtualization Format 1.0

Make sure the 'Write Manifest file' checkbox is checked.

Click on the  button to write file.

You should have the signing certificate installed in the certificate store. If you don't have this already, you need to consult your certificate provider.

To get the signing certificate in a usable form, you have to jump through a few hoops to get an old-timey Privacy Enhanced Mail (PEM) file.

You need to get the certificate into a file first.

Start the Certificate Manager by running certmgr.msc

Open Personal->Certificates and right-click on your signing certificate

Open the All tasks menu and choose Export

This should open the Certificate Export Wizard

Click [Next]

Choose the radio button marked "Yes, export the private key"

Click [Next]

Choose "Personal Information Exchange - PKCS (.PFX)"

Check "Include all certificates in the certification path if possible"

Check "Export all extended properties"

Check "Enable certificate privacy"

Click [Next]

Check the Password checkbox, and enter and confirm a password [using password "IMPPass" in this example]

Change the Encryption dropdown to AES256-SHA256

Click [Next]

Assign the filename and path for the exported certificate. In this example, I called it "MyCert". Note that you don't put the file extension on the name here. The Certificate Export Wizard adds it when it writes the file. You should save it on the path where you saved the OVA file.

Click [Next]

Review settings and Click

It should pop up a message box saying the export was successful. Dismiss it by clicking on the  button.

You need to do the next steps at the command line.

Open a console window.

Change to the directory where you have saved your OVA and PFX files.

cd c:<yoursavelocation>

You now need to convert the certificate to a form that can be used (.pem). To do this, you need to use OpenSSL. Here is the form of the command:

openssl pkcs12 -in MyCert.pfx -out MyCert.pem

Respond to the prompts for Import Password and PEM pass phrase:

Enter Import Password: IMPPass

Enter PEM pass phrase: PEMPass

Verifying - Enter PEM pass phrase: PEMPass

Finally, you can sign the exported OVA with ovftool with a command like this:

ovftool --privateKey=MyCert.pem --shaAlgorithm=SHA1 DamnSmall.ova DSL.ova

Opening OVA source: DamnSmall.ova

Opening OVA target: DSL.ova

Writing OVA package: DSL.ova

Transfer Completed

The manifest validates

Enter passphrase for MyCert.pem: PEMPass

A warning is issued here, but it will not interfere with the signing.

Warning:

No supported manifest(sha1, sha256, sha512) entry found for: 'DamnSmall-disk001.vmdk'.
Completed successfully

At this point, there should be a signed file called DSL.ova. It will indicate that when imported in VirtualBox.

To test, import the newly created and signed OVA file. Open the import dialog:

File->Import Appliance or alternatively  I

Enter the path and name of the signed Virtual Appliance.
Click [Next]

The Appliance settings dialog should have text in the bottom left corner indicating that you have signed the appliance, and that it is trusted.

Appliance is signed


问:
IdentityServer4. Using 2 roles per user
I'm using IdentityServer4 and an MVC client. My problem is just being able to use more than 1 role per user. In the example below, I have 2 controllers, each with its authorize. If 1 user has 2 Roles in the register, he gives access denied to both.

When you leave only 1 role for the user, it works just fine

Config.cs (IDS4)

```<code>        public static IEnumerable<IdentityResource> Ids =>
        new IdentityResource[]
        {
            new IdentityResources.OpenId(),
            new IdentityResources.Profile(),
            new IdentityResources.Email(),
            new IdentityResources.Phone(),
            new IdentityResource("role", "role", new List<string> { "role" }),
        };

            new Client
            {
                ClientId = "mvc",
                ClientName = "MVC App",
                ClientSecrets = { new Secret("secret".Sha256()) },
                AllowedGrantTypes = GrantTypes.CodeAndClientCredentials,
                RequireConsent = false,

                RedirectUris = { mvcURL + "/signin-oidc" },
                FrontChannelLogoutUri = mvcURL + "/signout-oidc",
                PostLogoutRedirectUris = { mvcURL + "/signout-callback-oidc" },

                //AllowOfflineAccess = true,
                AllowedScopes = {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    IdentityServerConstants.StandardScopes.Email,
                    IdentityServerConstants.StandardScopes.Phone,
                    "api", "role"
                }
            },
</code>```

ProfileService.cs (IDS4)

```<code>        public async Task GetProfileDataAsync(ProfileDataRequestContext context)
    {
        var sub = context.Subject.GetSubjectId();
        var user = await _userManager.FindByIdAsync(sub);
        var principal = await _claimsFactory.CreateAsync(user);

        var claims = principal.Claims.ToList();
        claims = claims.Where(claim => context.RequestedClaimTypes.Contains(claim.Type)).ToList();

        // Add custom claims in token here based on user properties or any other source
        claims.Add(new Claim("id_user", user.Id.ToString()));
        claims.Add(new Claim("name", user.Name));
        claims.Add(new Claim("email", user.Email.ToString()));
        claims.Add(new Claim("role", user.role.ToString()));

        if (_userManager.SupportsUserRole)
        {
            var roles = await _userManager.GetRolesAsync(user);
            foreach (var roleName in roles)
            {
                claims.Add(new Claim(JwtClaimTypes.Role, roleName));

                if (_roleManager.SupportsRoleClaims)
                {
                    var role = await _roleManager.FindByNameAsync(roleName);
                    if (role != null)
                        claims.AddRange(await _roleManager.GetClaimsAsync(role));
                }
            }
        }

        context.IssuedClaims = claims;
    }
</code>```

Startup.cs (MVC)

```<code>        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;

        })
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
            {
                options.Authority = Configuration.GetSection("ids_URI").Value;
                options.ClientId = "mvc";
                options.ClientSecret = "secret";
                options.ResponseType = OpenIdConnectResponseType.Code;
                options.GetClaimsFromUserInfoEndpoint = true;
                options.Scope.Add("openid");
                options.Scope.Add("profile");
                options.Scope.Add("email");
                options.Scope.Add("role");
                options.SaveTokens = true;
                options.ClaimActions.DeleteClaim("sid");
                options.ClaimActions.DeleteClaim("idp");
                options.ClaimActions.MapUniqueJsonKey("role", "role", "role");
                options.TokenValidationParameters.RoleClaimType = "role";
            });
</code>```

Controller 1 (MVC)

```<code>[Authorize(Roles = "CANCELAMENTO")]
public class CancelamentoController : Controller
</code>```

Controller 2 (MVC)

```<code>[Authorize(Roles = "ABASTECIMENTO")]
public class AbastecimentoController : Controller
</code>```

In the AspNetUserRoles table I have 2 roles for the user

The User object is coming from the roles:

```<code>Claims [IEnumerable]:{System.Security.Claims.ClaimsPrincipal.<get_Claims>d__22}
 Membros não públicos
Visualização dos Resultados:Expandir a Visualização dos Resultados vai enumerar o IEnumerable
   [0] [Claim]:{s_hash: 6WmMG-GghFBT9LCigeOnnw}
   [1] [Claim]:{sub: 64637127-9e46-46e2-ad51-47297a52d483}
   [2] [Claim]:{auth_time: 1641251760}
   [3] [Claim]:{amr: pwd}
   [4] [Claim]:{name: NOME}
   [5] [Claim]:{given_name: SOBRENOME}
   [6] [Claim]:{email: NOME@MAIL.COM}
   [8] [Claim]:{role: ["ABASTECIMENTO","CANCELAMENTO"]}
</code>```

Any idea?

Thank you

答:
I had the same issue and I changed

```<code>options.ClaimActions.MapUniqueJsonKey("role", "role", "role");
</code>```

to

```<code>options.ClaimActions.MapJsonKey("role", "role", "role");
</code>```

The User object will be like:

```<code>[8] [Claim]:{role: "ABASTECIMENTO"}
[9] [Claim]:{role: "CANCELAMENTO"}
</code>```

With this approach User.IsInRole("role name"); works fine.

My StartUp.cs in MVC:

```<code>services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
    options.Authority = "https://localhost:5001";
    options.ClientId = "mvc";
    options.ClientSecret = "secret";
    options.ResponseType = "code id_token";
    options.Scope.Add("email");
    options.Scope.Add("roles");

    options.ClaimActions.DeleteClaim("sid");
    options.ClaimActions.DeleteClaim("idp");
    options.ClaimActions.DeleteClaim("s_hash");
    options.ClaimActions.DeleteClaim("auth_time");
    options.ClaimActions.MapJsonKey("role", "role");
    options.Scope.Add("api1");
    options.SaveTokens = true;
    options.GetClaimsFromUserInfoEndpoint = true;
    options.TokenValidationParameters = new TokenValidationParameters
    {
        NameClaimType = "name",
        RoleClaimType = "role"
    };
});
</code>```

Config.cs in IDS4:

```<code>public static class Config
{
    public static IEnumerable<IdentityResource> IdentityResources =>
        new List<IdentityResource>
        {
        new IdentityResources.OpenId(),
        new IdentityResources.Profile(),
        new IdentityResources.Email(),
        new IdentityResource("roles", "Your role(s)", new List<string>() { "role" })
        };

    public static IEnumerable<ApiScope> ApiScopes =>
        new List<ApiScope>
        {
            new ApiScope("api1", "My API")
        };

    public static IEnumerable<Client> Clients =>
        new List<Client>
        {
        new Client
        {
            ClientId = "mvc",
            ClientName = "Application Web",
            AllowedGrantTypes = GrantTypes.Hybrid,
            ClientSecrets = { new Secret("secret".Sha256()) },
            RequirePkce = false,
            AllowRememberConsent = false,
            RedirectUris = { "https://localhost:5003/signin-oidc" },

            PostLogoutRedirectUris = { "https://localhost:5003/signout-callback-oidc" },

            AllowedScopes = new List<string>
            {
                IdentityServerConstants.StandardScopes.OpenId,
                IdentityServerConstants.StandardScopes.Profile,
                IdentityServerConstants.StandardScopes.Email,
                "api1",
                "roles"
            }
        }
        };
}
</code>```

Title: IdentityServer4. Using 2 roles per user

Body:
I'm using IdentityServer4 and an MVC client. My problem is just being able to use more than 1 role per user. In the example below, I have 2 controllers, each with its authorize. If 1 user has 2 Roles in the register, he gives access denied to both.

When you leave only 1 role for the user, it works just fine

Config.cs (IDS4)

        public static IEnumerable<IdentityResource> Ids =>
        new IdentityResource[]
        {
            new IdentityResources.OpenId(),
            new IdentityResources.Profile(),
            new IdentityResources.Email(),
            new IdentityResources.Phone(),
            new IdentityResource("role", "role", new List<string> { "role" }),
        };

            new Client
            {
                ClientId = "mvc",
                ClientName = "MVC App",
                ClientSecrets = { new Secret("secret".Sha256()) },
                AllowedGrantTypes = GrantTypes.CodeAndClientCredentials,
                RequireConsent = false,

                RedirectUris = { mvcURL + "/signin-oidc" },
                FrontChannelLogoutUri = mvcURL + "/signout-oidc",
                PostLogoutRedirectUris = { mvcURL + "/signout-callback-oidc" },

                //AllowOfflineAccess = true,
                AllowedScopes = {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    IdentityServerConstants.StandardScopes.Email,
                    IdentityServerConstants.StandardScopes.Phone,
                    "api", "role"
                }
            },

ProfileService.cs (IDS4)

        public async Task GetProfileDataAsync(ProfileDataRequestContext context)
    {
        var sub = context.Subject.GetSubjectId();
        var user = await _userManager.FindByIdAsync(sub);
        var principal = await _claimsFactory.CreateAsync(user);

        var claims = principal.Claims.ToList();
        claims = claims.Where(claim => context.RequestedClaimTypes.Contains(claim.Type)).ToList();

        // Add custom claims in token here based on user properties or any other source
        claims.Add(new Claim("id_user", user.Id.ToString()));
        claims.Add(new Claim("name", user.Name));
        claims.Add(new Claim("email", user.Email.ToString()));
        claims.Add(new Claim("role", user.role.ToString()));

        if (_userManager.SupportsUserRole)
        {
            var roles = await _userManager.GetRolesAsync(user);
            foreach (var roleName in roles)
            {
                claims.Add(new Claim(JwtClaimTypes.Role, roleName));

                if (_roleManager.SupportsRoleClaims)
                {
                    var role = await _roleManager.FindByNameAsync(roleName);
                    if (role != null)
                        claims.AddRange(await _roleManager.GetClaimsAsync(role));
                }
            }
        }

        context.IssuedClaims = claims;
    }

Startup.cs (MVC)

        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;

        })
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
            {
                options.Authority = Configuration.GetSection("ids_URI").Value;
                options.ClientId = "mvc";
                options.ClientSecret = "secret";
                options.ResponseType = OpenIdConnectResponseType.Code;
                options.GetClaimsFromUserInfoEndpoint = true;
                options.Scope.Add("openid");
                options.Scope.Add("profile");
                options.Scope.Add("email");
                options.Scope.Add("role");
                options.SaveTokens = true;
                options.ClaimActions.DeleteClaim("sid");
                options.ClaimActions.DeleteClaim("idp");
                options.ClaimActions.MapUniqueJsonKey("role", "role", "role");
                options.TokenValidationParameters.RoleClaimType = "role";
            });

Controller 1 (MVC)

[Authorize(Roles = "CANCELAMENTO")]
public class CancelamentoController : Controller

Controller 2 (MVC)

[Authorize(Roles = "ABASTECIMENTO")]
public class AbastecimentoController : Controller

In the AspNetUserRoles table I have 2 roles for the user

The User object is coming from the roles:

Claims [IEnumerable]:{System.Security.Claims.ClaimsPrincipal.<get_Claims>d__22}
 Membros não públicos
Visualização dos Resultados:Expandir a Visualização dos Resultados vai enumerar o IEnumerable
   [0] [Claim]:{s_hash: 6WmMG-GghFBT9LCigeOnnw}
   [1] [Claim]:{sub: 64637127-9e46-46e2-ad51-47297a52d483}
   [2] [Claim]:{auth_time: 1641251760}
   [3] [Claim]:{amr: pwd}
   [4] [Claim]:{name: NOME}
   [5] [Claim]:{given_name: SOBRENOME}
   [6] [Claim]:{email: NOME@MAIL.COM}
   [8] [Claim]:{role: ["ABASTECIMENTO","CANCELAMENTO"]}

Any idea?

Thank you

Body:
I had the same issue and I changed

options.ClaimActions.MapUniqueJsonKey("role", "role", "role");

to

options.ClaimActions.MapJsonKey("role", "role", "role");

The User object will be like:

[8] [Claim]:{role: "ABASTECIMENTO"}
[9] [Claim]:{role: "CANCELAMENTO"}

With this approach User.IsInRole("role name"); works fine.

My StartUp.cs in MVC:

services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
    options.Authority = "https://localhost:5001";
    options.ClientId = "mvc";
    options.ClientSecret = "secret";
    options.ResponseType = "code id_token";
    options.Scope.Add("email");
    options.Scope.Add("roles");

    options.ClaimActions.DeleteClaim("sid");
    options.ClaimActions.DeleteClaim("idp");
    options.ClaimActions.DeleteClaim("s_hash");
    options.ClaimActions.DeleteClaim("auth_time");
    options.ClaimActions.MapJsonKey("role", "role");
    options.Scope.Add("api1");
    options.SaveTokens = true;
    options.GetClaimsFromUserInfoEndpoint = true;
    options.TokenValidationParameters = new TokenValidationParameters
    {
        NameClaimType = "name",
        RoleClaimType = "role"
    };
});

Config.cs in IDS4:

public static class Config
{
    public static IEnumerable<IdentityResource> IdentityResources =>
        new List<IdentityResource>
        {
        new IdentityResources.OpenId(),
        new IdentityResources.Profile(),
        new IdentityResources.Email(),
        new IdentityResource("roles", "Your role(s)", new List<string>() { "role" })
        };

    public static IEnumerable<ApiScope> ApiScopes =>
        new List<ApiScope>
        {
            new ApiScope("api1", "My API")
        };

    public static IEnumerable<Client> Clients =>
        new List<Client>
        {
        new Client
        {
            ClientId = "mvc",
            ClientName = "Application Web",
            AllowedGrantTypes = GrantTypes.Hybrid,
            ClientSecrets = { new Secret("secret".Sha256()) },
            RequirePkce = false,
            AllowRememberConsent = false,
            RedirectUris = { "https://localhost:5003/signin-oidc" },

            PostLogoutRedirectUris = { "https://localhost:5003/signout-callback-oidc" },

            AllowedScopes = new List<string>
            {
                IdentityServerConstants.StandardScopes.OpenId,
                IdentityServerConstants.StandardScopes.Profile,
                IdentityServerConstants.StandardScopes.Email,
                "api1",
                "roles"
            }
        }
        };
}


问:
Simulate mouseenter with pure css
I need to style an element when I hover with the mouse above it. But, I don't want to style its parent DOM elements. However, when I use :hover the element in question is styled just as I want, but unfortunately, all of its parents are styled too

```<code>*:hover {
    border-color: red;
}
</code>```

DEMO

main,
article,
div {
  border: 1px solid lightgrey;
  padding: 30px;
}

*:hover {
  border-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
  <article>
    <div>

    </div>
  </article>
</main></code>```

The outer border shall be red only if the cursor is between the outer border and the middle border. The middle order shall be red only if the cursor is between the middle border and the inner border. The inner border shall be red only if the cursor is inside the inner border.

Is there a way to only style the DOM element being hovered (which can be any element)? or can I only achieve this goal with javascript?

答:
You can simply use this code:</p>
```<code>$("main, article, div").hover(function () {
      $(this).parent().css('border-color', 'lightgrey');
}, function () {
      $(this).parent().css('border-color', '');
});
</code>```

Title: Simulate mouseenter with pure css

Body:
I need to style an element when I hover with the mouse above it. But, I don't want to style its parent DOM elements. However, when I use :hover the element in question is styled just as I want, but unfortunately, all of its parents are styled too

*:hover {
    border-color: red;
}

DEMO

main,
article,
div {
  border: 1px solid lightgrey;
  padding: 30px;
}

*:hover {
  border-color: red;
}

The outer border shall be red only if the cursor is between the outer border and the middle border. The middle order shall be red only if the cursor is between the middle border and the inner border. The inner border shall be red only if the cursor is inside the inner border.

Is there a way to only style the DOM element being hovered (which can be any element)? or can I only achieve this goal with javascript?

Body:
You can simply use this code:

$("main, article, div").hover(function () {
      $(this).parent().css('border-color', 'lightgrey');
}, function () {
      $(this).parent().css('border-color', '');
});


问:
Need guidance in using LISTAGG with Regular Expression
```<code>SELECT
         ID_Col,
         lower(LISTAGG(distinct TEXT_COL,',')WITHIN GROUP(ORDER BY TEXT_COL))
         AS TEXT_COL_TXT
         FROM
         (SELECT
          CREATE_DT,
          ID_Col,
          TEXT_COL,
          TRY_CAST(Q_NO as INTEGER) as Q_NO
          FROM db_name.schema_name.tbl_name
          WHERE Flg = '0'
          AND date_of_cr = '2022-02-05'
          AND P_CODE NOT IN ('1','2','3','4')
          AND ID_Col IN('12345','23456')
          ORDER BY Q_NO)
          GROUP BY 1;
</code>```

When I run the above query, I'm getting results like this:

```<code>ID_COL                                        TEXT_COL

12345                                 ::abcd::0,aforapple
23456                                 ::abcd::0,n:sometext:::empty::
</code>```

I want this value to be removed in the result --> ::abcd::0,

The result should look like below:

```<code>ID_COL                                   TEXT_COL

12345                                 aforapple
23456                                 n:sometext:::empty::
</code>```

Can anyone guide me how to bring such a result?

When I use the below logic, I could see comma in the results now:

LISTAGG(distinct iff(TEXT_COL = '::abcd::0', '', TEXT_COL),',')

Result I could see is:

```<code>ID_COL                                   TEXT_COL

12345                                 ,aforapple
23456                                 ,n:sometext:::empty::
</code>```

I should not display comma in the results

答:
You could use nullif which will set that column value to null if it matches ::abcd::0. The listagg will ignore the nulls in aggregation

```<code>listagg(distinct nullif(text_col,'::abcd::0'),',') within group (order by text_col)
</code>```

Body:
SELECT
         ID_Col,
         lower(LISTAGG(distinct TEXT_COL,',')WITHIN GROUP(ORDER BY TEXT_COL))
         AS TEXT_COL_TXT
         FROM
         (SELECT
          CREATE_DT,
          ID_Col,
          TEXT_COL,
          TRY_CAST(Q_NO as INTEGER) as Q_NO
          FROM db_name.schema_name.tbl_name
          WHERE Flg = '0'
          AND date_of_cr = '2022-02-05'
          AND P_CODE NOT IN ('1','2','3','4')
          AND ID_Col IN('12345','23456')
          ORDER BY Q_NO)
          GROUP BY 1;

When I run the above query, I'm getting results like this:

ID_COL                                        TEXT_COL

12345                                 ::abcd::0,aforapple
23456                                 ::abcd::0,n:sometext:::empty::

I want this value to be removed in the result --> ::abcd::0,

The result should look like below:

ID_COL                                   TEXT_COL

12345                                 aforapple
23456                                 n:sometext:::empty::

Can anyone guide me how to bring such a result?

When I use the below logic, I could see comma in the results now:

LISTAGG(distinct iff(TEXT_COL = '::abcd::0', '', TEXT_COL),',')

Result I could see is:

ID_COL                                   TEXT_COL

12345                                 ,aforapple
23456                                 ,n:sometext:::empty::

I should not display comma in the results

Body:
You could use nullif which will set that column value to null if it matches ::abcd::0. The listagg will ignore the nulls in aggregation

listagg(distinct nullif(text_col,'::abcd::0'),',') within group (order by text_col)


问:
Nginx switches back to the first node after it comes back online
I am using Nginx as a failover cluster, where a service is given as an upstream.
The service is running in both the nodes simultaneously and the Nginx is set up in third node which redirects to other nodes.
When we switch off the service in one node it successfully switches to the backup node, but when the service in the 1st node is turned back on it switches back to the 1st node.
Below is the relevant part of the configuration in Nginx:

```<code>http {
include       mime.types;
default_type  application/octet-stream;

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"'
                  '"upstream: $upstream_addr"'
                  '"status: $upstream_status"';

access_log  logs\access.log  main;

sendfile        on;
#tcp_nopush     on;

#keepalive_timeout  0;
keepalive_timeout  65;

#gzip  on;

upstream backend {
    server ip1:port1 fail_timeout=5s max_fails=1;
    server ip2:port2 backup;
}

server {
    listen       8000;
    server_name  ip3;

    ssl_certificate      ...\certificate.crt;
    ssl_certificate_key  ...\privateKey.key;

    ssl_session_cache    shared:SSL:1m;
    ssl_session_timeout  5m;

    ssl_ciphers  HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers  on;

location / {
        proxy_pass https://backend;

}
</code>```

How can I stop switching the node to the primary node once the service is up again?

Thanks.

答:
This is the desired behaviour. If NGINX is balancing between two nodes and one of them is marked as backup NGINX will just switch to this note in case the primary node is done.

As soon as the primary node is back up and healthy, NGINX will always switch back to the primary node.

Read more about it here. https://nginx.org/en/docs/http/ngx_http_upstream_module.html#upstream

If you are looking for something like Blue / Green deployments there are other concepts to do it.

One that works with NGINX Open Source is available here.

Body:
I am using Nginx as a failover cluster, where a service is given as an upstream.
The service is running in both the nodes simultaneously and the Nginx is set up in third node which redirects to other nodes.
When we switch off the service in one node it successfully switches to the backup node, but when the service in the 1st node is turned back on it switches back to the 1st node.
Below is the relevant part of the configuration in Nginx:

http {
include       mime.types;
default_type  application/octet-stream;

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"'
                  '"upstream: $upstream_addr"'
                  '"status: $upstream_status"';

access_log  logs\access.log  main;

sendfile        on;
#tcp_nopush     on;

#keepalive_timeout  0;
keepalive_timeout  65;

#gzip  on;

upstream backend {
    server ip1:port1 fail_timeout=5s max_fails=1;
    server ip2:port2 backup;
}

server {
    listen       8000;
    server_name  ip3;

    ssl_certificate      ...\certificate.crt;
    ssl_certificate_key  ...\privateKey.key;

    ssl_session_cache    shared:SSL:1m;
    ssl_session_timeout  5m;

    ssl_ciphers  HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers  on;

location / {
        proxy_pass https://backend;

}

How can I stop switching the node to the primary node once the service is up again?

Thanks.


问:
R - Grouped Barplot with legend
I have tried to replicate code/ guidance from other answers to grouped barplot help but always seem to encounter error messages. I get these even before trying to add in titles/ legend.

I have the below dataset;

Month
CT Report Terminals
ATM DB Terminals
Member Stats Terminals
HC Errors

Nov-21
406
139
1251
888

Dec-21
640
1438
1544
740

Jan-22
795
939
1000
297

I want to replicate the below graph;

I can do this easily in excel but trying to stick with R. I have the below code;

```<code>library(ggplot2)

read_excel("ct_summary.xlsx")

data <- read_excel("ct_summary.xlsx")

Category <- c("CT Report Terminals", "ATM DB Terminals",
              "Member Stats Terminals", "HC Errors")

ggplot(data, aes(x = Category, y = Category, fill=Month)) +
  geom_bar(stat="identity", position = "dodge")
</code>```

The error message Error: Aesthetics must be either length 1 or the same as the data (3): x and fill keeps appearing or I get errors around bar height.

答:
You need to pivot your data into long format. You can use tidyr::pivot_longer(data, -1) to do this easily. Everything else in the following code is just cosmetic tweaks to make your plot look more like the original:

library(ggplot2)
library(dplyr)
library(tidyr)

data %>%
  pivot_longer(-1) %>%
  mutate(Month = factor(Month, c("Nov-21", "Dec-21", "Jan-22")),
         name = stringr::str_wrap(name, 12),
         name = factor(name, levels(factor(name))[c(2, 1, 4, 3)])) %>%
  ggplot(aes(name, value, fill = Month)) +
  geom_col(width = 0.6, position = position_dodge(width = 0.8)) +
  scale_fill_manual(values = c("#4472c4", "#ed7d31", "#a5a5a5")) +
  scale_y_continuous(breaks = 0:9 * 200) +
  labs(x = "", y = "", title = "Heading TBC") +
  theme_bw() +
  theme(panel.grid.major.x = element_blank(),
        panel.border = element_blank(),
        plot.title = element_text(hjust = 0.5))
```
<p><img src="https://i.stack.imgur.com/4HZF8.png" alt="enter image description here" /></p>
<hr />
<p><strong>Data</strong></p>
```data <- structure(list(Month = c("Nov-21", "Dec-21", "Jan-22"),
                       `CT Report Terminals` = c(406L, 640L, 795L),
                       `ATM DB Terminals` = c(139L, 1438L, 939L),
                       `Member Stats Terminals` = c(1251L, 1544L, 1000L),
                       `HC Errors` = c(888L, 740L, 297L)),
                  class = "data.frame", row.names = c(NA, -3L))
```

Title: R - Grouped Barplot with legend

Body:
I have tried to replicate code/ guidance from other answers to grouped barplot help but always seem to encounter error messages. I get these even before trying to add in titles/ legend.

I have the below dataset;

Month
CT Report Terminals
ATM DB Terminals
Member Stats Terminals
HC Errors

Nov-21
406
139
1251
888

Dec-21
640
1438
1544
740

Jan-22
795
939
1000
297

I want to replicate the below graph;

I can do this easily in excel but trying to stick with R. I have the below code;

library(ggplot2)

read_excel("ct_summary.xlsx")

data <- read_excel("ct_summary.xlsx")

Category <- c("CT Report Terminals", "ATM DB Terminals",
              "Member Stats Terminals", "HC Errors")

ggplot(data, aes(x = Category, y = Category, fill=Month)) +
  geom_bar(stat="identity", position = "dodge")

The error message Error: Aesthetics must be either length 1 or the same as the data (3): x and fill keeps appearing or I get errors around bar height.

Body:
You need to pivot your data into long format. You can use tidyr::pivot_longer(data, -1) to do this easily. Everything else in the following code is just cosmetic tweaks to make your plot look more like the original:

library(ggplot2)
library(dplyr)
library(tidyr)

data %>%
  pivot_longer(-1) %>%
  mutate(Month = factor(Month, c("Nov-21", "Dec-21", "Jan-22")),
         name = stringr::str_wrap(name, 12),
         name = factor(name, levels(factor(name))[c(2, 1, 4, 3)])) %>%
  ggplot(aes(name, value, fill = Month)) +
  geom_col(width = 0.6, position = position_dodge(width = 0.8)) +
  scale_fill_manual(values = c("#4472c4", "#ed7d31", "#a5a5a5")) +
  scale_y_continuous(breaks = 0:9 * 200) +
  labs(x = "", y = "", title = "Heading TBC") +
  theme_bw() +
  theme(panel.grid.major.x = element_blank(),
        panel.border = element_blank(),
        plot.title = element_text(hjust = 0.5))

Data

data <- structure(list(Month = c("Nov-21", "Dec-21", "Jan-22"),
                       `CT Report Terminals` = c(406L, 640L, 795L),
                       `ATM DB Terminals` = c(139L, 1438L, 939L),
                       `Member Stats Terminals` = c(1251L, 1544L, 1000L),
                       `HC Errors` = c(888L, 740L, 297L)),
                  class = "data.frame", row.names = c(NA, -3L))


问:
Order a Query by Name of Parent and its child
I have this table where you have an ParentID within the same table.

ID
Name
ParentID

1
Alpha
NULL

2
Delta
4

3
Sigma
7

4
Beta
NULL

5
Charlie
1

6
Echo
1

7
Foxtrot
NULL

8
Omega
7

How can I query ALL sorted by Name (Parent First) and child under it. So the result will be like this:

ID
Name
ParentID

1
Alpha
NULL

5
Charlie
1

6
Echo
1

4
Beta
NULL

2
Delta
4

7
Foxtrot
NULL

8
Omega
7

3
Sigma
7

答:
One other way to order the rows in the event the ID value ordering doesn't always align with the aphabetical ordering of the Parent names would be as follows

```<code>select *
from t
order by Concat(coalesce((select name from t t2 where t2.id=t.parentId),''), name)
</code>```

Of course this only works for a single level of parents, which appears to be the case with the sample data.

Body:
One other way to order the rows in the event the ID value ordering doesn't always align with the aphabetical ordering of the Parent names would be as follows

select *
from t
order by Concat(coalesce((select name from t t2 where t2.id=t.parentId),''), name)

Of course this only works for a single level of parents, which appears to be the case with the sample data.


问:
Communicate with Kohler Meter in C#
I m trying to communicate with Kohler active meter. It s half duplex. I ve read all protocol. Kohler has own software to see the profiles. While it was reading the profiles, i tried to view how it is happening. Sending and recieving datas. Then i tried to write a programme in C#. To communicate in first steps baud-rate is chosen 300, and then it should be 4800.

Here is my problems:

If i try to debug my programme using F5, it is not communicating. But if i use step into mode F11, it is working? i guess it should wait some amount of time. any idea?

When i try to change baud-rate from 300 to 4800, step into mode F11 is not working. I checked in the software if it is changing or not, but it is fine. any idea what this is about?

答:
This is a common mishap when you work with serial ports.  They are very slow devices, especially at 300 baud.  That's only one character per 33 milliseconds, an eternity on a modern machine.  By using the debugger, you artificially slow down your program.  A lot.  Giving the serial port driver time to receive the full device response.  When you run without single-stepping or breakpoints, the SerialPort.Read() call only returns one or a few characters at a time.  You fix this by using ReadLine() with a properly set NewLine property or by storing the received bytes in a buffer until you got the full response.

You can't just change the baudrate, it must always match the rate of the device.

Title: Communicate with Kohler Meter in C#


问:
Too many renders error when trying to delay rendering a component using setTimeout in React
So there is a parent & child component and I am setting cart items in local storage inside Parent component and want to access them in child components. Now the issue is that in child component , "cart is empty prompt" runs first even though I am extracting cart items from local storage. So I want to delay rendering of the child component by 2 sec so that the extracted cart items from the local storage are ready & get accessed first instead of running "cart is empty" prompt.

Here is the useEffect in child component in which i am extracting & checking for cart items -

```<code>var cartItems;

useEffect(() => {
if (localStorage.getItem("cartItems")) {
  cartItems = JSON.parse(localStorage.getItem("cartItems"));
} else {
  Swal.fire({
    position: "center",
    icon: "info",
    title: "Cart Is Empty!",
    showConfirmButton: true,
  }).then(() => {
        navigate(-1);
      });
    }
  }, []);
</code>```

Also cartItems is getting stored in local storage -

Here is the delay code which i took from (Delayed rendering of React components) which wraps around my child component -

```<code>import { useState, useEffect } from "react";

const Delayed = ({ children, delay, loader }) => {

  const [isShown, setIsShown] = useState(false);

  useEffect(() => {
    var timer = setTimeout(() => {
      setIsShown(true);
    }, delay);

    return () => {clearTimeout(timer);}

  }, [delay]);

  return isShown ? children : loader;
}

export default Delayed
</code>```

and finally my parent component -

```<code><Delayed delay={2000} loader={<Loader />}>
     <Products/>
 </Delayed>
</code>```

Also the 'setIsShown(true)' is causing the too many render problems , pointed in console.
Basic idea is that I would store cart items in local storage in parent component and then access them again in child component , i also tried passing the cart items as props but still the cart is empty prompt ran first , so it boils down to making the child component render after a delay to make the cartItems accessible. I am trying to resolve this issue from past couple of days but I had no luck. So I though of posting it here.Please help me resolve this problem. Thank you

答:
Have you tried using useLayoutEffect instead of useEffect?
The issue is not in your Delayed component, see this codesandbox.
I also need to mention, that it's bad practice to delay a ui-element.

Body:
So there is a parent & child component and I am setting cart items in local storage inside Parent component and want to access them in child components. Now the issue is that in child component , "cart is empty prompt" runs first even though I am extracting cart items from local storage. So I want to delay rendering of the child component by 2 sec so that the extracted cart items from the local storage are ready & get accessed first instead of running "cart is empty" prompt.

Here is the useEffect in child component in which i am extracting & checking for cart items -

var cartItems;

useEffect(() => {
if (localStorage.getItem("cartItems")) {
  cartItems = JSON.parse(localStorage.getItem("cartItems"));
} else {
  Swal.fire({
    position: "center",
    icon: "info",
    title: "Cart Is Empty!",
    showConfirmButton: true,
  }).then(() => {
        navigate(-1);
      });
    }
  }, []);

Also cartItems is getting stored in local storage -

Here is the delay code which i took from (Delayed rendering of React components) which wraps around my child component -

import { useState, useEffect } from "react";

const Delayed = ({ children, delay, loader }) => {

  const [isShown, setIsShown] = useState(false);

  useEffect(() => {
    var timer = setTimeout(() => {
      setIsShown(true);
    }, delay);

    return () => {clearTimeout(timer);}

  }, [delay]);

  return isShown ? children : loader;
}

export default Delayed

and finally my parent component -

<Delayed delay={2000} loader={<Loader />}>
     <Products/>
 </Delayed>

Also the 'setIsShown(true)' is causing the too many render problems , pointed in console.
Basic idea is that I would store cart items in local storage in parent component and then access them again in child component , i also tried passing the cart items as props but still the cart is empty prompt ran first , so it boils down to making the child component render after a delay to make the cartItems accessible. I am trying to resolve this issue from past couple of days but I had no luck. So I though of posting it here.Please help me resolve this problem. Thank you


问:
create an int column after dividing a column by a number in pandas
Assume that I have a panda data frame with a column that holds seconds.

I want to create a new column that holds minutes. so I divide the sec column by 60. The problem that I have is that min column is not an integer anymore. How can I make it an integer?

I have this code:

```<code>alldata['min']=alldata['sec']/60
</code>```

I tried this, but it did not work:

```<code>alldata['min']=int(alldata['sec']/60)
</code>```

I am getting this error:

```<code>TypeError: cannot convert the series to <class 'int'>
</code>```

I tried this:

```<code>alldata["min"] = pd.to_numeric(alldata["min"], downcast='integer')
</code>```

but I still have float values in min column.

How can have integer values for min? (Just drop the value to its floor value)

答:
Try

```<code>alldata['min'] = alldata['min'].astype('int64')
</code>```

or .astype('int32') Based on your operating system

Body:
Assume that I have a panda data frame with a column that holds seconds.

I want to create a new column that holds minutes. so I divide the sec column by 60. The problem that I have is that min column is not an integer anymore. How can I make it an integer?

I have this code:

alldata['min']=alldata['sec']/60

I tried this, but it did not work:

alldata['min']=int(alldata['sec']/60)

I am getting this error:

TypeError: cannot convert the series to <class 'int'>

I tried this:

alldata["min"] = pd.to_numeric(alldata["min"], downcast='integer')

but I still have float values in min column.

How can have integer values for min? (Just drop the value to its floor value)

Body:
Try

alldata['min'] = alldata['min'].astype('int64')

or .astype('int32') Based on your operating system


问:
Read spark csv dataframe as pandas
After processing a big data on pyspark, I saved it on csv using the following command:

```<code>df.repartition(1).write.option("header", "true").option("delimeter", "\t").csv("csv_data", mode="overwrite")
</code>```

Now, I want use pd.read_csv() to load it again.

```<code>info = pd.read_csv('part0000.csv', sep='\t', header='infer')
</code>```

info is returned as 1 column where the data is separated by comma not '\t'.

```<code>col1name,col2name,col3name
val1,val2,val3
</code>```

I tried to specify the sep=',' but I got an parsing error where some rows have more than 3 cols.

How to fix that without skipping any rows ? Is there anything to do with spark to resolve it such as specify a '|' as delimiter

答:
As mentioned here,  pandas treats the char " for queting, and expects " after every " which is not always true in my case. To fix this problem, we have to specify quoting=3 to not use quote.

```<code>data = pd.read_csv('data.csv', header='infer', sep='\t', engine='python', quoting=3)
</code>```

Title: Read spark csv dataframe as pandas

Body:
After processing a big data on pyspark, I saved it on csv using the following command:

df.repartition(1).write.option("header", "true").option("delimeter", "\t").csv("csv_data", mode="overwrite")

Now, I want use pd.read_csv() to load it again.

info = pd.read_csv('part0000.csv', sep='\t', header='infer')

info is returned as 1 column where the data is separated by comma not '\t'.

col1name,col2name,col3name
val1,val2,val3

I tried to specify the sep=',' but I got an parsing error where some rows have more than 3 cols.

How to fix that without skipping any rows ? Is there anything to do with spark to resolve it such as specify a '|' as delimiter

Body:
As mentioned here,  pandas treats the char " for queting, and expects " after every " which is not always true in my case. To fix this problem, we have to specify quoting=3 to not use quote.

data = pd.read_csv('data.csv', header='infer', sep='\t', engine='python', quoting=3)


答:
Actually, it's possible with some tricks using ::before or ::after. You can use these pseudo-elements to cover up the borders you want. It's important to use pointer-events: none; on these elements, so they won't disturb anything, they are just there for decoration.

However, my opinion is that javascript is more effective in this use case.

Here is a quick solution you can check out:
https://codepen.io/serazoltan/pen/WNXOREq

It needs a lot of updates for general use, but I've made it just to show it's possible.

:root {
  --general-padding: 30px;
  --general-padding-neg: -33px;
}

main,
article,
div {
  border: 1px solid lightgrey;
  padding: var(--general-padding);
  position: relative;
  transition: all .3s;
}

main {
  height: 400px;
  z-index: 0;
}

article {
  height: 200px;
  z-index: 10;
}

div {
  height: 80px;
  z-index: 20;
}

main:hover {
  border-color: red;
}

article:hover {
  border-color: red;
}

article:hover::after {
  content: "";
  position: absolute;
  top: var(--general-padding-neg);
  left: var(--general-padding-neg);
  width: calc(100% + var(--general-padding)*2 + 4px);
  height: 460px;
  border: 1px solid lightgrey;
  pointer-events: none;
}

div:hover {
  border: 1px solid red;
  z-index: 20;
}

div:hover::after {
  content: "";
  position: absolute;
  top: var(--general-padding-neg);
  left: var(--general-padding-neg);
  width: calc(100% + var(--general-padding)*2 + 4px);
  height: 260px;
  border: 1px solid lightgrey;
  pointer-events: none;
}
```

Title: Simulate mouseenter with pure css