问:
How to dynamically choose a DbContext for API endpoint method
I developed and API that uses a helper class to get the database context for each endpoint function. Now I'm trying to write unit tests for each endpoint and I want to use an In-memory db in my unit test project.

The issue I'm running into is that in order to call the API functions I had to add a constructor to my API controller class. This would allow me to pass the dbContext of the in-memory db to the controller function for it to use. However, since the adding of the constuctor I got the following error when attempting to hit the endpoint:

```<code>"exceptionMessage": "Unable to resolve service for type 'AppointmentAPI.Appt_Models.ApptSystemContext' while attempting to activate 'AppointmentAPI.Controllers.apptController'."
</code>```

UPDATE

controller.cs

```<code> public class apptController : Controller
    {
        private readonly ApptSystemContext _context;

        public apptController(ApptSystemContext dbContext)
        {
            _context = dbContext;
        }

        #region assingAppt
        /*
         * assignAppt()
         *
         * Assigns newly created appointment to slot
         * based on slotId
         *
         */
        [Authorize]
        [HttpPost]
        [Route("/appt/assignAppt")]
        public string assignAppt([FromBody] dynamic apptData)
        {
            int id = apptData.SlotId;
            string json = apptData.ApptJson;
            DateTime timeStamp = DateTime.Now;

            using (_context)
            {
               var slot = _context.AppointmentSlots.Single(s => s.SlotId == id);

                // make sure there isn't already an appointment booked in appt slot
                if (slot.Timestamp == null)
                {
                    slot.ApptJson = json;
                    slot.Timestamp = timeStamp;

                    _context.SaveChanges();
                    return "Task Executed\n";
                }
                else
                {
                    return "There is already an appointment booked for this slot.\n" +
                           "If this slot needs changing try updating it instead of assigning it.";
                }
            }
        }
   }
</code>```

UnitTest.cs

```<code>using System;
using Xunit;
using AppointmentAPI.Controllers;
using AppointmentAPI.Appt_Models;
using Microsoft.EntityFrameworkCore;

namespace XUnitTest
{
    public abstract class UnitTest1
    {
        protected UnitTest1(DbContextOptions<ApptSystemContext> contextOptions)
        {
            ContextOptions = contextOptions;

            SeedInMemoryDB();
        }

        protected DbContextOptions<ApptSystemContext> ContextOptions { get; }

        private void SeedInMemoryDB()
        {
            using(var context = new ApptSystemContext(ContextOptions))
            {
                context.Database.EnsureDeleted();
                context.Database.EnsureCreated();

                var seventh = new AppointmentSlots
                {
                    SlotId = 7,
                    Date = Convert.ToDateTime("2020-05-19 00:00:00.000"),
                    Time = TimeSpan.Parse("08:45:00.0000000"),
                    ApptJson = null,
                    Timestamp = null
                };

                context.AppointmentSlots.Add(seventh);
                context.SaveChanges();
            }
        }

        [Fact]
        public void Test1()
        {
            DbContextOptions<ApptSystemContext> options;
            var builder = new DbContextOptionsBuilder<ApptSystemContext>();
            builder.UseInMemoryDatabase();
            options = builder.Options;

            var context = new ApptSystemContext(options);

            var controller = new apptController(context);

            // Arrange
            var request = new AppointmentAPI.Appt_Models.AppointmentSlots
            {
                SlotId = 7,
                ApptJson = "{'fname':'Emily','lname':'Carlton','age':62,'caseWorker':'Brenda', 'appStatus':'unfinished'}",
                Timestamp = Convert.ToDateTime("2020-06-25 09:34:00.000")
            };

            string expectedResult = "Task Executed\n";

            // Act
            var response = controller.assignAppt(request);

            Assert.Equal(response, expectedResult);

        }
    }
}

</code>```

InMemoryClass.cs

```<code>using System;
using System.Data.Common;
using Microsoft.EntityFrameworkCore;
using AppointmentAPI.Appt_Models;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore.Infrastructure;

namespace XUnitTest
{
    public class InMemoryClass1 : UnitTest1, IDisposable
    {
        private readonly DbConnection _connection;

        public InMemoryClass1()
            :base(
                 new DbContextOptionsBuilder<ApptSystemContext>()
                    .UseSqlite(CreateInMemoryDB())
                    .Options
            )
        {
            _connection = RelationalOptionsExtension.Extract(ContextOptions).Connection;
        }

        private static DbConnection CreateInMemoryDB()
        {
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            return connection;
        }

        public void Dispose() => _connection.Dispose();

    }
}

</code>```

答:
The exception suggests that you haven't registered your DBContext in your Startup.cs (as mentioned above).  I'd also suggest that you change the name of your private readonly property to something other than DbContext (which is the class name and can get confusing)
 Use something like this:

private readonly ApptSystemContext _context;
```

<p>Besides that, your approach should be changed.  </p>

<p>First, you will set the connection string when you register the DBContext.  Just let dependency injection take care of that for you.  Your controller should look like this:</p>

<pre class="lang-cs prettyprint-override"><code>        public apptController(ApptSystemContext dbContext)
        {
            _context = dbContext;
        }
</code>```

The dbContext won't be null if you register it in Startup.

Next, unit testing is a tricky concept, but once you write your Unit test, you'll start to understand a little better.

You've said that you want to use the SQL In Memory db for unit testing, which is a good approach (be aware that there are limitations to SQL In Mem like no FK constraints).  Next, I assume you want to test your Controller, so, since you MUST pass in a DBContext in order to instantiate your Controller, you can create a new DBContext instance that is configured to use the In Memory Database.

For example

public void ApptControllerTest()
{
   //create new dbcontext
   DbContextOptions<ApptSystemContext> options;
        var builder = new DbContextOptionsBuilder<ApptSystemContext>();
        builder.UseInMemoryDatabase();
        options = builder.Options;

    var context = new ApptSystemContext(options);

   //instantiate your controller
   var controller = new appController(context);

   //call your method that you want to test
   var retVal = controller.assignAppt(args go here);
}
```

<p>Change the body of the method to this:</p>

<pre class="lang-cs prettyprint-override"><code>public string assignAppt([FromBody] dynamic apptData)
        {
            int id = apptData.SlotId;
            string json = apptData.ApptJson;
            DateTime timeStamp = DateTime.Now;

            using (_context)
            {
               var slot = _context.AppointmentSlots.Single(s => s.SlotId == id);

                // make sure there isn't already an appointment booked in appt slot
                if (slot.Timestamp == null)
                {
                    slot.ApptJson = json;
                    slot.Timestamp = timeStamp;

                    _context.SaveChanges();
                    return "Task Executed\n";
                }
                else
                {
                    return "There is already an appointment booked for this slot.\n" +
                           "If this slot needs changing try updating it instead of assigning it.";
                }
            }
        }
</code>```

Another suggestion, don't use a dynamic object as the body of a request unless you are absolutely forced to do so.  Using a dynamic object allows for anything to be passed in and you lose the ability to determine if a request is acceptible or not.

Body:
I developed and API that uses a helper class to get the database context for each endpoint function. Now I'm trying to write unit tests for each endpoint and I want to use an In-memory db in my unit test project.

The issue I'm running into is that in order to call the API functions I had to add a constructor to my API controller class. This would allow me to pass the dbContext of the in-memory db to the controller function for it to use. However, since the adding of the constuctor I got the following error when attempting to hit the endpoint:

"exceptionMessage": "Unable to resolve service for type 'AppointmentAPI.Appt_Models.ApptSystemContext' while attempting to activate 'AppointmentAPI.Controllers.apptController'."

UPDATE

controller.cs

 public class apptController : Controller
    {
        private readonly ApptSystemContext _context;

        public apptController(ApptSystemContext dbContext)
        {
            _context = dbContext;
        }

        #region assingAppt
        /*
         * assignAppt()
         *
         * Assigns newly created appointment to slot
         * based on slotId
         *
         */
        [Authorize]
        [HttpPost]
        [Route("/appt/assignAppt")]
        public string assignAppt([FromBody] dynamic apptData)
        {
            int id = apptData.SlotId;
            string json = apptData.ApptJson;
            DateTime timeStamp = DateTime.Now;

            using (_context)
            {
               var slot = _context.AppointmentSlots.Single(s => s.SlotId == id);

                // make sure there isn't already an appointment booked in appt slot
                if (slot.Timestamp == null)
                {
                    slot.ApptJson = json;
                    slot.Timestamp = timeStamp;

                    _context.SaveChanges();
                    return "Task Executed\n";
                }
                else
                {
                    return "There is already an appointment booked for this slot.\n" +
                           "If this slot needs changing try updating it instead of assigning it.";
                }
            }
        }
   }

UnitTest.cs

using System;
using Xunit;
using AppointmentAPI.Controllers;
using AppointmentAPI.Appt_Models;
using Microsoft.EntityFrameworkCore;

namespace XUnitTest
{
    public abstract class UnitTest1
    {
        protected UnitTest1(DbContextOptions<ApptSystemContext> contextOptions)
        {
            ContextOptions = contextOptions;

            SeedInMemoryDB();
        }

        protected DbContextOptions<ApptSystemContext> ContextOptions { get; }

        private void SeedInMemoryDB()
        {
            using(var context = new ApptSystemContext(ContextOptions))
            {
                context.Database.EnsureDeleted();
                context.Database.EnsureCreated();

                var seventh = new AppointmentSlots
                {
                    SlotId = 7,
                    Date = Convert.ToDateTime("2020-05-19 00:00:00.000"),
                    Time = TimeSpan.Parse("08:45:00.0000000"),
                    ApptJson = null,
                    Timestamp = null
                };

                context.AppointmentSlots.Add(seventh);
                context.SaveChanges();
            }
        }

        [Fact]
        public void Test1()
        {
            DbContextOptions<ApptSystemContext> options;
            var builder = new DbContextOptionsBuilder<ApptSystemContext>();
            builder.UseInMemoryDatabase();
            options = builder.Options;

            var context = new ApptSystemContext(options);

            var controller = new apptController(context);

            // Arrange
            var request = new AppointmentAPI.Appt_Models.AppointmentSlots
            {
                SlotId = 7,
                ApptJson = "{'fname':'Emily','lname':'Carlton','age':62,'caseWorker':'Brenda', 'appStatus':'unfinished'}",
                Timestamp = Convert.ToDateTime("2020-06-25 09:34:00.000")
            };

            string expectedResult = "Task Executed\n";

            // Act
            var response = controller.assignAppt(request);

            Assert.Equal(response, expectedResult);

        }
    }
}

InMemoryClass.cs

using System;
using System.Data.Common;
using Microsoft.EntityFrameworkCore;
using AppointmentAPI.Appt_Models;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore.Infrastructure;

namespace XUnitTest
{
    public class InMemoryClass1 : UnitTest1, IDisposable
    {
        private readonly DbConnection _connection;

        public InMemoryClass1()
            :base(
                 new DbContextOptionsBuilder<ApptSystemContext>()
                    .UseSqlite(CreateInMemoryDB())
                    .Options
            )
        {
            _connection = RelationalOptionsExtension.Extract(ContextOptions).Connection;
        }

        private static DbConnection CreateInMemoryDB()
        {
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            return connection;
        }

        public void Dispose() => _connection.Dispose();

    }
}

Body:
The exception suggests that you haven't registered your DBContext in your Startup.cs (as mentioned above).  I'd also suggest that you change the name of your private readonly property to something other than DbContext (which is the class name and can get confusing)
 Use something like this:

private readonly ApptSystemContext _context;

Besides that, your approach should be changed.

First, you will set the connection string when you register the DBContext.  Just let dependency injection take care of that for you.  Your controller should look like this:

        public apptController(ApptSystemContext dbContext)
        {
            _context = dbContext;
        }

The dbContext won't be null if you register it in Startup.

Next, unit testing is a tricky concept, but once you write your Unit test, you'll start to understand a little better.

You've said that you want to use the SQL In Memory db for unit testing, which is a good approach (be aware that there are limitations to SQL In Mem like no FK constraints).  Next, I assume you want to test your Controller, so, since you MUST pass in a DBContext in order to instantiate your Controller, you can create a new DBContext instance that is configured to use the In Memory Database.

For example

public void ApptControllerTest()
{
   //create new dbcontext
   DbContextOptions<ApptSystemContext> options;
        var builder = new DbContextOptionsBuilder<ApptSystemContext>();
        builder.UseInMemoryDatabase();
        options = builder.Options;

    var context = new ApptSystemContext(options);

   //instantiate your controller
   var controller = new appController(context);

   //call your method that you want to test
   var retVal = controller.assignAppt(args go here);
}

Change the body of the method to this:

public string assignAppt([FromBody] dynamic apptData)
        {
            int id = apptData.SlotId;
            string json = apptData.ApptJson;
            DateTime timeStamp = DateTime.Now;

            using (_context)
            {
               var slot = _context.AppointmentSlots.Single(s => s.SlotId == id);

                // make sure there isn't already an appointment booked in appt slot
                if (slot.Timestamp == null)
                {
                    slot.ApptJson = json;
                    slot.Timestamp = timeStamp;

                    _context.SaveChanges();
                    return "Task Executed\n";
                }
                else
                {
                    return "There is already an appointment booked for this slot.\n" +
                           "If this slot needs changing try updating it instead of assigning it.";
                }
            }
        }

Another suggestion, don't use a dynamic object as the body of a request unless you are absolutely forced to do so.  Using a dynamic object allows for anything to be passed in and you lose the ability to determine if a request is acceptible or not.


来源: stackexchange

问:
Converting a non-decimal number to a decimal-based number
I have a number in php formatted as 5299, and I'd like for it to be converted to a number that's decimal formatted as 52.99 to resemble money. I've messed around with php's number_format() but it doesn't seem like there is a way to add decimals for converting to cents. This number is dynamically calculated, so the 5299 might be 12122, where 5299 would be 52.99 and 12122 would be converted to 121.22.

答:
Just use a simple function like this.</p>

```<code><?php

$value = 50;

echo number_format(($value /100), 2, '.', ' ');

?>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Just use a simple function like this.

<?php

$value = 50;

echo number_format(($value /100), 2, '.', ' ');

?>


问:
How to stop Excel from mangling a formula inserted by my VBA script
I have a VBA script in an Excel workbook that gathers results from all the workbooks in a particular folder.

```<code>Private Sub Workbook_Open()

    Dim path As String
    Dim fso As Object
    Dim folder As Object
    Dim file As Object

    Dim i As Integer

    Dim data As Object

    Set data = Worksheets("RawData")
    path = data.Range("A1").Value

    i = 3

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set folder = fso.GetFolder(path)

    data.Rows("2:" & data.Rows.Count).ClearContents

    For Each file In folder.Files
        If Right(UCase(file.name), 5) = ".XLSX" And Left(file.name, 1) <> "~" Then
            data.Cells(i, 2) = "='" + path + "\[" + file.name + "]Summary'!A1:J1"
            i = i + 1
        End If
    Next file

End Sub
</code>```

The idea is for each .xlsx file in a given folder, I add a reference to the results range in that file. For example, if there is a file Test1.xlsx in folder C:\Sheets, the VBA puts the following formula into some row on the sheet containing the script:

```<code>='C:\Sheets\[Test1.xlsx]Summary'!A1:J1
</code>```

Excel then pulls values out of Test1 and puts them in the current workbook's RawData sheet.

This worked until today, when my formulas started ending up with @ right after the = sign, like this:

```<code>=@'C:\Sheets\[Test1.xlsx]Summary'!A1:J1
</code>```

This gives me a #VALUE?.

Excel helpfully gave me a message stating that it has just now started inserting @ into formulas due to some syntax changes, but that it wouldn't affect calculations. I can't get this message to show up again, but that was the gist of it. Obviously it does affect calculations. If I manually remove the @ from the formula, it works fine.

I have Office 365 and I guess I must have received an update recently that added this "feature" because all this used to work fine.

If I modify the VBA script to reference only a single cell, the @ does not get inserted. But using a named range for the results (rather than A1:J1) still has the problem.

Anyone have any ideas for a workaround?

答:
You could assign the formula to a variable and then remove the @ from the string using the Right() function...

As the length of the string will be dynamic depending on the length of the file name, I've used the Len() function to get the full lenght of the string, then minus 2 from it to remove the = and @.

Note the = is concatenated with the Right() function when assigning the value to the cell.

```<code>Dim FormulaString as String
    For Each file In folder.Files
        If Right(UCase(file.name), 5) = ".XLSX" And Left(file.name, 1) <> "~" Then
            FormulaString = "='" + path + "\[" + file.name + "]Summary'!A1:J1"
            data.Cells(i, 2) = "=" & Right(FormulaString, Len(FormulaString) - 2)
            i = i + 1
        End If
    Next file
</code>```

Output is

```<code>='C:\Sheets\[Test1.xlsx]Summary'!A1:J1
</code>```

Body:
I have a VBA script in an Excel workbook that gathers results from all the workbooks in a particular folder.

Private Sub Workbook_Open()

    Dim path As String
    Dim fso As Object
    Dim folder As Object
    Dim file As Object

    Dim i As Integer

    Dim data As Object

    Set data = Worksheets("RawData")
    path = data.Range("A1").Value

    i = 3

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set folder = fso.GetFolder(path)

    data.Rows("2:" & data.Rows.Count).ClearContents

    For Each file In folder.Files
        If Right(UCase(file.name), 5) = ".XLSX" And Left(file.name, 1) <> "~" Then
            data.Cells(i, 2) = "='" + path + "\[" + file.name + "]Summary'!A1:J1"
            i = i + 1
        End If
    Next file

End Sub

The idea is for each .xlsx file in a given folder, I add a reference to the results range in that file. For example, if there is a file Test1.xlsx in folder C:\Sheets, the VBA puts the following formula into some row on the sheet containing the script:

='C:\Sheets\[Test1.xlsx]Summary'!A1:J1

Excel then pulls values out of Test1 and puts them in the current workbook's RawData sheet.

This worked until today, when my formulas started ending up with @ right after the = sign, like this:

=@'C:\Sheets\[Test1.xlsx]Summary'!A1:J1

This gives me a #VALUE?.

Excel helpfully gave me a message stating that it has just now started inserting @ into formulas due to some syntax changes, but that it wouldn't affect calculations. I can't get this message to show up again, but that was the gist of it. Obviously it does affect calculations. If I manually remove the @ from the formula, it works fine.

I have Office 365 and I guess I must have received an update recently that added this "feature" because all this used to work fine.

If I modify the VBA script to reference only a single cell, the @ does not get inserted. But using a named range for the results (rather than A1:J1) still has the problem.

Anyone have any ideas for a workaround?

Body:
You could assign the formula to a variable and then remove the @ from the string using the Right() function...

As the length of the string will be dynamic depending on the length of the file name, I've used the Len() function to get the full lenght of the string, then minus 2 from it to remove the = and @.

Note the = is concatenated with the Right() function when assigning the value to the cell.

Dim FormulaString as String
    For Each file In folder.Files
        If Right(UCase(file.name), 5) = ".XLSX" And Left(file.name, 1) <> "~" Then
            FormulaString = "='" + path + "\[" + file.name + "]Summary'!A1:J1"
            data.Cells(i, 2) = "=" & Right(FormulaString, Len(FormulaString) - 2)
            i = i + 1
        End If
    Next file

Output is

='C:\Sheets\[Test1.xlsx]Summary'!A1:J1


问:
Call self.variable(established in __init__() ) within class definition parameters
I would like to call a class variable established in init from a class definition so it can be the default parameter value. Wording is hard but here is an example.

```<code>class Sound:
   def __init__(self):
      self.volume = 10

   def set_volume(self, vol=self.volume)
      play_sound_a(vol)
</code>```

I assumed that since init is called, then I should be able to use variables established in init from class definitions. I could do some if statements within the definition but using parameter defaults would be easier.

I simply get an error that self does not exist.

答:
It can't be done this way. The default parameter is defined when the method is compiled, well before any instance has been created. In fact, all instances of that class will share that same default value for that method. Instead you can use a sentinel such as None to know when you should use the instance volume. Assuming None is not otherwise a valid value for that parameter.

```<code>class Sound:
    def __init__(self):
        self.volume = 10

    def set_volume(self, vol=None):
        if vol is None:
            vol = self.volumne
        play_sound_a(vol)
</code>```

Body:
I would like to call a class variable established in init from a class definition so it can be the default parameter value. Wording is hard but here is an example.

class Sound:
   def __init__(self):
      self.volume = 10

   def set_volume(self, vol=self.volume)
      play_sound_a(vol)

I assumed that since init is called, then I should be able to use variables established in init from class definitions. I could do some if statements within the definition but using parameter defaults would be easier.

I simply get an error that self does not exist.

Body:
It can't be done this way. The default parameter is defined when the method is compiled, well before any instance has been created. In fact, all instances of that class will share that same default value for that method. Instead you can use a sentinel such as None to know when you should use the instance volume. Assuming None is not otherwise a valid value for that parameter.

class Sound:
    def __init__(self):
        self.volume = 10

    def set_volume(self, vol=None):
        if vol is None:
            vol = self.volumne
        play_sound_a(vol)


问:
Why when the components of this script, do they run fine but do not work when pieced together? There may just be a problem with it all together
This script is from Roblox Studio and is in Lua. I have tried using separate scripts but when I do, they don't work because of the bool value. The scripts seem either not to respond to it or it just doesn't update correctly.  I have attached the picture of the hierarchy from ROBLOX Studio. I am reasonably to new to Lua but I am familiar with the basic concepts. I also know the Roblox Studio Interface deeply. If anyone could help, that would be greatly appreciated. Thanks in advance.</p>

```<code>local lockvalue = script.Parent.Lockdown.Value
lockvalue = false
local RobBank = script.Parent["Rob Bank"]
local ClickDetector = RobBank:WaitForChild("ClickDetector")
local BillboardCXZ = RobBank:WaitForChild("BillboardGui")
local Billboard = BillboardCXZ:WaitForChild("TextLabel")
local emergencylight1 = script.Parent.Parent.EmergencyLight.Toggle.Value
local emergencylight2 = script.Parent.Parent.EmergencyLight2.Toggle.Value
local emergencylight3 = script.Parent.Parent.EmergencyLight3.Toggle.Value
local alarm1 = script.Parent.Parent.Alarm1.AlarmSound
local alarm2 = script.Parent.ParentAlarm2.AlarmSound
local Notif1 = script.Parent.NotifcationScreen.SurfaceGui.Frame.Visible
local Notif2 = script.Parent.NotifcationScreen.SurfaceGui.Frame.TextButton.MouseButton1Click
print ("Values Loaded.")

local function lock()
    print ("LOCK FUNCTION ACTIVATED")
    emergencylight1 = true
    emergencylight2 = true
    emergencylight3 = true
    alarm1:play()
    alarm2:play()
    lockvalue = true
    Notif1 = true
end

local function unlock()
    print ("UNLOCK FUNCTION ACTIVATED")
    emergencylight1 = false
    emergencylight2 = false
    emergencylight3 = false
    alarm1.stop()
    alarm2:stop()
    lockvalue = false
    Notif1 = false
end

Notif2:Connect(function()

unlock()
print ("Unlocked Via Override")

end)

RobBank.ClickDetector.MouseClick:Connect(function(Player)
print ("Functioning")
if Player and Player.Character then
print ("Milestone 2")
        if lockvalue == false then
    print ("After Lock Value")
          if Player.Team == game.Teams.Criminal then
            print ("Team Check")
            local clicks = Player:FindFirstChild("leaderstats")["Bounty"]
            clicks.Value = clicks.Value + 500
            local clicks2 = Player:FindFirstChild("leaderstats")["Cash"]
            clicks2.Value = clicks2.Value + 2500
            Billboard.TextColor3 = Color3.new(1,0,0)
            lock()
            wait(60)
            unlock()
            Billboard.TextColor3 = Color3.new(0,1,0)
          else
                print("Player Is not On Crim team.")
                Billboard.Text = ("You are on the Wrong Team!")
                wait(3)
                Billboard.Text = ("Steal Cash")
          end

        else
            Billboard.Text = ("Already been recently robbed!")
            wait(3)
            Billboard.Text = ("Steal Cash")
        end
    end
end)
</code>```

答:
In Lua, a variable can be a reference to a table which has children (key/value pairs):

```<code>local myTable = { }
myTable.myKey = true
</code>```

However, if you refer to a single child (by its key) then it will evaluate and pass only the resulting value into the variable (not a reference to the key itself).

```<code>local newVar = myTable.myKey
print(newVar)         -- true
newVar = false
print(newVar)         -- false
print(myTable.myKey)  -- true, because we never changed myKey
</code>```

So in the following statement, emergencylight1 is probably the value 'true' or 'false' rather than being a reference to the property itself.

```<code>local emergencylight1 = script.Parent.Parent.EmergencyLight.Toggle.Value
</code>```

Recommendation

Ensure your variables are references to an actual table, and then refer to a child of that table (by its key) when assigning a new value.

```<code>local emergencylighttoggle1 = script.Parent.Parent.EmergencyLight.Toggle
local emergencylighttoggle2 = script.Parent.Parent.EmergencyLight2.Toggle
local emergencylighttoggle3 = script.Parent.Parent.EmergencyLight3.Toggle

local function lock()
    emergencylighttoggle1.Value = true
    emergencylighttoggle2.Value = true
    emergencylighttoggle3.Value = true
end

local function unlock()
    emergencylighttoggle1.Value = false
    emergencylighttoggle2.Value = false
    emergencylighttoggle3.Value = false
end
</code>```

Body:
This script is from Roblox Studio and is in Lua. I have tried using separate scripts but when I do, they don't work because of the bool value. The scripts seem either not to respond to it or it just doesn't update correctly.  I have attached the picture of the hierarchy from ROBLOX Studio. I am reasonably to new to Lua but I am familiar with the basic concepts. I also know the Roblox Studio Interface deeply. If anyone could help, that would be greatly appreciated. Thanks in advance.

local lockvalue = script.Parent.Lockdown.Value
lockvalue = false
local RobBank = script.Parent["Rob Bank"]
local ClickDetector = RobBank:WaitForChild("ClickDetector")
local BillboardCXZ = RobBank:WaitForChild("BillboardGui")
local Billboard = BillboardCXZ:WaitForChild("TextLabel")
local emergencylight1 = script.Parent.Parent.EmergencyLight.Toggle.Value
local emergencylight2 = script.Parent.Parent.EmergencyLight2.Toggle.Value
local emergencylight3 = script.Parent.Parent.EmergencyLight3.Toggle.Value
local alarm1 = script.Parent.Parent.Alarm1.AlarmSound
local alarm2 = script.Parent.ParentAlarm2.AlarmSound
local Notif1 = script.Parent.NotifcationScreen.SurfaceGui.Frame.Visible
local Notif2 = script.Parent.NotifcationScreen.SurfaceGui.Frame.TextButton.MouseButton1Click
print ("Values Loaded.")

local function lock()
    print ("LOCK FUNCTION ACTIVATED")
    emergencylight1 = true
    emergencylight2 = true
    emergencylight3 = true
    alarm1:play()
    alarm2:play()
    lockvalue = true
    Notif1 = true
end

local function unlock()
    print ("UNLOCK FUNCTION ACTIVATED")
    emergencylight1 = false
    emergencylight2 = false
    emergencylight3 = false
    alarm1.stop()
    alarm2:stop()
    lockvalue = false
    Notif1 = false
end

Notif2:Connect(function()

unlock()
print ("Unlocked Via Override")

end)

RobBank.ClickDetector.MouseClick:Connect(function(Player)
print ("Functioning")
if Player and Player.Character then
print ("Milestone 2")
        if lockvalue == false then
    print ("After Lock Value")
          if Player.Team == game.Teams.Criminal then
            print ("Team Check")
            local clicks = Player:FindFirstChild("leaderstats")["Bounty"]
            clicks.Value = clicks.Value + 500
            local clicks2 = Player:FindFirstChild("leaderstats")["Cash"]
            clicks2.Value = clicks2.Value + 2500
            Billboard.TextColor3 = Color3.new(1,0,0)
            lock()
            wait(60)
            unlock()
            Billboard.TextColor3 = Color3.new(0,1,0)
          else
                print("Player Is not On Crim team.")
                Billboard.Text = ("You are on the Wrong Team!")
                wait(3)
                Billboard.Text = ("Steal Cash")
          end

        else
            Billboard.Text = ("Already been recently robbed!")
            wait(3)
            Billboard.Text = ("Steal Cash")
        end
    end
end)

Body:
In Lua, a variable can be a reference to a table which has children (key/value pairs):

local myTable = { }
myTable.myKey = true

However, if you refer to a single child (by its key) then it will evaluate and pass only the resulting value into the variable (not a reference to the key itself).

local newVar = myTable.myKey
print(newVar)         -- true
newVar = false
print(newVar)         -- false
print(myTable.myKey)  -- true, because we never changed myKey

So in the following statement, emergencylight1 is probably the value 'true' or 'false' rather than being a reference to the property itself.

local emergencylight1 = script.Parent.Parent.EmergencyLight.Toggle.Value

Recommendation

Ensure your variables are references to an actual table, and then refer to a child of that table (by its key) when assigning a new value.

local emergencylighttoggle1 = script.Parent.Parent.EmergencyLight.Toggle
local emergencylighttoggle2 = script.Parent.Parent.EmergencyLight2.Toggle
local emergencylighttoggle3 = script.Parent.Parent.EmergencyLight3.Toggle

local function lock()
    emergencylighttoggle1.Value = true
    emergencylighttoggle2.Value = true
    emergencylighttoggle3.Value = true
end

local function unlock()
    emergencylighttoggle1.Value = false
    emergencylighttoggle2.Value = false
    emergencylighttoggle3.Value = false
end


问:
HIDE Column in Select query?
Hi I'm trying to hide the TotalRank Column that gets displayed during my results because I only needed it in this query to help sort items. I don't need this information displayed.</p>

```<code>SELECT TOP 15 G.CharacterName, G.JobCode, G.PvPExp, D.PVPWin, D.PVPLose, D.PVPGiveUp, RANK() OVER (ORDER BY TotalRank ASC ) as TotalRank
FROM PvPRanking as G
INNER JOIN PVPScores as D
ON G.CharacterID = D.CharacterID
</code>```

答:
You can create and alias to the resulting table and select everything from it except for the total rank column.</p>

```<code>SELECT t1.CharacterName, t1.JobCode, t1.PvPExp, t1.PVPWin, t1.PVPLose, t1.PVPGiveUp
FROM
(SELECT TOP 15 G.CharacterName, G.JobCode, G.PvPExp, D.PVPWin, D.PVPLose, D.PVPGiveUp,
RANK() OVER (ORDER BY TotalRank ASC ) as TotalRank
FROM PvPRanking as G
INNER JOIN PVPScores as D
ON G.CharacterID = D.CharacterID) AS t1
</code>```

Title: HIDE Column in Select query?

Body:
Hi I'm trying to hide the TotalRank Column that gets displayed during my results because I only needed it in this query to help sort items. I don't need this information displayed.

SELECT TOP 15 G.CharacterName, G.JobCode, G.PvPExp, D.PVPWin, D.PVPLose, D.PVPGiveUp, RANK() OVER (ORDER BY TotalRank ASC ) as TotalRank
FROM PvPRanking as G
INNER JOIN PVPScores as D
ON G.CharacterID = D.CharacterID

Body:
You can create and alias to the resulting table and select everything from it except for the total rank column.

SELECT t1.CharacterName, t1.JobCode, t1.PvPExp, t1.PVPWin, t1.PVPLose, t1.PVPGiveUp
FROM
(SELECT TOP 15 G.CharacterName, G.JobCode, G.PvPExp, D.PVPWin, D.PVPLose, D.PVPGiveUp,
RANK() OVER (ORDER BY TotalRank ASC ) as TotalRank
FROM PvPRanking as G
INNER JOIN PVPScores as D
ON G.CharacterID = D.CharacterID) AS t1


问:
how to merge 4 arrays object using lodash
I am looking for best ways of doing this.

exData1 = [
  { name: "b", data1: "aa" },
  { name: "c", data1: "ee" },
];
exData2 = [
  { name: "a", data2: "cc" },
  { name: "b", data2: "bb" },
];
exData3 = [
  { name: "a", data3: "ee" },
  { name: "c", data3: "eee" },
];
exData4 = [
  { name: "a", data4: "ff" },
  { name: "b", data4: "cc" },
];```
</div>
</div>
</p>

<p>The end result I want is an array of merge with lodash:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>resultData = [{
    name: "b",
    data1: "aa",
    data2: "bb",
    data4: "cc",
  },
  {
    name: "c",
    data1: "ee",
    data3: "eee",
  },
  {
    name: "a",
    data2: "cc",
    data3: "eee",
    data4: "ff"
  },
];</code>```

How do I do it the most efficient/clean way using lodash? Thanks!

答:
No need for lodash!

function combine(items = []) {
  return Object.values(items.flat().reduce((a, c) => {
    a[c.name] = {...(a[c.name] || {}), ...c};
    return a;
  }, {}));
}

exData1 = [
  { name: "b", data1: "aa" },
  { name: "c", data1: "ee" },
];
exData2 = [
  { name: "a", data2: "cc" },
  { name: "b", data2: "bb" },
];
exData3 = [
  { name: "a", data3: "ee" },
  { name: "c", data3: "eee" },
];
exData4 = [
  { name: "a", data4: "ff" },
  { name: "b", data4: "cc" },
];

console.log(combine([exData1, exData2, exData3, exData4]));```

Body:
I am looking for best ways of doing this.

exData1 = [
  { name: "b", data1: "aa" },
  { name: "c", data1: "ee" },
];
exData2 = [
  { name: "a", data2: "cc" },
  { name: "b", data2: "bb" },
];
exData3 = [
  { name: "a", data3: "ee" },
  { name: "c", data3: "eee" },
];
exData4 = [
  { name: "a", data4: "ff" },
  { name: "b", data4: "cc" },
];

The end result I want is an array of merge with lodash:

resultData = [{
    name: "b",
    data1: "aa",
    data2: "bb",
    data4: "cc",
  },
  {
    name: "c",
    data1: "ee",
    data3: "eee",
  },
  {
    name: "a",
    data2: "cc",
    data3: "eee",
    data4: "ff"
  },
];

How do I do it the most efficient/clean way using lodash? Thanks!


问:
Pandas delete Column where Header is NAN
How can I drop all column with a NaN value from dataframes?

```<code>      count       bal  NaN        NaN      sum           NaN

0   10.534709  254.38   0  215490.85  -7118.52     2013-07-31
1    0.000000  135.39   0  227822.73 -10034.44     2013-08-31
2    0.000000  143.58   0  247432.23   -107.51     2013-09-30
</code>```

I have tried various versions of this:

```<code>df.drop ( '', axis = 1 )
</code>```

Thank you.

Body:
How can I drop all column with a NaN value from dataframes?

      count       bal  NaN        NaN      sum           NaN

0   10.534709  254.38   0  215490.85  -7118.52     2013-07-31
1    0.000000  135.39   0  227822.73 -10034.44     2013-08-31
2    0.000000  143.58   0  247432.23   -107.51     2013-09-30

I have tried various versions of this:

df.drop ( '', axis = 1 )

Thank you.

Body:
You can use dropna

df = df[df.columns.dropna()]
df
       count     bal       sum
0  10.534709  254.38  -7118.52
1   0.000000  135.39 -10034.44
2   0.000000  143.58   -107.51


问:
How can I hide the app name in androidstudio?
i need help how can hide app name without delete name in

string name="app_name"

like this . Thanks for the straightforward answer .

答:
Try to modify your app's AndroidManifest.xml here:

```<code><application
    android:label="@string/app_name"
    (...)
    >
</code>```

to below:

```<code><application
    android:label=""
    (...)
    >
</code>```

Thus you don't need to touch the entry in <string name="app_name">app name</string>
 in the string resource file.

Body:
Try to modify your app's AndroidManifest.xml here:

<application
    android:label="@string/app_name"
    (...)
    >

to below:

<application
    android:label=""
    (...)
    >

Thus you don't need to touch the entry in <string name="app_name">app name</string>
 in the string resource file.


问:
How to avoid Elastic IP translation to private IP when setting Cassandra listen_address for external client connection?
I am setting

listen_address: private IP (gets translated by AWS to public IP, whether I ask it to or not)
broadcast_address: public IP
rpc_address: 0.0.0.0

I'm not able to do this because of that automatic NAT'ing stuff being done by AWS Elastic IP.  Cassandra refuses to start, claiming that I need to specify an address that I can bind to (e.g. my private IP), and instead giving me the public, elastic IP as my 7000 port listen_address setting.
..but I did this.  And it translated to public anyway.

I tried dual-homing it, but I can't even talk to the private IP on the second NIC, so I'm kind of stuck.

Is there a workaround for this elastic IP translation?

Thanks!

答:
Client connections rely on rpc_address. You'll need to set the following as a starting point:

```<code>listen_address: private_ip
rpc_address: public_ip
</code>```

If nodes are distributed across regions and using Ec2MultiRegionSnitch set:

```<code>broadcast_address: public_ip
</code>```

so nodes can communicate with nodes in another region. Cheers!

Body:
Client connections rely on rpc_address. You'll need to set the following as a starting point:

listen_address: private_ip
rpc_address: public_ip

If nodes are distributed across regions and using Ec2MultiRegionSnitch set:

broadcast_address: public_ip

so nodes can communicate with nodes in another region. Cheers!


问:
DataGrid want to display NO RECORDS
In my application i am using DataGrid,i am binding dataset to that DataGrid.So if the dataset records is zero i want to display "NO ReCORDS FOUND" in my DataGrid.

Thanks in advance.

答:
There is no EmptyDataText  property in a DataGrid, so in your code-behind do something like

```<code>if (dgTest.Items.Count == 0)
{
    lblEmpty.Visible = true;
    lblEmpty.Text = "Empty";
}
</code>```

Where dgTest is the ID of the DataGrid and lblEmpty is a placeholder label.

ContentLicense: CC BY-SA 3.0

Title: DataGrid want to display NO RECORDS

Body:
There is no EmptyDataText  property in a DataGrid, so in your code-behind do something like

if (dgTest.Items.Count == 0)
{
    lblEmpty.Visible = true;
    lblEmpty.Text = "Empty";
}

Where dgTest is the ID of the DataGrid and lblEmpty is a placeholder label.


问:
Firebase user signup with email and send them password via email
I'm trying to allow users to sign up to a Firebase website using only their email and phone number.  At a later time, I would like to send them their auto-generated password via email.  Is this possible to do with Firebase Auth or Realtime Database?</p>

答:
Sure thing. You'll have to create the account through the Admin SDK, so in a trusted environment like your dev machine, a server you control, or Cloud Functions. There you call createUser(...) with the email the user entered, the a temporary password that you made up.

You could do the same client-side, but in that case the password would be determined from the client too, which wouldn't be secure.


问:
Use value retrieved from Firebase database outside of valueEventListener
I'm developing an app using Java and Firebase in android in that I an retrieving data from Firebase Database. Here is my code

```<code>databaseReference.orderByChild("email").equalTo(email).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
                    AddFaculty addFaculty = dataSnapshot1.getValue(AddFaculty.class);
                    department = addFaculty.getDepartment();
                    year = addFaculty.getYear();
                }

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
</code>```

Model class

```<code>public class AddFaculty {
    private String name;
    private String email;
    private String position;
    private String department;
    private String year;
    private String facultyId;

    public AddFaculty() {
    }

    public AddFaculty(String name, String email, String position, String department, String year, String facultyId) {
        this.name = name;
        this.email = email;
        this.position = position;
        this.department = department;
        this.year = year;
        this.facultyId = facultyId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPosition() {
        return position;
    }

    public void setPosition(String position) {
        this.position = position;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }

    public String getFacultyId() {
        return facultyId;
    }

    public void setFacultyId(String facultyId) {
        this.facultyId = facultyId;
    }
}

</code>```

Here is my problem. I want to use 'addFaculty' or department and year variable outside of the valueEventListener. I know many people asked question related to this. I tried many solutions related to this question but it didn't work.
So if you know how to achieve this it would be great help.

答:
Create an interface to access the variable

```<code>interface CallbackFaculty {
    void passFaculty(AddFaculty addFaculty);
}
</code>```

then you can create a function with the interface parameter

```<code>private void getFaculty(CallbackFaculty callbackFaculty) {
     databaseReference.orderByChild("email").equalTo(email).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
                AddFaculty addFaculty = dataSnapshot1.getValue(AddFaculty.class);
                department = addFaculty.getDepartment();
                year = addFaculty.getYear();
                callbackFaculty.passFaculty(addFaculty);
            }

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}
</code>```

to use the method

```<code>getFaculty(new CallbackFaculty {
    @Override
    public void passFaculty(AddFaculty addFaculty) {
         // here you have the access of addFaculty
         // you can try logging addFaculty to check the value
    }
});
</code>```

hope it helps you

Body:
I'm developing an app using Java and Firebase in android in that I an retrieving data from Firebase Database. Here is my code

databaseReference.orderByChild("email").equalTo(email).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
                    AddFaculty addFaculty = dataSnapshot1.getValue(AddFaculty.class);
                    department = addFaculty.getDepartment();
                    year = addFaculty.getYear();
                }

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

Model class

public class AddFaculty {
    private String name;
    private String email;
    private String position;
    private String department;
    private String year;
    private String facultyId;

    public AddFaculty() {
    }

    public AddFaculty(String name, String email, String position, String department, String year, String facultyId) {
        this.name = name;
        this.email = email;
        this.position = position;
        this.department = department;
        this.year = year;
        this.facultyId = facultyId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPosition() {
        return position;
    }

    public void setPosition(String position) {
        this.position = position;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }

    public String getFacultyId() {
        return facultyId;
    }

    public void setFacultyId(String facultyId) {
        this.facultyId = facultyId;
    }
}

Here is my problem. I want to use 'addFaculty' or department and year variable outside of the valueEventListener. I know many people asked question related to this. I tried many solutions related to this question but it didn't work.
So if you know how to achieve this it would be great help.

Body:
Create an interface to access the variable

interface CallbackFaculty {
    void passFaculty(AddFaculty addFaculty);
}

then you can create a function with the interface parameter

private void getFaculty(CallbackFaculty callbackFaculty) {
     databaseReference.orderByChild("email").equalTo(email).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
                AddFaculty addFaculty = dataSnapshot1.getValue(AddFaculty.class);
                department = addFaculty.getDepartment();
                year = addFaculty.getYear();
                callbackFaculty.passFaculty(addFaculty);
            }

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}

to use the method

getFaculty(new CallbackFaculty {
    @Override
    public void passFaculty(AddFaculty addFaculty) {
         // here you have the access of addFaculty
         // you can try logging addFaculty to check the value
    }
});

hope it helps you


问:
Blocking pipe ConnectNamedPipe does not trigger
I want to do IPC using named pipes.
Here is a test client/server that I attempted to make to communicate between two processes
Client code:

#include <iostream>
#include <Windows.h>

int main()
{
    HANDLE pipe = CreateFileA("\\\\.\\pipe\\DokiDoki", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
    if (pipe != INVALID_HANDLE_VALUE) {
        char buffer[] = "DokiDoki from the other side :P";
        DWORD bytesWritten;
        WriteFile(pipe, static_cast<LPCVOID>(buffer), sizeof(buffer), &bytesWritten, NULL);
        std::cout << "Done!\n";
        CloseHandle(pipe);
    }
    else {
        std::cout << "Could not get a handle to the pipe!\n";
        return 1;
    }
    return 0;
}
```

<p>Server code:</p>

<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <array>
#include <Windows.h>

int main()
{
    char buffer[1024];
    HANDLE pipe = CreateNamedPipeA("\\\\.\\pipe\\DokiDoki", PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, 1, sizeof(buffer), sizeof(buffer), NMPWAIT_USE_DEFAULT_WAIT, NULL);
    while (pipe != INVALID_HANDLE_VALUE) {
        if (!ConnectNamedPipe(pipe, NULL)) {
         //Setting a breakpoint here will never trigger.
            DWORD bytesRead = 0;
            while (ReadFile(pipe, static_cast<LPVOID>(buffer), sizeof(buffer) - 1, &bytesRead, NULL)) {
                std::cout << buffer << std::endl;
            }
        }
        DisconnectNamedPipe(pipe);
    }
    return 0;
}
</code>```

The program stops at ConnectNamedPipe and will not execute any other instructions, even when the client connects and writes to the pipe.
WriteFile (on the client) returns true.

答:
ConnectNamedPipe returns a nonzero value if it succeeds, which is why this wasn't working.
Changing if (!ConnectNamedPipe(pipe, NULL)) to if (ConnectNamedPipe(pipe, NULL)) seems to work fine.

Body:
I want to do IPC using named pipes.
Here is a test client/server that I attempted to make to communicate between two processes
Client code:

#include <iostream>
#include <Windows.h>

int main()
{
    HANDLE pipe = CreateFileA("\\\\.\\pipe\\DokiDoki", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
    if (pipe != INVALID_HANDLE_VALUE) {
        char buffer[] = "DokiDoki from the other side :P";
        DWORD bytesWritten;
        WriteFile(pipe, static_cast<LPCVOID>(buffer), sizeof(buffer), &bytesWritten, NULL);
        std::cout << "Done!\n";
        CloseHandle(pipe);
    }
    else {
        std::cout << "Could not get a handle to the pipe!\n";
        return 1;
    }
    return 0;
}

Server code:

#include <iostream>
#include <array>
#include <Windows.h>

int main()
{
    char buffer[1024];
    HANDLE pipe = CreateNamedPipeA("\\\\.\\pipe\\DokiDoki", PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, 1, sizeof(buffer), sizeof(buffer), NMPWAIT_USE_DEFAULT_WAIT, NULL);
    while (pipe != INVALID_HANDLE_VALUE) {
        if (!ConnectNamedPipe(pipe, NULL)) {
         //Setting a breakpoint here will never trigger.
            DWORD bytesRead = 0;
            while (ReadFile(pipe, static_cast<LPVOID>(buffer), sizeof(buffer) - 1, &bytesRead, NULL)) {
                std::cout << buffer << std::endl;
            }
        }
        DisconnectNamedPipe(pipe);
    }
    return 0;
}

The program stops at ConnectNamedPipe and will not execute any other instructions, even when the client connects and writes to the pipe.
WriteFile (on the client) returns true.


问:
Access and disable ToolStripItems (ToolStripButtons, ToolStripMenuItems) using their names
I would like to disable UI elements (Controls, Components etc.) which names are stored in a database.

My code works for Controls, but I would like to access (to disable them) ToolStripItems such as ToolStripButtons, ToolStripMenuItems etc..

This is my current code:

```<code>Dim df_command As New SqlCommand("select * from treftab where ref_data = 'INTERVENTION' and ref_code  = '0'", sfacon)
Dim df_reader As SqlDataReader = df_command.ExecuteReader

If df_reader.HasRows Then
    While df_reader.Read
        Dim reftext As String = df_reader("ref_text")
        Dim someVariable As Control = Nothing
        Dim SearchedControls = Me.Controls.Find(key:=reftext, searchAllChildren:=True)
        someVariable = SearchedControls(0)
        someVariable.Enabled = False
    End While
End If
</code>```

答:
You cannot find ToolStrip or MenuStrip Items in the Form.Control collection because those UI elements are not Controls but a special breed of Components.

While ToolStrip and MenuStrip both inherit from Control, ToolStripMenuItems inherit from Component and ToolStripItem (the latter provides the Enabled property).

You could build a Dictionary(Of String, Boolean) containing the names of the UI elements to enable or disable, based on values stored in the data source you have.

The use a method that reads the current Form's Fields, loop the KeyValuePairs in the Dictionary to find elements matching the Dictionary Keys and sets the Enable property based on the corresponding Values.

For example, to disabled all the elements in the collection:

(I assume you have stored all different names per each Form in your data source)

```<code>Dim names As New Dictionary(Of String, Boolean)()

' [...]
While df_reader.Read()
    names.Add(df_reader("ref_text").ToString(), False)
End While

EnableDisableFormElements(Me, names)
</code>```

The method use Type.GetFields() to find all non public instance fields of the specified Form, the FieldInfo.GetValue() to get the instance of a UI element represented by that Field.

It then determines whether the UI element is a Control or a ToolStripItem (UI elements that inherit from these base classes have an Enabled property) and sets it using the Value stored in the Dictionary.

TrimStart("_"c) is there because VB.Net has the (IMO) bad habit to add an underscore to these Field names. It doesn't happen using C#.

```<code>Imports System.Reflection
Imports System.Windows.Forms

Private Sub EnableDisableFormElements(parentForm As Form, elementNames As Dictionary(Of String, Boolean))
    Dim allFields = parentForm.GetType().GetFields(BindingFlags.NonPublic Or BindingFlags.Instance)

    For Each element As KeyValuePair(Of String, Boolean) In elementNames
        Dim searchElement = allFields.FirstOrDefault(
        Function(f) f.Name.TrimStart("_"c).Equals(element.Key)).GetValue(parentForm)

        If searchElement IsNot Nothing Then
            If TypeOf searchElement Is Control Then
                DirectCast(searchElement, Control).Enabled = element.Value
            ElseIf TypeOf searchElement Is ToolStripItem Then
                DirectCast(searchElement, ToolStripItem).Enabled = element.Value
            End If
        End If
    Next
End Sub
</code>```

Body:
I would like to disable UI elements (Controls, Components etc.) which names are stored in a database.

My code works for Controls, but I would like to access (to disable them) ToolStripItems such as ToolStripButtons, ToolStripMenuItems etc..

This is my current code:

Dim df_command As New SqlCommand("select * from treftab where ref_data = 'INTERVENTION' and ref_code  = '0'", sfacon)
Dim df_reader As SqlDataReader = df_command.ExecuteReader

If df_reader.HasRows Then
    While df_reader.Read
        Dim reftext As String = df_reader("ref_text")
        Dim someVariable As Control = Nothing
        Dim SearchedControls = Me.Controls.Find(key:=reftext, searchAllChildren:=True)
        someVariable = SearchedControls(0)
        someVariable.Enabled = False
    End While
End If

Body:
You cannot find ToolStrip or MenuStrip Items in the Form.Control collection because those UI elements are not Controls but a special breed of Components.

While ToolStrip and MenuStrip both inherit from Control, ToolStripMenuItems inherit from Component and ToolStripItem (the latter provides the Enabled property).

You could build a Dictionary(Of String, Boolean) containing the names of the UI elements to enable or disable, based on values stored in the data source you have.

The use a method that reads the current Form's Fields, loop the KeyValuePairs in the Dictionary to find elements matching the Dictionary Keys and sets the Enable property based on the corresponding Values.

For example, to disabled all the elements in the collection:

(I assume you have stored all different names per each Form in your data source)

Dim names As New Dictionary(Of String, Boolean)()

' [...]
While df_reader.Read()
    names.Add(df_reader("ref_text").ToString(), False)
End While

EnableDisableFormElements(Me, names)

The method use Type.GetFields() to find all non public instance fields of the specified Form, the FieldInfo.GetValue() to get the instance of a UI element represented by that Field.

It then determines whether the UI element is a Control or a ToolStripItem (UI elements that inherit from these base classes have an Enabled property) and sets it using the Value stored in the Dictionary.

TrimStart("_"c) is there because VB.Net has the (IMO) bad habit to add an underscore to these Field names. It doesn't happen using C#.

Imports System.Reflection
Imports System.Windows.Forms

Private Sub EnableDisableFormElements(parentForm As Form, elementNames As Dictionary(Of String, Boolean))
    Dim allFields = parentForm.GetType().GetFields(BindingFlags.NonPublic Or BindingFlags.Instance)

    For Each element As KeyValuePair(Of String, Boolean) In elementNames
        Dim searchElement = allFields.FirstOrDefault(
        Function(f) f.Name.TrimStart("_"c).Equals(element.Key)).GetValue(parentForm)

        If searchElement IsNot Nothing Then
            If TypeOf searchElement Is Control Then
                DirectCast(searchElement, Control).Enabled = element.Value
            ElseIf TypeOf searchElement Is ToolStripItem Then
                DirectCast(searchElement, ToolStripItem).Enabled = element.Value
            End If
        End If
    Next
End Sub


问:
Laravel 5.7, How to decrypt or view Hash Password in Laravel?
I stored my password Hash method in laravel 5.7

```<code>'password' => Hash::make($request->newPassword)
</code>```

I need to view original password so can you help any one?

答:
No you cannot decrypt hashed passwords. You can only attempt brute force checking.

You can check if a password matches the hash by using

```<code>Hash::check('plain-text', $hashedPassword);
</code>```

This function will return true if the passwords match, else false. You can get more info about hashing from laravel docs

There should never be a case of needing to view your password, because that would be a big flaw. A lot of users use same password on multiple sites so being able to view password will be a huge security risk. If someone gains unauthorised access to your database, then just imagine if they could see passwords, accounts on multiple sites could get could get compromised if same password is used.

If you forget password, then reset it. No harm done.

Body:
I stored my password Hash method in laravel 5.7

'password' => Hash::make($request->newPassword)

I need to view original password so can you help any one?

Body:
No you cannot decrypt hashed passwords. You can only attempt brute force checking.

You can check if a password matches the hash by using

Hash::check('plain-text', $hashedPassword);

This function will return true if the passwords match, else false. You can get more info about hashing from laravel docs

There should never be a case of needing to view your password, because that would be a big flaw. A lot of users use same password on multiple sites so being able to view password will be a huge security risk. If someone gains unauthorised access to your database, then just imagine if they could see passwords, accounts on multiple sites could get could get compromised if same password is used.

If you forget password, then reset it. No harm done.


问:
Cannot access android.arch.lifecycle.LifecycleOwner on fragment?
This happens when i extend from an abstract base fragment like so:

```<code>public abstract class BaseFragment<T extends BasePresenter, E extends BaseModel> extends Fragment {
....
}
</code>```

, but the app still build without any errors. below is my build.gradle config:

```<code>android {
    compileSdkVersion 27
    buildToolsVersion '26.0.2'
    defaultConfig
    {
        multiDexEnabled true
        minSdkVersion 21
        targetSdkVersion 27
    }
}
</code>```

答:
Add following line to gradle</p>

```<code>implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
</code>```

Body:
This happens when i extend from an abstract base fragment like so:

public abstract class BaseFragment<T extends BasePresenter, E extends BaseModel> extends Fragment {
....
}

, but the app still build without any errors. below is my build.gradle config:

android {
    compileSdkVersion 27
    buildToolsVersion '26.0.2'
    defaultConfig
    {
        multiDexEnabled true
        minSdkVersion 21
        targetSdkVersion 27
    }
}

Body:
Add following line to gradle

implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'


问:
UITableView SelectAll - willDeselectRowAtIndexPath alternative
I built a multi-selection table, I did that using willSelectRowAtIndexPath and willDeselectRowAtIndexPath. It is working fine. Now I want to programatically selectALL or Select None. Is there a way to call

```<code>[tableView selectRowAtIndexPath: [NSIndexPath indexPathForRow:i inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
</code>```

without having the currently selected row unselected? I read in documentation, this method does not call delegate's willDeselectRowAtIndexPath.

Here's all code to allow multiple selection. The problem is now that I cannot select programmatically without deselecting previous.

```<code>- (NSIndexPath *)tableView:(UITableView *)aTableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    NSDictionary* friend = [friendsData objectAtIndex:[indexPath row]];
    if (![selectedIndexes containsObject:friend]) {
        [selectedIndexes addObject:friend];

    }
    else {
        [selectedIndexes removeObject:friend];
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
        return nil;
    }
    return indexPath;
}

- (NSIndexPath *)tableView:(UITableView *)tableView willDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary* friend = [friendsData objectAtIndex:[indexPath row]];
    if (![selectedIndexes containsObject:friend]) {
         return indexPath;
     }
    // do not select so we can have multiple select
    return nil;
}
</code>```

答:
You'll have to change your data source to reflect the select all or select none, then refresh the rows in question to update them to their new status.

I can't post any specific code because it really depends on how you've set up your multi-selection.

Edit

It seems that you can select all by setting selectedIndexes to friendsData and select none by clearing the contents of selectedIndexes.

Select All:

```<code>[selectedIndexes setArray: friendsData];
</code>```

Select None:

```<code>[selectedIndexes removeAllObjects];
</code>```

Then you can reload your table view. If you want it to be instant, execute [tableView reloadData] otherwise you can use the reload methods with animation.

Body:
I built a multi-selection table, I did that using willSelectRowAtIndexPath and willDeselectRowAtIndexPath. It is working fine. Now I want to programatically selectALL or Select None. Is there a way to call

[tableView selectRowAtIndexPath: [NSIndexPath indexPathForRow:i inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];

without having the currently selected row unselected? I read in documentation, this method does not call delegate's willDeselectRowAtIndexPath.

Here's all code to allow multiple selection. The problem is now that I cannot select programmatically without deselecting previous.

- (NSIndexPath *)tableView:(UITableView *)aTableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    NSDictionary* friend = [friendsData objectAtIndex:[indexPath row]];
    if (![selectedIndexes containsObject:friend]) {
        [selectedIndexes addObject:friend];

    }
    else {
        [selectedIndexes removeObject:friend];
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
        return nil;
    }
    return indexPath;
}

- (NSIndexPath *)tableView:(UITableView *)tableView willDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary* friend = [friendsData objectAtIndex:[indexPath row]];
    if (![selectedIndexes containsObject:friend]) {
         return indexPath;
     }
    // do not select so we can have multiple select
    return nil;
}

Body:
You'll have to change your data source to reflect the select all or select none, then refresh the rows in question to update them to their new status.

I can't post any specific code because it really depends on how you've set up your multi-selection.

Edit

It seems that you can select all by setting selectedIndexes to friendsData and select none by clearing the contents of selectedIndexes.

Select All:

[selectedIndexes setArray: friendsData];

Select None:

[selectedIndexes removeAllObjects];

Then you can reload your table view. If you want it to be instant, execute [tableView reloadData] otherwise you can use the reload methods with animation.


问:
How to filter table rows in nodejs using db queries?
I am using nest js framework for my demo application. In my demo application I have an entity Category which has two columns (id, description). description is jsonb type.

```<code>export class Category extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ type: 'jsonb' })
  description;
}
</code>```

I inserted some data in my table.

Now I want to filter that data and only show those rows which have name = test.

Currently I'm using the code shown here, which returns all rows. But I need only the rows which have name equals to test. Currently there is only one row

```<code>@Get('/app')
  async getApp(): Promise<Category[]> {
    return this.categoryRepository.find({});
  }
</code>```

Here is my full code:
https://codesandbox.io/s/nest-nhqyb?file=/src/app.controller.ts:568-670

You can see filter result like

https://nhqyb-5000.sse.codesandbox.io/app

答:
According to this issue, it's not possible unless you are writing raw SQL and using database specific syntax.

In Postgres, it would look something like

SELECT *
FROM Category cat
WHERE EXISTS (
  SELECT FROM jsonb_each(cat.description) desc
   WHERE  desc.value->>'name' ILIKE 'test'
   );
```

Lots more discussion and in depth answers over here

Body:
I am using nest js framework for my demo application. In my demo application I have an entity Category which has two columns (id, description). description is jsonb type.

export class Category extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ type: 'jsonb' })
  description;
}

I inserted some data in my table.

Now I want to filter that data and only show those rows which have name = test.

Currently I'm using the code shown here, which returns all rows. But I need only the rows which have name equals to test. Currently there is only one row

@Get('/app')
  async getApp(): Promise<Category[]> {
    return this.categoryRepository.find({});
  }

Here is my full code:
https://codesandbox.io/s/nest-nhqyb?file=/src/app.controller.ts:568-670

You can see filter result like

https://nhqyb-5000.sse.codesandbox.io/app

Body:
According to this issue, it's not possible unless you are writing raw SQL and using database specific syntax.

In Postgres, it would look something like

SELECT *
FROM Category cat
WHERE EXISTS (
  SELECT FROM jsonb_each(cat.description) desc
   WHERE  desc.value->>'name' ILIKE 'test'
   );

Lots more discussion and in depth answers over here


问:
Trying to make a list case insensitive in discord.py (python)
I am trying to make a bad word filter for a bot that I am making for my friend's server, but, the list is case sensitive. How do I fix this?

```<code>@client.event
async def on_message(message):
   author = message.author
    content = message.content
    channel = message.channel
    log = client.get_channel(log channel)
    bad_words=["bad","word","yellow"]
    if any(bad_word in content for bad_word in bad_words):
        embed = discord.Embed(title="Bad word detected!", color=discord.Color.red())
        embed.add_field(name=f"{author.display_name}, you have said a forbidden word!", value="You
        have been sent to Jail!")
        embed2 = discord.Embed(title=f"Bad word sent by {author} in #{channel}.",
        color=discord.Color.red())
        embed2.add_field(name="They said:", value=f"{author.display_name}: {content}")
        await message.delete()
        await author.add_roles(discord.utils.get(author.guild.roles, name="jail"))
        await channel.send(embed=embed)
        await log.send(embed=embed2)
    await client.process_commands(message)
</code>```

答:
Make the content lowercase before you check with it</p>

```<code>content = message.content.lower()
</code>```

Body:
I am trying to make a bad word filter for a bot that I am making for my friend's server, but, the list is case sensitive. How do I fix this?

@client.event
async def on_message(message):
   author = message.author
    content = message.content
    channel = message.channel
    log = client.get_channel(log channel)
    bad_words=["bad","word","yellow"]
    if any(bad_word in content for bad_word in bad_words):
        embed = discord.Embed(title="Bad word detected!", color=discord.Color.red())
        embed.add_field(name=f"{author.display_name}, you have said a forbidden word!", value="You
        have been sent to Jail!")
        embed2 = discord.Embed(title=f"Bad word sent by {author} in #{channel}.",
        color=discord.Color.red())
        embed2.add_field(name="They said:", value=f"{author.display_name}: {content}")
        await message.delete()
        await author.add_roles(discord.utils.get(author.guild.roles, name="jail"))
        await channel.send(embed=embed)
        await log.send(embed=embed2)
    await client.process_commands(message)

Body:
Make the content lowercase before you check with it

content = message.content.lower()


问:
ECDSA Algorithms not available in Java with jlink
I'm writing a Java 14 application that should verify some signatures with algorithms such as SHA256withECDSA, SHA384withECDSA and SHA512withECDSA, but I'm experiencing a particular side-effect of jlink:

when running the application with the Standard JDK/JRE 14 runtime, the algorithms are showing up (SunEC is loaded successfully)

when running the application with an optimized version of the JRE runtime, using jlink AND including the jdk.crypto.ec module, SunEC isn't loaded at all and the algorithms aren't available

I'm aware of this Ticket in the OpenJDK bug tracker, but I cannot understand why there's a different behaviour in the optimized jlink version.

In the runtime folder generated by jlink, there's also the libsunec.so.

I'm printing out the available algorithms with this SO snippet and I obtain the following output:

```<code>MD2withRSA
MD5andSHA1withRSA
MD5withRSA
NONEwithDSA
NONEwithDSAinP1363Format
RSASSA-PSS
SHA1withDSA
SHA1withDSAinP1363Format
SHA1withRSA
SHA224withDSA
SHA224withDSAinP1363Format
SHA224withRSA
SHA256withDSA
SHA256withDSAinP1363Format
SHA256withRSA
SHA384withRSA
SHA512/224withRSA
SHA512/256withRSA
SHA512withRSA
</code>```

For same and related reasons, the verification of signed Jars with policy files doesn't work.

Could anyone explain/point me what should I look for?

EDIT: the jlink runtime is built with the following arguments:

```<code>jlink --strip-debug \
      --strip-native-commands \
      --bind-services \
      --no-header-files \
      --no-man-pages \
      --compress=2 \
      --module-path ${JAVA_HOME}/jmods \
      --add-modules java.desktop,java.smartcardio,java.management,java.sql,java.logging,java.net.http,java.xml.crypto,jdk.crypto.ec \
      --output jlink-runtime
</code>```

答:
This is an official bug of the JDK now.

There is currently no support for signed JARs on the application module path that are signed with EC certs. The reason is that module path is scan early during VM startup, long before code outside of java.base can execute. JDK-8215932 tracks the same issue.

Body:
I'm writing a Java 14 application that should verify some signatures with algorithms such as SHA256withECDSA, SHA384withECDSA and SHA512withECDSA, but I'm experiencing a particular side-effect of jlink:

when running the application with the Standard JDK/JRE 14 runtime, the algorithms are showing up (SunEC is loaded successfully)

when running the application with an optimized version of the JRE runtime, using jlink AND including the jdk.crypto.ec module, SunEC isn't loaded at all and the algorithms aren't available

I'm aware of this Ticket in the OpenJDK bug tracker, but I cannot understand why there's a different behaviour in the optimized jlink version.

In the runtime folder generated by jlink, there's also the libsunec.so.

I'm printing out the available algorithms with this SO snippet and I obtain the following output:

MD2withRSA
MD5andSHA1withRSA
MD5withRSA
NONEwithDSA
NONEwithDSAinP1363Format
RSASSA-PSS
SHA1withDSA
SHA1withDSAinP1363Format
SHA1withRSA
SHA224withDSA
SHA224withDSAinP1363Format
SHA224withRSA
SHA256withDSA
SHA256withDSAinP1363Format
SHA256withRSA
SHA384withRSA
SHA512/224withRSA
SHA512/256withRSA
SHA512withRSA

For same and related reasons, the verification of signed Jars with policy files doesn't work.

Could anyone explain/point me what should I look for?

EDIT: the jlink runtime is built with the following arguments:

jlink --strip-debug \
      --strip-native-commands \
      --bind-services \
      --no-header-files \
      --no-man-pages \
      --compress=2 \
      --module-path ${JAVA_HOME}/jmods \
      --add-modules java.desktop,java.smartcardio,java.management,java.sql,java.logging,java.net.http,java.xml.crypto,jdk.crypto.ec \
      --output jlink-runtime


问:
How to convert List<NameValuePair> into a List<Map.Entry<String, String>>?
I'm capturing parameters from a request url using com.apache.http.NameValuePair which basically store those params in a List<NameValuePair>. To do certain checks and verifications on those params, I need to convert that list into a List<Map.Entry<String, String>>. Is there a way to do this conversion?

something like this:

http://127.0.0.1:9898/v3/{project_id}/eip/publicips?fields=id&fields=owner

from How to convert List<NameValuePair> into a hashMap<String, String>?

```<code>Map<String, String> mapped = list.stream().collect(
        Collectors.toMap(NameValuePair::getName, NameValuePair::getValue));
</code>```

It is not work for me. because there are many fields key.

答:
You can convert each NameValuePair into Map.Entry and then collect them into List

```<code>List<Map.Entry<String, String>> entries = list.stream()
                                              .map(n->new AbstractMap.SimpleEntry<String, String>(n.getName(), n.getValue())
                                              .collect(Collectors.toList());
</code>```

Body:
I'm capturing parameters from a request url using com.apache.http.NameValuePair which basically store those params in a List<NameValuePair>. To do certain checks and verifications on those params, I need to convert that list into a List<Map.Entry<String, String>>. Is there a way to do this conversion?

something like this:

http://127.0.0.1:9898/v3/{project_id}/eip/publicips?fields=id&fields=owner

from How to convert List<NameValuePair> into a hashMap<String, String>?

Map<String, String> mapped = list.stream().collect(
        Collectors.toMap(NameValuePair::getName, NameValuePair::getValue));

It is not work for me. because there are many fields key.

Body:
You can convert each NameValuePair into Map.Entry and then collect them into List

List<Map.Entry<String, String>> entries = list.stream()
                                              .map(n->new AbstractMap.SimpleEntry<String, String>(n.getName(), n.getValue())
                                              .collect(Collectors.toList());


问:
AddSingleton<>() vs AddSingleton()
I'm implementing dependency injection in my project. I've come across two ways to add a singleton service -

services.AddSingleton(new MyCustomService())
```

<p>and </p>

<pre class="lang-csh prettyprint-override"><code>services.AddSingleton<MyCustomService>()
</code>```

Both methods seem to work. What's the difference between these two methods, and which one should I be using?

答:
Short answer: explicit loading of a service versus using generics to pull from injection via configuration.

In the first instance, you are adding a SingletonService you are instantiating yourself. In the second, you are asking dependency injection to load up MyCustomService based on configuration. The latter is useful when you might have different versions of MyCustomService for different configurations of the application.

Another way of looking at it. The first is loading a singleton and fails if it is not. The second is using generics to validate the type of service and will blow up if there are none specified in configuration.

Title: AddSingleton<>() vs AddSingleton()

Body:
I'm implementing dependency injection in my project. I've come across two ways to add a singleton service -

services.AddSingleton(new MyCustomService())

and

services.AddSingleton<MyCustomService>()

Both methods seem to work. What's the difference between these two methods, and which one should I be using?


问:
Use Dash with websockets
What is the best way to use Dash with Websockets to build a real-time dashboard ? I would like to update a graph everytime a message is received but the only thing I've found is calling the callback every x seconds like the example below.

```<code>import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_daq as daq
from dash.dependencies import Input, Output
import plotly
import plotly.graph_objs as go
from websocket import create_connection
from tinydb import TinyDB, Query
import json
import ssl

# Setting up the websocket and the necessary web handles
ws = create_connection(address, sslopt={"cert_reqs": ssl.CERT_NONE})

app = dash.Dash(__name__)
app.layout = html.Div(
    [
        dcc.Graph(id='live-graph', animate=True),
        dcc.Interval(
            id='graph-update',
            interval=1*1000,
            n_intervals=0)
    ]
)

@app.callback(Output('live-graph', 'figure'),
              [Input('graph-update', 'n_intervals')])

def update_graph_live(n):

    message = ws.recv()
    x=message.get('data1')
    y=message.get('data2')
        .....

    fig = go.Figure(
        data = [go.Bar(x=x,y=y)],
        layout=go.Layout(
            title=go.layout.Title(text="Bar Chart")
            )
        )
    )

    return fig

if __name__ == '__main__':
    app.run_server(debug=True)
</code>```

Is there a way to trigger the callback everytime a message is received (maybe storing them in a database before) ?

答: I had two separate servers: one for dash, the other one as a socket server. They are running on different ports. On receiving a message, I edited a common json file to share information to dash's callback. That's how I did it.</p>

Title: Use Dash with websockets

Body:
What is the best way to use Dash with Websockets to build a real-time dashboard ? I would like to update a graph everytime a message is received but the only thing I've found is calling the callback every x seconds like the example below.

import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_daq as daq
from dash.dependencies import Input, Output
import plotly
import plotly.graph_objs as go
from websocket import create_connection
from tinydb import TinyDB, Query
import json
import ssl

# Setting up the websocket and the necessary web handles
ws = create_connection(address, sslopt={"cert_reqs": ssl.CERT_NONE})

app = dash.Dash(__name__)
app.layout = html.Div(
    [
        dcc.Graph(id='live-graph', animate=True),
        dcc.Interval(
            id='graph-update',
            interval=1*1000,
            n_intervals=0)
    ]
)

@app.callback(Output('live-graph', 'figure'),
              [Input('graph-update', 'n_intervals')])

def update_graph_live(n):

    message = ws.recv()
    x=message.get('data1')
    y=message.get('data2')
        .....

    fig = go.Figure(
        data = [go.Bar(x=x,y=y)],
        layout=go.Layout(
            title=go.layout.Title(text="Bar Chart")
            )
        )
    )

    return fig

if __name__ == '__main__':
    app.run_server(debug=True)

Is there a way to trigger the callback everytime a message is received (maybe storing them in a database before) ?


问:
How to get post values from first page to third page ,as post
i have 3 pages

Page1.php,page2.php,page3.php

In page1.php, i have some hidden values, for example 'name'

After the submission of page1.php, it will go to page2.

Then after some process in page2.php, it should need to automatically submit to page3.php(where page3.php is in another sever)

Finally,when i print the $_POST  variables in page3.php, i need to get the variable 'name'

答:
There are several solutions:

PHP sessions

cookies

passing arguments as GET/POST parameters

storing data in database

In simple cases passing arguments as GET parameter page2.php?name=... or using hidden form field is the best solution


问:
Retrieving Laravel notification from database to blade
So i want to retrieve data from Notifications Table in laravel.

but what i am trying to do is showing notifications on public it means without an auth so it would show in here

notification example

if i do this it throws an error as undefined variable

```<code>@foreach( $notifications as $notif)
       lob {{ $notif->type }}
@endforeach
</code>```

and then i tried to count the unreadNotifications but it throws an error of

Trying to get property 'unreadNotifications' of non-object

what should i do in here? because after i search about this,
the solution always use auth()->user()->notifications() meanwhile what i am trying to do is showing notification in home.blade.php without any auth

Regards.

答:
It is failing because of the reason that there isn't any logged in user.

auth()->user() grabs the logged in user if there is any, otherwise it returns null.

What you have to do here is to get the user for which you want the notifications and then make call to notifications relation on it. For example: for grabbing notifications for user id 1, it would be \App\User::find(1)->notifications

Body:
So i want to retrieve data from Notifications Table in laravel.

but what i am trying to do is showing notifications on public it means without an auth so it would show in here

notification example

if i do this it throws an error as undefined variable

@foreach( $notifications as $notif)
       lob {{ $notif->type }}
@endforeach

and then i tried to count the unreadNotifications but it throws an error of

Trying to get property 'unreadNotifications' of non-object

what should i do in here? because after i search about this,
the solution always use auth()->user()->notifications() meanwhile what i am trying to do is showing notification in home.blade.php without any auth

Regards.


问:
BeautifulSoup not scraping anything from webpage
I am working on a web scraping project. In this project, I am trying to scrape all the product links on a particular page in amazon. this process will repeat as many times as required and scrape multiple pages from amazon.

Here is my code so far

```<code>def scrape_pages(headers, product, num_of_pages):

    product_links = []

    for page in range(1, num_of_pages+1):

        url = f'https://www.amazon.com/s?k={product}&page={page}&ref=nb_sb_noss'
        print(url)

        response = requests.get(url, headers=headers)
        soup = BeautifulSoup(response.content, features="lxml")
        data = soup.findAll('h2', attrs={'class':'a-size-mini'})

        for i in data:
            links = i.findAll('a')

            for a in links:
                product_links.append(f"https://www.amazon.com{a['href']}")
        print('TOTAL NUMBER OF PRODUCTS LINKS SCRAPPED: ', len(product_links))

    return product_links
</code>```

In the above code, I am trying to scrape links inside all h2 tags in a page. I am using user-agent to make the scraping possible.

My problem is this code does not run all the time. Some times it scrapes some of the links and some times it does not scrape any links.

Each page in amazon has around 48 products listed. If I were to scrape 5 pages then the product_links list should hold somewhere around 240 links in it. but I have done multiple tests and it is always less than 200 and sometimes it is 0.

I want to know what I am doing wrong

FYI this is the user-agent I am using

```<code>{'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'}
</code>```

答:
I am not sure about this but as many online retailers, such as Amazon put anti-bot software throughout the websites which might stop your crawler. These retailers will shut down any requests from Beautiful Soup as it knows that it does not come from legitimate browsers. You can use Selenium instead. Or put some constraints in your code such as

```<code>time.sleep(1)

</code>```

to pause your code for a second so that you are not spamming the website with requests.

Body:
I am working on a web scraping project. In this project, I am trying to scrape all the product links on a particular page in amazon. this process will repeat as many times as required and scrape multiple pages from amazon.

Here is my code so far

def scrape_pages(headers, product, num_of_pages):

    product_links = []

    for page in range(1, num_of_pages+1):

        url = f'https://www.amazon.com/s?k={product}&page={page}&ref=nb_sb_noss'
        print(url)

        response = requests.get(url, headers=headers)
        soup = BeautifulSoup(response.content, features="lxml")
        data = soup.findAll('h2', attrs={'class':'a-size-mini'})

        for i in data:
            links = i.findAll('a')

            for a in links:
                product_links.append(f"https://www.amazon.com{a['href']}")
        print('TOTAL NUMBER OF PRODUCTS LINKS SCRAPPED: ', len(product_links))

    return product_links

In the above code, I am trying to scrape links inside all h2 tags in a page. I am using user-agent to make the scraping possible.

My problem is this code does not run all the time. Some times it scrapes some of the links and some times it does not scrape any links.

Each page in amazon has around 48 products listed. If I were to scrape 5 pages then the product_links list should hold somewhere around 240 links in it. but I have done multiple tests and it is always less than 200 and sometimes it is 0.

I want to know what I am doing wrong

FYI this is the user-agent I am using

{'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'}

Body:
I am not sure about this but as many online retailers, such as Amazon put anti-bot software throughout the websites which might stop your crawler. These retailers will shut down any requests from Beautiful Soup as it knows that it does not come from legitimate browsers. You can use Selenium instead. Or put some constraints in your code such as

time.sleep(1)

to pause your code for a second so that you are not spamming the website with requests.


问:
What is the parameter argument used for in Alamofire request? I got results without specifying parameters
I used Alamofire to network in Swift, and didn't supplement information for the parameter argument within the request. I got the results back fine. Does anyone know what the parameter argument is for and when I should supplement information for it?</p>

```<code>    let editedFlowerName = flowerName.replacingOccurrences(of: " ", with: "%20", options: .literal, range: nil)
    let url = "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&exintro&explaintext&redirects=1&indexpageids"
    guard let wikiURL = URL(string: "\(url)&titles=\(editedFlowerName)") else {fatalError("Error creating url")}
    //print(wikiURL)
    AF.request(wikiURL, method: .get).validate()
      .responseJSON { (response) in
          let json = JSON(value)
          print(json)
        }
</code>```

答:
Parameters is not mandatory unless you want to send some data along with the request. When using default encoding, the requests GET, DELETE and HEAD encodes the parameters as query string and adds it to the URL. However, for all other requests - POST, PATCH, PUT, OPTIONS, CONNECT - the parameters are encoded as query string and sent as the body of the request.

You can change this behavior by changing the encoding type.

For example, by setting the encoding to queryString you can set or append the encoded query string result to existing query string.

```<code>URLEncoding(destination: .queryString)
</code>```

Similarly, you can set encoded query string result as the HTTP body of the URL request for all requests using httpBody.

```<code>URLEncoding(destination: .httpBody)
</code>```

Body:
I used Alamofire to network in Swift, and didn't supplement information for the parameter argument within the request. I got the results back fine. Does anyone know what the parameter argument is for and when I should supplement information for it?

    let editedFlowerName = flowerName.replacingOccurrences(of: " ", with: "%20", options: .literal, range: nil)
    let url = "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&exintro&explaintext&redirects=1&indexpageids"
    guard let wikiURL = URL(string: "\(url)&titles=\(editedFlowerName)") else {fatalError("Error creating url")}
    //print(wikiURL)
    AF.request(wikiURL, method: .get).validate()
      .responseJSON { (response) in
          let json = JSON(value)
          print(json)
        }

Body:
Parameters is not mandatory unless you want to send some data along with the request. When using default encoding, the requests GET, DELETE and HEAD encodes the parameters as query string and adds it to the URL. However, for all other requests - POST, PATCH, PUT, OPTIONS, CONNECT - the parameters are encoded as query string and sent as the body of the request.

You can change this behavior by changing the encoding type.

For example, by setting the encoding to queryString you can set or append the encoded query string result to existing query string.

URLEncoding(destination: .queryString)

Similarly, you can set encoded query string result as the HTTP body of the URL request for all requests using httpBody.

URLEncoding(destination: .httpBody)


问:
Errors by installing Python modules Pygame and Pygame Zero
I've succesfully installed Python version 3.8.1 and also PIP.

After that i want to install Pygame and Pygame Zero with the commands
pip install pygame
or
pip install pgzero

But I get the following error:

```<code>C:\>pip install pygame
Traceback (most recent call last):
  File "c:\program files\python38\lib\runpy.py", line 193, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "c:\program files\python38\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "C:\Program Files\Python38\Scripts\pip.exe\__main__.py", line 9, in <module>
TypeError: 'module' object is not callable
</code>```

Also with the --user command it doesn't succeed:

```<code>pip install pygame --user
</code>```

or

```<code>pip install pgzero --user
</code>```

What am I doing wrong here now?

答:
I also got that problem long ago.

You can try this:

pip uninstall pygame
pip uninstall pgzrun
```

<p>then download it by: </p>

<pre class="lang-sh prettyprint-override"><code>pip install pygame
pip install pgzrun
</code>```

Body:
I've succesfully installed Python version 3.8.1 and also PIP.

After that i want to install Pygame and Pygame Zero with the commands
pip install pygame
or
pip install pgzero

But I get the following error:

C:\>pip install pygame
Traceback (most recent call last):
  File "c:\program files\python38\lib\runpy.py", line 193, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "c:\program files\python38\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "C:\Program Files\Python38\Scripts\pip.exe\__main__.py", line 9, in <module>
TypeError: 'module' object is not callable

Also with the --user command it doesn't succeed:

pip install pygame --user

or

pip install pgzero --user

What am I doing wrong here now?

Body:
I also got that problem long ago.

You can try this:

pip uninstall pygame
pip uninstall pgzrun

then download it by:

pip install pygame
pip install pgzrun


问:
Numpy Lambda Function Not Working as Expected
market['AAPL'] is a dataframe with Apple's daily stock return

I noticed that:

```<code>market['AAPL'].apply(lambda x: np.exp(x))

market['AAPL'].apply(lambda x: np.cumprod(np.exp(x)))
</code>```

Both give the same results
Why is the np.cumprod not working?

答:
You probably mean to apply the cumulative product across the AAPL column. Your current attempt doesn't work, because .apply works per row. As a result, np.cumprod is called each time for a single number, not for an array of numbers.

Instead, try something like this:

```<code>import pandas as pd
import numpy as np

aapl = {"AAPL": np.linspace(1, 2, 10)}
df = pd.DataFrame(appl)
# Calculate exp for the column, then calculate
# the cumulative product over the column
df['cum-AAPL'] = np.exp(df['AAPL']).cumprod())
</code>```

Body:
market['AAPL'] is a dataframe with Apple's daily stock return

I noticed that:

market['AAPL'].apply(lambda x: np.exp(x))

market['AAPL'].apply(lambda x: np.cumprod(np.exp(x)))

Both give the same results
Why is the np.cumprod not working?

Body:
You probably mean to apply the cumulative product across the AAPL column. Your current attempt doesn't work, because .apply works per row. As a result, np.cumprod is called each time for a single number, not for an array of numbers.

Instead, try something like this:

import pandas as pd
import numpy as np

aapl = {"AAPL": np.linspace(1, 2, 10)}
df = pd.DataFrame(appl)
# Calculate exp for the column, then calculate
# the cumulative product over the column
df['cum-AAPL'] = np.exp(df['AAPL']).cumprod())


问:
JsonSerialize graphQLResponse
```<code>using var graphQLClient = new GraphQLHttpClient(local, new NewtonsoftJsonSerializer());
var request = new GraphQLRequest{...}

var graphQLResponse = await graphQLClient.SendQueryAsync<ValueResponse>(request);
return System.Text.Json.JsonSerializer.Serialize(graphQLResponse, new JsonSerializerOptions { WriteIndented = true });
</code>```

return "abc" for english text field,

and "\u0422\u0435\u043A\u0443\u0449\u0438\u0439 \u0422\u04201" for russian text field

please tell me how to set encoding

答:
```<code>JsonSerializerOptions jso = new JsonSerializerOptions();
jso.Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping;

var graphQLResponse = await graphQLClient.SendQueryAsync<ValueResponse>(request);

return System.Text.Json.JsonSerializer.Serialize(graphQLResponse, jso);
</code>```

Title: JsonSerialize graphQLResponse

Body:
using var graphQLClient = new GraphQLHttpClient(local, new NewtonsoftJsonSerializer());
var request = new GraphQLRequest{...}

var graphQLResponse = await graphQLClient.SendQueryAsync<ValueResponse>(request);
return System.Text.Json.JsonSerializer.Serialize(graphQLResponse, new JsonSerializerOptions { WriteIndented = true });

return "abc" for english text field,

and "\u0422\u0435\u043A\u0443\u0449\u0438\u0439 \u0422\u04201" for russian text field

please tell me how to set encoding