问:
Python 3: remove attributes from class before instancing it
I'm working with Python3, and I have a really heavy class with many functions as attributes:

```<code>Class A (object):

    def __init__(self):
        ...

    def method1(self):
        ...

    def method2(self):
        ...

        ...

    def methodN(self):
        ...
</code>```

I would like to create an instance of class A that only has method1, for example. How could I do this?

Using inheritance, though it might be the most technically correct way, is not an option in my case - I can't modify the codebase so much.

I thought about decorating the class and deleting its attributes before __init__ is called, but I'm not even sure where to start tackling this. Any ideas?

答:
You can modify the __getattribute__ method of the class to disallow access to those attributes (via normal instance.attribute access)

```<code>class A (object):
    def __init__(self, x):
        self.x = x
    def method1(self):
        ...
    def method2(self):
        ...
    def __getattribute__(self, name):
        if object.__getattribute__(self, 'x'):
            if name == 'method2':
                raise AttributeError("Cannot access method2 is self.x is True")
        return object.__getattribute__(self, name)

>>> a = A(False)
>>> a.method1
<bound method A.method1 of <__main__.A object at 0x000001E25992F248>>
>>> a.method2
<bound method A.method2 of <__main__.A object at 0x000001E25992F248>>
>>> b = A(True)
>>> b.method1
<bound method A.method1 of <__main__.A object at 0x000001E25992F2C8>>
>>> b.method2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 11, in __getattribute__
AttributeError: Cannot access method2 is self.x is True
</code>```

Obviously, this gets pretty unwieldy and violates a lot of assumptions about what it means to be an instance of a class.  I can't think of a good reason to do this in real code, as you can still access the methods through object.__getattribute__(b, 'method2')

Body:
I'm working with Python3, and I have a really heavy class with many functions as attributes:

Class A (object):

    def __init__(self):
        ...

    def method1(self):
        ...

    def method2(self):
        ...

        ...

    def methodN(self):
        ...

I would like to create an instance of class A that only has method1, for example. How could I do this?

Using inheritance, though it might be the most technically correct way, is not an option in my case - I can't modify the codebase so much.

I thought about decorating the class and deleting its attributes before __init__ is called, but I'm not even sure where to start tackling this. Any ideas?

Body:
You can modify the __getattribute__ method of the class to disallow access to those attributes (via normal instance.attribute access)

class A (object):
    def __init__(self, x):
        self.x = x
    def method1(self):
        ...
    def method2(self):
        ...
    def __getattribute__(self, name):
        if object.__getattribute__(self, 'x'):
            if name == 'method2':
                raise AttributeError("Cannot access method2 is self.x is True")
        return object.__getattribute__(self, name)

>>> a = A(False)
>>> a.method1
<bound method A.method1 of <__main__.A object at 0x000001E25992F248>>
>>> a.method2
<bound method A.method2 of <__main__.A object at 0x000001E25992F248>>
>>> b = A(True)
>>> b.method1
<bound method A.method1 of <__main__.A object at 0x000001E25992F2C8>>
>>> b.method2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 11, in __getattribute__
AttributeError: Cannot access method2 is self.x is True

Obviously, this gets pretty unwieldy and violates a lot of assumptions about what it means to be an instance of a class.  I can't think of a good reason to do this in real code, as you can still access the methods through object.__getattribute__(b, 'method2')


来源: stackexchange

问:
Rails how to pass ID in views - NameError in MessagesController#create
I'm trying to remember again pure Rails with view in html.erb. In my controller I've got an action which allows me to replay to original message from my inbox:

```<code>def create
  orignal_message = current_user.inbox.messages.find_by(id: params[:original_message_id])

  inbox = if orignal_message.created_at > 3.days.ago
             orignal_message.moderator.inbox
          else
             original_message.admin.inbox
          end

  @message = Message.create(
    inbox: inbox
    body: params[:message][:body]
  )
end
</code>```

As you see if the original message will be older than 3 days the reply should goes to the moderator.outbox, if it's fresh new - go to the admin outbox. How to handle that sort of action in view to fetch this original message and reply on?

In my show.html.erb I've got simple:
<%= link_to "Answer", new_message_path, class: "btn-primary" %>

Which gives me an error:

```<code>NameError in MessagesController#create
undefined local variable or method `original_message' for #<MessagesController:0x00007fcf969bb618>
</code>```

答: You've got a typo in your controller. Sometimes you use original_message and sometimes orignal_message. Fix those and it should be fine

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to remember again pure Rails with view in html.erb. In my controller I've got an action which allows me to replay to original message from my inbox:

def create
  orignal_message = current_user.inbox.messages.find_by(id: params[:original_message_id])

  inbox = if orignal_message.created_at > 3.days.ago
             orignal_message.moderator.inbox
          else
             original_message.admin.inbox
          end

  @message = Message.create(
    inbox: inbox
    body: params[:message][:body]
  )
end

As you see if the original message will be older than 3 days the reply should goes to the moderator.outbox, if it's fresh new - go to the admin outbox. How to handle that sort of action in view to fetch this original message and reply on?

In my show.html.erb I've got simple:
<%= link_to "Answer", new_message_path, class: "btn-primary" %>

Which gives me an error:

NameError in MessagesController#create
undefined local variable or method `original_message' for #<MessagesController:0x00007fcf969bb618>


问:
ASP.NET ActiveDirectory Federation authentication for multiple projects
At this point, our company is hosting multiple (internal) projects, all related to each other under windows authentication. With this - it is easy - we just set up windows forms authentication in IIS, and all of them are secured, one login required, and the user is logged in in all of them.

The main applications are as fallows:

Client side application (built with just html/javascript). Hosts index.html for the application

Server side application (APS.NET MVC project, but we mainly use it as a WebAPI. Client side application calls for back-end resource, Server side is usually responsible for the responses.

Proxy application - proxies some webRequests to remote resources from client side.

Under IIS our projects look like this:

```<code>- Sites
  - hostname
      Client side application with
      index.html
      all of the other front end resources
      web.config for clientside application
      - ServerSideApplication (MVC4 project)
          - its bin
          - web.config for serverside application
      - Proxy application (Strange ASP.NET project)
          - its bin
          - web.config for proxy application
</code>```

URLS are made like this

https://hostname/index.html for clientSide application

https://hostname/SERVER/ for ServerSide application

https://hostname/PROXY/ for the proxy application

Now I am tasked to enable Federation authentication for this system, and I don't have enough knowledge to connect all of this together!

I was looking at creating new MVC projects to get some examples, with selecting authentication to "Work or School Accounts" and "On-Premises". This creates an application that could work for me. But that is for a single application. What would I do with ClientSide application? Would I need to wrap it in an ASP.NET MVC project, and set the same settings as for the ServerSide application? I noticed - if I create a WebAPI project, it adds token authentication. With that, I would require additional step for client side application to obtain that token, to be sent with the requests?

How should I build this system? No need concrete code examples, some hints for finding the solution, some experience would be appreciated.

答:
Do you need to authenticate with Azure AD or ADFS?

Azure AD = "Work or School Accounts"

ADFS = "On-Premises"

There are Azure AD samples here.

There are ADFS samples here.

For both, you need IDP configuration for each application.

Applications are called Relying Parties (RP) and there is an RP configuration per application.

If the application calls a web API, then that is two RP.

You then configure permissions for the application to access the web API.

Find a sample similar to your use case and that will explain this in more detail.

Body:
At this point, our company is hosting multiple (internal) projects, all related to each other under windows authentication. With this - it is easy - we just set up windows forms authentication in IIS, and all of them are secured, one login required, and the user is logged in in all of them.

The main applications are as fallows:

Client side application (built with just html/javascript). Hosts index.html for the application

Server side application (APS.NET MVC project, but we mainly use it as a WebAPI. Client side application calls for back-end resource, Server side is usually responsible for the responses.

Proxy application - proxies some webRequests to remote resources from client side.

Under IIS our projects look like this:

- Sites
  - hostname
      Client side application with
      index.html
      all of the other front end resources
      web.config for clientside application
      - ServerSideApplication (MVC4 project)
          - its bin
          - web.config for serverside application
      - Proxy application (Strange ASP.NET project)
          - its bin
          - web.config for proxy application

URLS are made like this

https://hostname/index.html for clientSide application

https://hostname/SERVER/ for ServerSide application

https://hostname/PROXY/ for the proxy application

Now I am tasked to enable Federation authentication for this system, and I don't have enough knowledge to connect all of this together!

I was looking at creating new MVC projects to get some examples, with selecting authentication to "Work or School Accounts" and "On-Premises". This creates an application that could work for me. But that is for a single application. What would I do with ClientSide application? Would I need to wrap it in an ASP.NET MVC project, and set the same settings as for the ServerSide application? I noticed - if I create a WebAPI project, it adds token authentication. With that, I would require additional step for client side application to obtain that token, to be sent with the requests?

How should I build this system? No need concrete code examples, some hints for finding the solution, some experience would be appreciated.


问:
Why isn't my variable being updated and my LEDs don't go on?
Working on a code project using an arduino, but things seem to not work and I'm not exactly sure why. I intended it to use the A-D buttons on a 16 key keypad to change a variable called activeSlot, which would then change what actual slot the number keys would write to when pressed. Things don't seem to work though, and I'm not sure what went wrong.

```<code>#include <Keypad.h>

const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] = {
  {'D','C','B','A'},
  {'#','9','6','3'},
  {'0','8','5','2'},
  {'*','7','4','1'}
};

byte rowPins[ROWS] = {2, 3, 4, 5}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {6, 7, 8, 9}; //connect to the column pinouts of the keypad

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
</code>```

basic keypad setup

```<code>

//the amount of energy in each slot
int slotA = 0;
int slotB = 0;
int slotC = 0;
int slotD = 0;

//the amount of energy in the other slots, set to 0 at the beginning
int totalA = 0;
int totalB = 0;
int totalC = 0;
int totalD = 0;

//the total allocated energy, used for lighting the correct number of LEDs
int totalE = 0;

int activeSlot[] = {0};
int x = activeSlot[0];

</code>```

Setup for integers, all start at 0 and should be changed in the loop section

```<code>void setup() {
  // put your setup code here, to run once:

//pinMode(2,INPUT);
//pinMode(3,INPUT);
//pinMode(4,INPUT);
//pinMode(5,INPUT);
//pinMode(6,INPUT);
//pinMode(7,INPUT);
//pinMode(8,INPUT);
//pinMode(9,INPUT);
pinMode(10,OUTPUT);
pinMode(11,OUTPUT);
pinMode(12,OUTPUT);
pinMode(13,OUTPUT);
pinMode(14,OUTPUT);
pinMode(15,OUTPUT);
pinMode(16,OUTPUT);
pinMode(17,OUTPUT);
pinMode(18,OUTPUT);
pinMode(19,OUTPUT);
  Serial.begin(9600);
}
</code>```

configures pins

```<code>void loop() {
  // put your main code here, to run repeatedly:
  char key = keypad.getKey();

  //the amount of energy in the other slots, set to 0 at the beginning
  int totalA = 10 - (slotB + slotC + slotD);
  int totalB = 10 - (slotA + slotC + slotD);
  int totalC = 10 - (slotA + slotB + slotD);
  int totalD = 10 - (slotA + slotB + slotC);
</code>```

There should be 10 energy/points to allocate to any slot. totalA is the starting 10 - the energy in each other slot. If there is less energy left than the number key you press for that slot, it shouldn't change the variable.

```<code>  // section for active slot keypress actions
   if (key == 'A'){activeSlot[0] = 1;
   Serial.println(x = activeSlot[0]);
   }
   if (key == 'B'){activeSlot[0] = 2;
   Serial.println(x = activeSlot[0]);
   }
   if (key == 'C'){activeSlot[0] = 3;
   Serial.println(x = activeSlot[0]);
   }
   if (key == 'D'){activeSlot[0] = 4;
   Serial.println(x = activeSlot[0]);
   }

x = activeSlot[0];

//1 energy section
if(key == '1');          //if _ is pressed
  if(activeSlot[0] = 1); //if the slot is A
    if(totalA >= 1);     //if A has at least _ energy
      slotA = 1;         //set A to _
                   //B section
  if(activeSlot[0] = 2);
    if(totalB >= 1);
      slotB = 1;
                   //C section
  if(activeSlot[0] = 3);
    if(totalC >= 1);
      slotC = 1;
                   //D section
  if(activeSlot[0] = 4);
    if(totalD >= 1);
      slotD = 1;

//2 energy section
if(key == '2');
  if(activeSlot[0] = 1);
    if(totalA >= 2);
      slotA = 2;
  if(activeSlot[0] = 2);
    if(totalB >= 2);
      slotB = 2;
  if(activeSlot[0] = 3);
    if(totalC >= 2);
      slotC = 2;
  if(activeSlot[0] = 4);
    if(totalD >= 2);
      slotD = 2;
//3 energy section
if(key == '3');
  if(activeSlot[0] = 1);
    if(totalA >= 3);
      slotA = 3;
  if(activeSlot[0] = 2);
    if(totalB >= 3);
      slotB = 3;
  if(activeSlot[0] = 3);
    if(totalC >= 3);
      slotC = 3;
  if(activeSlot[0] = 4);
    if(totalD >= 3);
      slotD = 3;
//4 energy section
if(key == '4');
  if(activeSlot[0] = 1);
    if(totalA >= 4);
      slotA = 4;
  if(activeSlot[0] = 2);
    if(totalB >= 4);
      slotB = 4;
  if(activeSlot[0] = 3);
    if(totalC >= 4);
      slotC = 4;
  if(activeSlot[0] = 4);
    if(totalD >= 4);
      slotD = 4;
//5 energy section
if(key == '5');
  if(activeSlot[0] = 1);
    if(totalA >= 5);
      slotA = 5;
  if(activeSlot[0] = 2);
    if(totalB >= 5);
      slotB = 5;
  if(activeSlot[0] = 3);
    if(totalC >= 5);
      slotC = 5;
  if(activeSlot[0] = 4);
    if(totalD >= 5);
      slotD = 5;
//6 energy section
if(key == '6');
  if(activeSlot[0] = 1);
    if(totalA >= 6);
      slotA = 6;
  if(activeSlot[0] = 2);
    if(totalB >= 6);
      slotB = 6;
  if(activeSlot[0] = 3);
    if(totalC >= 6);
      slotC = 6;
  if(activeSlot[0] = 4);
    if(totalD >= 6);
      slotD = 6;
//7 energy section
if(key == '7');
  if(activeSlot[0] = 1);
    if(totalA >= 7);
      slotA = 7;
  if(activeSlot[0] = 2);
    if(totalB >= 7);
      slotB = 7;
  if(activeSlot[0] = 3);
    if(totalC >= 7);
      slotC = 7;
  if(activeSlot[0] = 4);
    if(totalD >= 7);
      slotD = 7;
//0 energy section
if(key == '0');
  if(activeSlot[0] = 1);
    if(totalA >= 0);
      slotA = 0;
  if(activeSlot[0] = 2);
    if(totalB >= 0);
      slotB = 0;
  if(activeSlot[0] = 3);
    if(totalC >= 0);
      slotC = 0;
  if(activeSlot[0] = 4);
    if(totalD >= 0);
      slotD = 0;

  //the amount of energy used in all the slots, for the LEDs
  int totalE = slotA + slotB + slotC + slotD;
</code>```

this section checks for a pressed number key. If one is pressed, it checks the activeSlot for what slot to change. If the total energy left is enough, it then should change that slot to the value of the number key pressed.

```<code>//LED SECTION
if(totalE == 0){
  digitalWrite(13,LOW);
  digitalWrite(12,LOW);
  digitalWrite(11,LOW);
  digitalWrite(10,LOW);
  digitalWrite(14,LOW);
  digitalWrite(15,LOW);
  digitalWrite(16,LOW);
  digitalWrite(17,LOW);
  digitalWrite(18,LOW);
  digitalWrite(19,LOW);
}
if(totalE == 1){
  digitalWrite(13,HIGH);
  digitalWrite(12,LOW);
  digitalWrite(11,LOW);
  digitalWrite(10,LOW);
  digitalWrite(14,LOW);
  digitalWrite(15,LOW);
  digitalWrite(16,LOW);
  digitalWrite(17,LOW);
  digitalWrite(18,LOW);
  digitalWrite(19,LOW);
}
if(totalE == 2){
  digitalWrite(13,HIGH);
  digitalWrite(12,HIGH);
  digitalWrite(11,LOW);
  digitalWrite(10,LOW);
  digitalWrite(14,LOW);
  digitalWrite(15,LOW);
  digitalWrite(16,LOW);
  digitalWrite(17,LOW);
  digitalWrite(18,LOW);
  digitalWrite(19,LOW);
}
if(totalE == 3){
  digitalWrite(13,HIGH);
  digitalWrite(12,HIGH);
  digitalWrite(11,HIGH);
  digitalWrite(10,LOW);
  digitalWrite(14,LOW);
  digitalWrite(15,LOW);
  digitalWrite(16,LOW);
  digitalWrite(17,LOW);
  digitalWrite(18,LOW);
  digitalWrite(19,LOW);
}
if(totalE == 4){
  digitalWrite(13,HIGH);
  digitalWrite(12,HIGH);
  digitalWrite(11,HIGH);
  digitalWrite(10,HIGH);
  digitalWrite(14,LOW);
  digitalWrite(15,LOW);
  digitalWrite(16,LOW);
  digitalWrite(17,LOW);
  digitalWrite(18,LOW);
  digitalWrite(19,LOW);
}
if(totalE == 5){
  digitalWrite(13,HIGH);
  digitalWrite(12,HIGH);
  digitalWrite(11,HIGH);
  digitalWrite(10,HIGH);
  digitalWrite(14,HIGH);
  digitalWrite(15,LOW);
  digitalWrite(16,LOW);
  digitalWrite(17,LOW);
  digitalWrite(18,LOW);
  digitalWrite(19,LOW);
}
if(totalE == 6){
  digitalWrite(13,HIGH);
  digitalWrite(12,HIGH);
  digitalWrite(11,HIGH);
  digitalWrite(10,HIGH);
  digitalWrite(14,HIGH);
  digitalWrite(15,HIGH);
  digitalWrite(16,LOW);
  digitalWrite(17,LOW);
  digitalWrite(18,LOW);
  digitalWrite(19,LOW);
}
if(totalE == 7){
  digitalWrite(13,HIGH);
  digitalWrite(12,HIGH);
  digitalWrite(11,HIGH);
  digitalWrite(10,HIGH);
  digitalWrite(14,HIGH);
  digitalWrite(15,HIGH);
  digitalWrite(16,HIGH);
  digitalWrite(17,LOW);
  digitalWrite(18,LOW);
  digitalWrite(19,LOW);
}
if(totalE == 8){
  digitalWrite(13,HIGH);
  digitalWrite(12,HIGH);
  digitalWrite(11,HIGH);
  digitalWrite(10,HIGH);
  digitalWrite(14,HIGH);
  digitalWrite(15,HIGH);
  digitalWrite(16,HIGH);
  digitalWrite(17,HIGH);
  digitalWrite(18,LOW);
  digitalWrite(19,LOW);
}
if(totalE == 9){
  digitalWrite(13,HIGH);
  digitalWrite(12,HIGH);
  digitalWrite(11,HIGH);
  digitalWrite(10,HIGH);
  digitalWrite(14,HIGH);
  digitalWrite(15,HIGH);
  digitalWrite(16,HIGH);
  digitalWrite(17,HIGH);
  digitalWrite(18,HIGH);
  digitalWrite(19,LOW);
}
if(totalE == 10){
  digitalWrite(13,HIGH);
  digitalWrite(12,HIGH);
  digitalWrite(11,HIGH);
  digitalWrite(10,HIGH);
  digitalWrite(14,HIGH);
  digitalWrite(15,HIGH);
  digitalWrite(16,HIGH);
  digitalWrite(17,HIGH);
  digitalWrite(18,HIGH);
  digitalWrite(19,HIGH);
}

if(key == '#'){
  Serial.println(x = activeSlot[0]);
}
if(key == '*'){
  Serial.println(x = totalE);
}

//end of void loop
}
</code>```

This is the LED section. I intended it to check the totalE (the total value of each slot) and use that for lighting up the correct number of LEDs. totalE at 0 means none are lit up, 1 means 1 is lit up, etc.. It doesn't seem to do anything, and totalE doesn't seem to change. For some reason, activeSlot[0] is always stuck at 4 as well.

答:
This section of code

```<code>if(key == '1');          //if _ is pressed
  if(activeSlot[0] = 1); //if the slot is A
    if(totalA >= 1);     //if A has at least _ energy
      slotA = 1;         //set A to _
</code>```

is almost certainly not doing what you expect. The semicolon ; after each if statement terminates the if statement, and executes nothing. The lines following each if statement are then executed unconditionally, as if there was no if condition guarding on them (because as written, there is not). Further, you're assigning values to activeSlot[0] (activeSlot[0] = 1) instead of checking for equality. You want if (activeSlot[0] == 1). Your current code can be rewritten (with indentation indicating scoping) as

```<code>if(key == '1');        //if '1' is pressed, do nothing
if(activeSlot[0] = 1); //assign the value of 1 to activeSlot[0], then do nothing
if(totalA >= 1);       //if A has at least 1 energy, do nothing
slotA = 1;             //set A to 1
</code>```

You most likely want to rewrite this as

```<code>if(key == '1')           //if _ is pressed
  if(activeSlot[0] == 1) //if the slot is A
    if(totalA >= 1)      //if A has at least _ energy
      slotA = 1;         //set A to _
</code>```

Note the lack of semicolons after the if statements, and the boolean == operator instead of assignment =.

At the end of your entire chain of if statements and variable assignments you have (rewritten to show behavior better)

```<code>if(key == '0');        // do nothing
if(activeSlot[0] = 1); // activeSlot[0] always gets assigned 1
if(totalA >= 0);       // do nothing
slotA = 0;             // this happens always
if(activeSlot[0] = 2); // activeSlot[0] always gets assigned 2
if(totalB >= 0);       // do nothing
slotB = 0;             // this happens always
if(activeSlot[0] = 3); // activeSlot[0] always gets assigned 3
if(totalC >= 0);       // do nothing
slotC = 0;             // this happens always
if(activeSlot[0] = 4); // activeSlot[0] always gets assigned 4 (overwriting all previous assignments)
if(totalD >= 0);       // do nothing
slotD = 0;             // this happens always
</code>```

Body:
Working on a code project using an arduino, but things seem to not work and I'm not exactly sure why. I intended it to use the A-D buttons on a 16 key keypad to change a variable called activeSlot, which would then change what actual slot the number keys would write to when pressed. Things don't seem to work though, and I'm not sure what went wrong.

#include <Keypad.h>

const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] = {
  {'D','C','B','A'},
  {'#','9','6','3'},
  {'0','8','5','2'},
  {'*','7','4','1'}
};

byte rowPins[ROWS] = {2, 3, 4, 5}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {6, 7, 8, 9}; //connect to the column pinouts of the keypad

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

basic keypad setup

//the amount of energy in each slot
int slotA = 0;
int slotB = 0;
int slotC = 0;
int slotD = 0;

//the amount of energy in the other slots, set to 0 at the beginning
int totalA = 0;
int totalB = 0;
int totalC = 0;
int totalD = 0;

//the total allocated energy, used for lighting the correct number of LEDs
int totalE = 0;

int activeSlot[] = {0};
int x = activeSlot[0];

Setup for integers, all start at 0 and should be changed in the loop section

void setup() {
  // put your setup code here, to run once:

//pinMode(2,INPUT);
//pinMode(3,INPUT);
//pinMode(4,INPUT);
//pinMode(5,INPUT);
//pinMode(6,INPUT);
//pinMode(7,INPUT);
//pinMode(8,INPUT);
//pinMode(9,INPUT);
pinMode(10,OUTPUT);
pinMode(11,OUTPUT);
pinMode(12,OUTPUT);
pinMode(13,OUTPUT);
pinMode(14,OUTPUT);
pinMode(15,OUTPUT);
pinMode(16,OUTPUT);
pinMode(17,OUTPUT);
pinMode(18,OUTPUT);
pinMode(19,OUTPUT);
  Serial.begin(9600);
}

configures pins

void loop() {
  // put your main code here, to run repeatedly:
  char key = keypad.getKey();

  //the amount of energy in the other slots, set to 0 at the beginning
  int totalA = 10 - (slotB + slotC + slotD);
  int totalB = 10 - (slotA + slotC + slotD);
  int totalC = 10 - (slotA + slotB + slotD);
  int totalD = 10 - (slotA + slotB + slotC);

There should be 10 energy/points to allocate to any slot. totalA is the starting 10 - the energy in each other slot. If there is less energy left than the number key you press for that slot, it shouldn't change the variable.

  // section for active slot keypress actions
   if (key == 'A'){activeSlot[0] = 1;
   Serial.println(x = activeSlot[0]);
   }
   if (key == 'B'){activeSlot[0] = 2;
   Serial.println(x = activeSlot[0]);
   }
   if (key == 'C'){activeSlot[0] = 3;
   Serial.println(x = activeSlot[0]);
   }
   if (key == 'D'){activeSlot[0] = 4;
   Serial.println(x = activeSlot[0]);
   }

x = activeSlot[0];

//1 energy section
if(key == '1');          //if _ is pressed
  if(activeSlot[0] = 1); //if the slot is A
    if(totalA >= 1);     //if A has at least _ energy
      slotA = 1;         //set A to _
                   //B section
  if(activeSlot[0] = 2);
    if(totalB >= 1);
      slotB = 1;
                   //C section
  if(activeSlot[0] = 3);
    if(totalC >= 1);
      slotC = 1;
                   //D section
  if(activeSlot[0] = 4);
    if(totalD >= 1);
      slotD = 1;

//2 energy section
if(key == '2');
  if(activeSlot[0] = 1);
    if(totalA >= 2);
      slotA = 2;
  if(activeSlot[0] = 2);
    if(totalB >= 2);
      slotB = 2;
  if(activeSlot[0] = 3);
    if(totalC >= 2);
      slotC = 2;
  if(activeSlot[0] = 4);
    if(totalD >= 2);
      slotD = 2;
//3 energy section
if(key == '3');
  if(activeSlot[0] = 1);
    if(totalA >= 3);
      slotA = 3;
  if(activeSlot[0] = 2);
    if(totalB >= 3);
      slotB = 3;
  if(activeSlot[0] = 3);
    if(totalC >= 3);
      slotC = 3;
  if(activeSlot[0] = 4);
    if(totalD >= 3);
      slotD = 3;
//4 energy section
if(key == '4');
  if(activeSlot[0] = 1);
    if(totalA >= 4);
      slotA = 4;
  if(activeSlot[0] = 2);
    if(totalB >= 4);
      slotB = 4;
  if(activeSlot[0] = 3);
    if(totalC >= 4);
      slotC = 4;
  if(activeSlot[0] = 4);
    if(totalD >= 4);
      slotD = 4;
//5 energy section
if(key == '5');
  if(activeSlot[0] = 1);
    if(totalA >= 5);
      slotA = 5;
  if(activeSlot[0] = 2);
    if(totalB >= 5);
      slotB = 5;
  if(activeSlot[0] = 3);
    if(totalC >= 5);
      slotC = 5;
  if(activeSlot[0] = 4);
    if(totalD >= 5);
      slotD = 5;
//6 energy section
if(key == '6');
  if(activeSlot[0] = 1);
    if(totalA >= 6);
      slotA = 6;
  if(activeSlot[0] = 2);
    if(totalB >= 6);
      slotB = 6;
  if(activeSlot[0] = 3);
    if(totalC >= 6);
      slotC = 6;
  if(activeSlot[0] = 4);
    if(totalD >= 6);
      slotD = 6;
//7 energy section
if(key == '7');
  if(activeSlot[0] = 1);
    if(totalA >= 7);
      slotA = 7;
  if(activeSlot[0] = 2);
    if(totalB >= 7);
      slotB = 7;
  if(activeSlot[0] = 3);
    if(totalC >= 7);
      slotC = 7;
  if(activeSlot[0] = 4);
    if(totalD >= 7);
      slotD = 7;
//0 energy section
if(key == '0');
  if(activeSlot[0] = 1);
    if(totalA >= 0);
      slotA = 0;
  if(activeSlot[0] = 2);
    if(totalB >= 0);
      slotB = 0;
  if(activeSlot[0] = 3);
    if(totalC >= 0);
      slotC = 0;
  if(activeSlot[0] = 4);
    if(totalD >= 0);
      slotD = 0;

  //the amount of energy used in all the slots, for the LEDs
  int totalE = slotA + slotB + slotC + slotD;

this section checks for a pressed number key. If one is pressed, it checks the activeSlot for what slot to change. If the total energy left is enough, it then should change that slot to the value of the number key pressed.

//LED SECTION
if(totalE == 0){
  digitalWrite(13,LOW);
  digitalWrite(12,LOW);
  digitalWrite(11,LOW);
  digitalWrite(10,LOW);
  digitalWrite(14,LOW);
  digitalWrite(15,LOW);
  digitalWrite(16,LOW);
  digitalWrite(17,LOW);
  digitalWrite(18,LOW);
  digitalWrite(19,LOW);
}
if(totalE == 1){
  digitalWrite(13,HIGH);
  digitalWrite(12,LOW);
  digitalWrite(11,LOW);
  digitalWrite(10,LOW);
  digitalWrite(14,LOW);
  digitalWrite(15,LOW);
  digitalWrite(16,LOW);
  digitalWrite(17,LOW);
  digitalWrite(18,LOW);
  digitalWrite(19,LOW);
}
if(totalE == 2){
  digitalWrite(13,HIGH);
  digitalWrite(12,HIGH);
  digitalWrite(11,LOW);
  digitalWrite(10,LOW);
  digitalWrite(14,LOW);
  digitalWrite(15,LOW);
  digitalWrite(16,LOW);
  digitalWrite(17,LOW);
  digitalWrite(18,LOW);
  digitalWrite(19,LOW);
}
if(totalE == 3){
  digitalWrite(13,HIGH);
  digitalWrite(12,HIGH);
  digitalWrite(11,HIGH);
  digitalWrite(10,LOW);
  digitalWrite(14,LOW);
  digitalWrite(15,LOW);
  digitalWrite(16,LOW);
  digitalWrite(17,LOW);
  digitalWrite(18,LOW);
  digitalWrite(19,LOW);
}
if(totalE == 4){
  digitalWrite(13,HIGH);
  digitalWrite(12,HIGH);
  digitalWrite(11,HIGH);
  digitalWrite(10,HIGH);
  digitalWrite(14,LOW);
  digitalWrite(15,LOW);
  digitalWrite(16,LOW);
  digitalWrite(17,LOW);
  digitalWrite(18,LOW);
  digitalWrite(19,LOW);
}
if(totalE == 5){
  digitalWrite(13,HIGH);
  digitalWrite(12,HIGH);
  digitalWrite(11,HIGH);
  digitalWrite(10,HIGH);
  digitalWrite(14,HIGH);
  digitalWrite(15,LOW);
  digitalWrite(16,LOW);
  digitalWrite(17,LOW);
  digitalWrite(18,LOW);
  digitalWrite(19,LOW);
}
if(totalE == 6){
  digitalWrite(13,HIGH);
  digitalWrite(12,HIGH);
  digitalWrite(11,HIGH);
  digitalWrite(10,HIGH);
  digitalWrite(14,HIGH);
  digitalWrite(15,HIGH);
  digitalWrite(16,LOW);
  digitalWrite(17,LOW);
  digitalWrite(18,LOW);
  digitalWrite(19,LOW);
}
if(totalE == 7){
  digitalWrite(13,HIGH);
  digitalWrite(12,HIGH);
  digitalWrite(11,HIGH);
  digitalWrite(10,HIGH);
  digitalWrite(14,HIGH);
  digitalWrite(15,HIGH);
  digitalWrite(16,HIGH);
  digitalWrite(17,LOW);
  digitalWrite(18,LOW);
  digitalWrite(19,LOW);
}
if(totalE == 8){
  digitalWrite(13,HIGH);
  digitalWrite(12,HIGH);
  digitalWrite(11,HIGH);
  digitalWrite(10,HIGH);
  digitalWrite(14,HIGH);
  digitalWrite(15,HIGH);
  digitalWrite(16,HIGH);
  digitalWrite(17,HIGH);
  digitalWrite(18,LOW);
  digitalWrite(19,LOW);
}
if(totalE == 9){
  digitalWrite(13,HIGH);
  digitalWrite(12,HIGH);
  digitalWrite(11,HIGH);
  digitalWrite(10,HIGH);
  digitalWrite(14,HIGH);
  digitalWrite(15,HIGH);
  digitalWrite(16,HIGH);
  digitalWrite(17,HIGH);
  digitalWrite(18,HIGH);
  digitalWrite(19,LOW);
}
if(totalE == 10){
  digitalWrite(13,HIGH);
  digitalWrite(12,HIGH);
  digitalWrite(11,HIGH);
  digitalWrite(10,HIGH);
  digitalWrite(14,HIGH);
  digitalWrite(15,HIGH);
  digitalWrite(16,HIGH);
  digitalWrite(17,HIGH);
  digitalWrite(18,HIGH);
  digitalWrite(19,HIGH);
}

if(key == '#'){
  Serial.println(x = activeSlot[0]);
}
if(key == '*'){
  Serial.println(x = totalE);
}

//end of void loop
}

This is the LED section. I intended it to check the totalE (the total value of each slot) and use that for lighting up the correct number of LEDs. totalE at 0 means none are lit up, 1 means 1 is lit up, etc.. It doesn't seem to do anything, and totalE doesn't seem to change. For some reason, activeSlot[0] is always stuck at 4 as well.

Body:
This section of code

if(key == '1');          //if _ is pressed
  if(activeSlot[0] = 1); //if the slot is A
    if(totalA >= 1);     //if A has at least _ energy
      slotA = 1;         //set A to _

is almost certainly not doing what you expect. The semicolon ; after each if statement terminates the if statement, and executes nothing. The lines following each if statement are then executed unconditionally, as if there was no if condition guarding on them (because as written, there is not). Further, you're assigning values to activeSlot[0] (activeSlot[0] = 1) instead of checking for equality. You want if (activeSlot[0] == 1). Your current code can be rewritten (with indentation indicating scoping) as

if(key == '1');        //if '1' is pressed, do nothing
if(activeSlot[0] = 1); //assign the value of 1 to activeSlot[0], then do nothing
if(totalA >= 1);       //if A has at least 1 energy, do nothing
slotA = 1;             //set A to 1

You most likely want to rewrite this as

if(key == '1')           //if _ is pressed
  if(activeSlot[0] == 1) //if the slot is A
    if(totalA >= 1)      //if A has at least _ energy
      slotA = 1;         //set A to _

Note the lack of semicolons after the if statements, and the boolean == operator instead of assignment =.

At the end of your entire chain of if statements and variable assignments you have (rewritten to show behavior better)

if(key == '0');        // do nothing
if(activeSlot[0] = 1); // activeSlot[0] always gets assigned 1
if(totalA >= 0);       // do nothing
slotA = 0;             // this happens always
if(activeSlot[0] = 2); // activeSlot[0] always gets assigned 2
if(totalB >= 0);       // do nothing
slotB = 0;             // this happens always
if(activeSlot[0] = 3); // activeSlot[0] always gets assigned 3
if(totalC >= 0);       // do nothing
slotC = 0;             // this happens always
if(activeSlot[0] = 4); // activeSlot[0] always gets assigned 4 (overwriting all previous assignments)
if(totalD >= 0);       // do nothing
slotD = 0;             // this happens always


问:
JavaScript - Math.random() - parameter
What changes adding the parameter in Math.random()?

For example:

```<code>Math.random() == Math.random(1234)
</code>```

答:
Math.random doesn't take params.

If you want to generate a random number between 2 intervals (a and b) you can use the formula:

```<code>math.random()*(b-a)+a
</code>```

ContentLicense: CC BY-SA 3.0

Title: JavaScript - Math.random() - parameter

Body:
What changes adding the parameter in Math.random()?

For example:

Math.random() == Math.random(1234)

Body:
Math.random doesn't take params.

If you want to generate a random number between 2 intervals (a and b) you can use the formula:

math.random()*(b-a)+a


问:
Adding quotations around words preceding a colon in Python
I am learning Python (python3) and am working with a text file containing semi-JSON format. It is not full JSON because the "keys" are not surrounded by quotes. I am looking to programmatically add quotes around all of these key names. My plan was to "open" this file and parse each "line" as an individual string.

From:

key_name: { another_key: "somevalue", second_key: "anotherval" }

Into:

"key_name": { "another_key": "somevalue", "second_key": "anotherval" }

I'm sure regex would be the ideal way to do this - for the sake of learning I have been using arrays...

I have some code that works partially, but not all of the keys get parentheses placed around them.

```<code>str = "this is: a string: testing testing: blah blah more: test: hereis: test:"

cp_str = list(str[::-1])

skip = False
find_end = False
for step in range(len(cp_str) - 1):
  if skip:
    skip = False
    continue

  if cp_str[step] == ':':
    cp_str.insert(step + 1, '"')
    skip = True
    find_end = True

  if not skip and find_end and not(ord(cp_str[step].lower()) > 95 and ord(cp_str[step].lower()) < 95+26):
    cp_str.insert(step, '"')
    skip = True
    find_end = False

print(''.join(cp_str[::-1]))
</code>```

Outputs:

this is: a string": testing "testing": blah blah "more":
  "test": "hereis": "test":

Any tips or help on the best ways to tackle this would be appreciated.

答:
Avoid using regex to handle structured formats. It will almost always mis-handle certain corner cases.

Since your input is valid YAML, you can install PyYAML, load the input as YAML, and dump the data structure as JSON instead:

```<code>import yaml
import json
s = 'key_name: { another_key: "somevalue", second_key: "anotherval" }'
print(json.dumps(yaml.load(s)))
</code>```

This outputs:

```<code>{"key_name": {"another_key": "somevalue", "second_key": "anotherval"}}
</code>```

Body:
I am learning Python (python3) and am working with a text file containing semi-JSON format. It is not full JSON because the "keys" are not surrounded by quotes. I am looking to programmatically add quotes around all of these key names. My plan was to "open" this file and parse each "line" as an individual string.

From:

key_name: { another_key: "somevalue", second_key: "anotherval" }

Into:

"key_name": { "another_key": "somevalue", "second_key": "anotherval" }

I'm sure regex would be the ideal way to do this - for the sake of learning I have been using arrays...

I have some code that works partially, but not all of the keys get parentheses placed around them.

str = "this is: a string: testing testing: blah blah more: test: hereis: test:"

cp_str = list(str[::-1])

skip = False
find_end = False
for step in range(len(cp_str) - 1):
  if skip:
    skip = False
    continue

  if cp_str[step] == ':':
    cp_str.insert(step + 1, '"')
    skip = True
    find_end = True

  if not skip and find_end and not(ord(cp_str[step].lower()) > 95 and ord(cp_str[step].lower()) < 95+26):
    cp_str.insert(step, '"')
    skip = True
    find_end = False

print(''.join(cp_str[::-1]))

Outputs:

this is: a string": testing "testing": blah blah "more":
  "test": "hereis": "test":

Any tips or help on the best ways to tackle this would be appreciated.

Body:
Avoid using regex to handle structured formats. It will almost always mis-handle certain corner cases.

Since your input is valid YAML, you can install PyYAML, load the input as YAML, and dump the data structure as JSON instead:

import yaml
import json
s = 'key_name: { another_key: "somevalue", second_key: "anotherval" }'
print(json.dumps(yaml.load(s)))

This outputs:

{"key_name": {"another_key": "somevalue", "second_key": "anotherval"}}


问:
HTML/CSS markup: irregular, asymmetrical lines drawn with DIV blocks on a HiPPI monitor
TLDR: same lines drawn with the div element look different at different scales and sizes of the browser window. This is the example: imgur, jsfiddle.

I drew some horizontal, vertical and diagonal lines using DIV blocks. With different browser window sizes, different scales, different content above and below the drawn blocks, these blocks (with the same thickness) look different (some are thinner, others are wider). Conversely, blocks with different thicknesses may look the same in some moments.

These pictures demonstate how a part of my schema looks in different situations.

On a monitor with a normal pixel density and with system scale = 100% this problem is less noticeable or not showing itself at all.

I saw a similar problem earlier when I added narrow (1-2px) div elements as horizontal dividers. Some of them sometimes were disappeared (they were invisible) when others behaved as usual on the same page, if all of them were visible, some of them were thicker than others. This behavior for each element changes even I open/close Chrome developer tools panel or drag a corner of browser window.

I tried to replace div lines with svg elements, but they also demonstate strange behavior.

Can I make all elements resize the same? I would not want to replace each such element with a bitmap image.

A similar problem was described in this (not solved) question (if you can't see the problem, just zoom the result window in jsfiddle.

I cant catch the problem in other sites, for example, on Wikipedia, all horizontal lines (under h2 elements, left menu dividers) look the same at any scale. At stackoverflow there are comment horizontal dividers (narrow gray lines between comments), they are also look great.

This (imgur, jsfiddle) minimal examlpe demonstrates the different line scaling at 90, 100 and 110%. I noticed a strange feature. If I use a border to draw lines instead of the background-color, then these lines look much better. This method used at stackoverflow and wikipedia sites (Wiki also uses png at the left menu).

This is the  minimal reproducible example, built in Stack Snippets:

.line {
  background-color: pink;
  /*  border-bottom: 1px solid pink; */
  margin: 20px auto;
  width: 80%;
  height: 1px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="line"></div>
<div class="line"></div>
<div class="line"></div>
<div class="line"></div>
<div class="line"></div></code>```

答:
This is just how different browsers solve for fractions at different zoom sizes. You can't have part of a pixel on your screen.

For example, let's say you have three divs stacked on top of each other, each 2px high. Zoom in to 120% and each div would now be 2.2px high. Since the browser can't actually render that, it might round the first div to 2px high. The second div might have a top of 2px and also be 2px high.

However, the third div should technically be 4.4px from the top, but its bottom should be 6.6px from the top. If the browser is rounding to the nearest whole number, you could see how it might compute the top of the third div at 4px and the bottom at 7px, giving it a height of 3px, instead of 2px.

I'm not saying that's exactly what's going on - each browser uses slightly different calculations when it comes to painting - but hopefully that helps illustrate the point. It sounds like you're having better luck with border so that might be your best approach.

Here's a similar question


问:
alternative of time for a seed to a random number generator?
In Go what value can one use as an alternative of current time

for a seed to a random number generator?

This simple question came to me as I was following the Tour of Go

where they say the current time in their sandbox environment is fixed.

答:
You can use crypto.rand package to read some random bytes, and convert that to a int64:

```<code>import (
  "crypto/rand"
  "encoding/binary"
)
...

b:=make([]byte,8)
rand.Read(b)
seed:=binary.BigEndian.Uint64(b)
</code>```

Body:
You can use crypto.rand package to read some random bytes, and convert that to a int64:

import (
  "crypto/rand"
  "encoding/binary"
)
...

b:=make([]byte,8)
rand.Read(b)
seed:=binary.BigEndian.Uint64(b)


问:
Cannot install httr package in R 3.6.2 in Linux Mint 19.3
I am totally new to R.

I tried to install the httr package.

I first installed pacman, and then tried to load httr through it by running pacman::p_load(httr).

It wasn't successful. And it showed the following message in terminal-

Installing package into
  ‘/home/|username|/R/x86_64-pc-linux-gnu-library/3.6’ (as ‘lib’ is
  unspecified) also installing the dependencies ‘curl’, ‘openssl’

trying URL 'https://cloud.r-project.org/src/contrib/curl_4.3.tar.gz'
  Content type 'application/x-gzip' length 673779 bytes (657 KB)
  ================================================== downloaded 657 KB

trying URL
  'https://cloud.r-project.org/src/contrib/openssl_1.4.1.tar.gz' Content
  type 'application/x-gzip' length 1206885 bytes (1.2 MB)
  ================================================== downloaded 1.2 MB

trying URL 'https://cloud.r-project.org/src/contrib/httr_1.4.1.tar.gz'
  Content type 'application/x-gzip' length 158465 bytes (154 KB)
  ================================================== downloaded 154 KB

installing source package ‘curl’ ...
  ** package ‘curl’ successfully unpacked and MD5 sums checked
  ** using staged installation Package libcurl was not found in the pkg-config search path. Perhaps you should add the directory
  containing libcurl.pc' to the PKG_CONFIG_PATH environment variable No
  package 'libcurl' found Package libcurl was not found in the
  pkg-config search path. Perhaps you should add the directory
  containinglibcurl.pc' to the PKG_CONFIG_PATH environment variable No
  package 'libcurl' found Using PKG_CFLAGS= Using PKG_LIBS=-lcurl
  ------------------------- ANTICONF ERROR --------------------------- Configuration failed because libcurl was not found. Try installing:  *
  deb: libcurl4-openssl-dev (Debian, Ubuntu, etc)  * rpm: libcurl-devel
  (Fedora, CentOS, RHEL)  * csw: libcurl_dev (Solaris) If libcurl is
  already installed, check that 'pkg-config' is in your PATH and
  PKG_CONFIG_PATH contains a libcurl.pc file. If pkg-config is
  unavailable you can set INCLUDE_DIR and LIB_DIR manually via: R CMD
  INSTALL --configure-vars='INCLUDE_DIR=... LIB_DIR=...'
  -------------------------------------------------------------------- ERROR: configuration failed for package ‘curl’

removing ‘/home/|username|/R/x86_64-pc-linux-gnu-library/3.6/curl’

installing source package ‘openssl’ ...
  ** package ‘openssl’ successfully unpacked and MD5 sums checked
  ** using staged installation Using PKG_CFLAGS=
  ------------------------- ANTICONF ERROR --------------------------- Configuration failed because openssl was not found. Try installing:  *
  deb: libssl-dev (Debian, Ubuntu, etc)  * rpm: openssl-devel (Fedora,
  CentOS, RHEL)  * csw: libssl_dev (Solaris)  * brew: openssl@1.1 (Mac
  OSX) If openssl is already installed, check that 'pkg-config' is in
  your PATH and PKG_CONFIG_PATH contains a openssl.pc file. If
  pkg-config is unavailable you can set INCLUDE_DIR and LIB_DIR manually
  via: R CMD INSTALL --configure-vars='INCLUDE_DIR=... LIB_DIR=...'
  -------------------------------------------------------------------- ERROR: configuration failed for package ‘openssl’

removing ‘/home/|username|/R/x86_64-pc-linux-gnu-library/3.6/openssl’ ERROR: dependencies ‘curl’, ‘openssl’ are not available for package
  ‘httr’

removing ‘/home/|username|/R/x86_64-pc-linux-gnu-library/3.6/httr’

The downloaded source packages are in
    ‘/tmp/Rtmp3wZaOu/downloaded_packages’ Warning messages: 1: In
  utils::install.packages(package, ...) :   installation of package
  ‘curl’ had non-zero exit status 2: In utils::install.packages(package,
  ...) :   installation of package ‘openssl’ had non-zero exit status 3:
  In utils::install.packages(package, ...) :   installation of package
  ‘httr’ had non-zero exit status 4: In p_install(package,
  character.only = TRUE, ...) :  5: In library(package, lib.loc =
  lib.loc, character.only = TRUE, logical.return = TRUE,  :   there is
  no package called ‘httr’ 6: In pacman::p_load(httr) : Failed to
  install/load: httr

How do I solve this?

Note: I have installed several other external packages through pacman. Like- dplyr, ggplot2 etc.

答:
httr imports openssl (https://cran.r-project.org/web/packages/openssl/index.html) and curl (https://cran.r-project.org/web/packages/curl/index.html)
and both are specific system requirements. For openssl "SystemRequirements:   OpenSSL >= 1.0.1" and for curl "SystemRequirements:   libcurl: libcurl-devel (rpm) or libcurl4-openssl-dev (deb)."


问:
Disable chrome yellow infobar?

I'm trying to remove the yellow infobar. Tried this, adding that parametet to shortcut with no luck:

```<code>C:\Users[USERNAME]\AppData\Local\Google\Chrome\Application\chrome.exe –disable-web-security
</code>```

What is the correct way to hide this yellow infobar ? Thanks

答:
You can use --app=desired_address_without_brackets. Works in Chrome 80.

Semi-official Chrome(ium?) doc for command line options

it will launch chrome in App mode and hide such infobars (alongside the adress bar and maybe tabs). Not always applicable, but --disable-infobars removed in Chrome 76 anyway.

Title: Disable chrome yellow infobar?

Body:
I'm trying to remove the yellow infobar. Tried this, adding that parametet to shortcut with no luck:

C:\Users[USERNAME]\AppData\Local\Google\Chrome\Application\chrome.exe –disable-web-security

What is the correct way to hide this yellow infobar ? Thanks


问:
Is it possible to make a task call inside wait statement in system Verilog?
```<code>wait((irq == 1'b1) || (wb_bus.master_read(2'b10,DON) DON == 16'h8000));
</code>```

Is this possible?

答:
No, not directly. But indirectly is probably not going to do what you want. (Which we have no idea what that is. See the XY Problem)

Assuming master_read is a time consuming task, you can wrap it non-void function that always returns true. The then do fork wb_bus.master_read(2'b10,DON); join_none inside the function. If master_read is not time consuming, then make it a function with a void return.

But you have no control over how often the expression gets evaluated, and therefore how often the task gets called. If irq and DON change at the same time, it could get called once or twice.

Body:
wait((irq == 1'b1) || (wb_bus.master_read(2'b10,DON) DON == 16'h8000));

Is this possible?


问:
SQL Oracle, dynamic PL/SQL pivot in function
I have the script below that pivots (transposes) rows to columns (column names are stored in variable "r", values in "v", while "A" and "B" are the identifiers that will remain on the rows after pivoting):

```<code>drop table T_out;
declare
      q2     clob;
      cols   clob;
    begin

      select listagg(''''||r||''' as '||r||' ', ',') within group (order by r)
      into cols from (select distinct r from T);

     q2 :=
     'create table T_out as
      select * from
      (select A, B, r, v from T)
      pivot
      ( sum(v) for r in ('||cols||') )';

      execute immediate q2;
end;
/
</code>```

I tried to turn it in a function:

```<code>CREATE OR REPLACE PROCEDURE transpose(T IN char, riga IN char, classe IN char, valore IN char)
IS
      q1   clob;
      q2   clob;
      cols clob;
BEGIN
      q1 :=
      'select
      listagg(''''''''||'||riga||'||'''''' as ''||'||riga||'||'' '', '','')
      within group (order by '||riga||')
      into cols
      from (select distinct '||riga||' from '||T||')';

     dbms_output.put_line(q1);
     execute immediate(q1);

      q2 :=
     'create table '||T||'_out as
      select * from
      (select '||classe||', '||riga||', '||valore||' from '||T||')
      pivot
      ( sum(v) for  '||riga||' in ('||cols||') )';

    dbms_output.put_line(q2);
    execute immediate(q2);

end;
</code>```

However, running:

```<code>execute transpose('T','r', 'A, B', 'v');
</code>```

I get the error:

```<code>Error starting at line : 35 in command -
BEGIN transpose('T', 'r', 'A, B', 'v'); END;
Error report -
ORA-00905: missing keyword
ORA-06512: at "USER12345.TRANSPOSE", line 18
ORA-06512: at line 1
00905. 00000 -  "missing keyword"
*Cause:
*Action:
</code>```

The issue is in executing the "q1" query, but I cannot figure out what the missing keyword is...the DBMS output for "q1" seems to be identical to the part running in the script version:

```<code>select listagg(''''||r||''' as '||r||' ', ',')
      within group (order by r)
      into cols
      from (select distinct r from T)
</code>```

答:
I think this is easier if you call listagg with the 2nd parameter ''',''' and then just prepend and append a single '

Also, to debug just print out the generated line -- you will probably see your problem right away (an extra ' I'm guessing).

Body:
I have the script below that pivots (transposes) rows to columns (column names are stored in variable "r", values in "v", while "A" and "B" are the identifiers that will remain on the rows after pivoting):

drop table T_out;
declare
      q2     clob;
      cols   clob;
    begin

      select listagg(''''||r||''' as '||r||' ', ',') within group (order by r)
      into cols from (select distinct r from T);

     q2 :=
     'create table T_out as
      select * from
      (select A, B, r, v from T)
      pivot
      ( sum(v) for r in ('||cols||') )';

      execute immediate q2;
end;
/

I tried to turn it in a function:

CREATE OR REPLACE PROCEDURE transpose(T IN char, riga IN char, classe IN char, valore IN char)
IS
      q1   clob;
      q2   clob;
      cols clob;
BEGIN
      q1 :=
      'select
      listagg(''''''''||'||riga||'||'''''' as ''||'||riga||'||'' '', '','')
      within group (order by '||riga||')
      into cols
      from (select distinct '||riga||' from '||T||')';

     dbms_output.put_line(q1);
     execute immediate(q1);

      q2 :=
     'create table '||T||'_out as
      select * from
      (select '||classe||', '||riga||', '||valore||' from '||T||')
      pivot
      ( sum(v) for  '||riga||' in ('||cols||') )';

    dbms_output.put_line(q2);
    execute immediate(q2);

end;

However, running:

execute transpose('T','r', 'A, B', 'v');

I get the error:

Error starting at line : 35 in command -
BEGIN transpose('T', 'r', 'A, B', 'v'); END;
Error report -
ORA-00905: missing keyword
ORA-06512: at "USER12345.TRANSPOSE", line 18
ORA-06512: at line 1
00905. 00000 -  "missing keyword"
*Cause:
*Action:

The issue is in executing the "q1" query, but I cannot figure out what the missing keyword is...the DBMS output for "q1" seems to be identical to the part running in the script version:

select listagg(''''||r||''' as '||r||' ', ',')
      within group (order by r)
      into cols
      from (select distinct r from T)


问:
How to create dynamic self-sizing height UITableViewCell in swift?
Hey I have a tableview controller and I want to create dynamic cell height with label and ImageViews. I tried something like below but it doesn't work for me. Where is the mistake about code. Any idea ?</p>

```<code>class NotificationsPageController: UITableViewController{

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.register(NotificationCell.self, forCellReuseIdentifier: notCell)
    view.backgroundColor = .black
    tableView.estimatedRowHeight = 60
}

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableView.automaticDimension
}

    override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
      return 60
  }

 class NotificationCell: UITableViewCell {

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
      super.init(style: style, reuseIdentifier: reuseIdentifier)
   backgroundColor = UIColor(red: 18/255, green: 18/255, blue: 18/255, alpha: 1)

    setNotificationAnchors()

}

fileprivate func setNotificationAnchors() {

    addSubview(notiType)
    notiType.anchor(top: topAnchor, left: leftAnchor, bottom: nil, right: rightAnchor, paddingTop: 4, paddingLeft: 6, paddingBottom: 0, paddingRight: 20, width: 0, height: 0)
    //notiType.centerYAnchor.constraint(equalTo: notiImage.centerYAnchor).isActive = true

    addSubview(notiImage)
    notiImage.anchor(top: nil, left: nil, bottom: nil, right: rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 4, width: 0, height: 0)
    notiImage.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true

}

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
}
</code>```

答:
Follow the steps below:

Add the below lines in ViewDidLoad

```<code>tableView.dataSource = self
tableView.delegate = self

// Set automatic dimensions for row height
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = UITableViewAutomaticDimension
</code>```

In XIB or Cell if you have label update the numberOLines = 0 and make the lineBreakMode = truncateTail

Update constraints to top, bottom, right and left  to its superView

Body:
Hey I have a tableview controller and I want to create dynamic cell height with label and ImageViews. I tried something like below but it doesn't work for me. Where is the mistake about code. Any idea ?

class NotificationsPageController: UITableViewController{

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.register(NotificationCell.self, forCellReuseIdentifier: notCell)
    view.backgroundColor = .black
    tableView.estimatedRowHeight = 60
}

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableView.automaticDimension
}

    override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
      return 60
  }

 class NotificationCell: UITableViewCell {

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
      super.init(style: style, reuseIdentifier: reuseIdentifier)
   backgroundColor = UIColor(red: 18/255, green: 18/255, blue: 18/255, alpha: 1)

    setNotificationAnchors()

}

fileprivate func setNotificationAnchors() {

    addSubview(notiType)
    notiType.anchor(top: topAnchor, left: leftAnchor, bottom: nil, right: rightAnchor, paddingTop: 4, paddingLeft: 6, paddingBottom: 0, paddingRight: 20, width: 0, height: 0)
    //notiType.centerYAnchor.constraint(equalTo: notiImage.centerYAnchor).isActive = true

    addSubview(notiImage)
    notiImage.anchor(top: nil, left: nil, bottom: nil, right: rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 4, width: 0, height: 0)
    notiImage.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true

}

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
}

Body:
Follow the steps below:

Add the below lines in ViewDidLoad

tableView.dataSource = self
tableView.delegate = self

// Set automatic dimensions for row height
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = UITableViewAutomaticDimension

In XIB or Cell if you have label update the numberOLines = 0 and make the lineBreakMode = truncateTail

Update constraints to top, bottom, right and left  to its superView


问:
How to delete all objects from a S3 folder of various sub folder with Specific name which are older than n days using AWS Ruby SDK
I have a requirement to delete files with prefix application.log which are older than 5 days in an S3 folder.

The file is present inside log-bucket/main-shell/apps/app-main-shell-55f79d74fc-4sx6c/helpkit.

Is there a way where we can list and delete files recursively using AWS Ruby SDK?

答:
If you want to perform a 1-time clean-up of objects under a single key prefix, you can use the batch operations on the objects collection.

```<code>s3 = Aws::S3::Resource.new()

s3.bucket('bucket-name').objects(prefix: 'some/key/prefix/').batch_delete!
</code>```

This will list objects with the given key prefix and then issue a batch delete for each page of results. The more objects with the given prefix, the more api calls. It should be 2 requests (1x list, 1x batch delete) per 1k objects to delete.

Please note, this is a destructive operation. Make sure you key prefix is correct before you issue the batch delete.

If you want to do this on a frequent basis, then I would use a bucket lifecycle configuration.

Body:
If you want to perform a 1-time clean-up of objects under a single key prefix, you can use the batch operations on the objects collection.

s3 = Aws::S3::Resource.new()

s3.bucket('bucket-name').objects(prefix: 'some/key/prefix/').batch_delete!

This will list objects with the given key prefix and then issue a batch delete for each page of results. The more objects with the given prefix, the more api calls. It should be 2 requests (1x list, 1x batch delete) per 1k objects to delete.

Please note, this is a destructive operation. Make sure you key prefix is correct before you issue the batch delete.

If you want to do this on a frequent basis, then I would use a bucket lifecycle configuration.


问:
How can I get a character array from a string?
How do you convert a string to a character array in JavaScript?

I'm thinking getting a string like "Hello world!" to the array

['H','e','l','l','o',' ','w','o','r','l','d','!']

答:
One possibility is the next:</p>

```<code>console.log([1, 2, 3].map(e => Math.random().toString(36).slice(2)).join('').split('').map(e => Math.random() > 0.5 ? e.toUpperCase() : e).join(''));
</code>```

Body:
One possibility is the next:

console.log([1, 2, 3].map(e => Math.random().toString(36).slice(2)).join('').split('').map(e => Math.random() > 0.5 ? e.toUpperCase() : e).join(''));


问:
problem in laravel route on tackling the response of payment gateway
I'm using laravel and integrate the payment gateway.when i send the post request then after success or cancellation ,it redirect the referece id like this
http://localhost/multi_vendor/user/paypal/return?flwref=FLW-MOCK-d4f7572650fbe61ecff7fb17a7129859&txref=rave-bxw7c98dymo8so0kwosco0wwscs8ogc
so how can tackle it in laravel?

I made route for this

```<code>Route::get('/paypal/return', 'User\PaypalController@payreturn')->name('user.payment.return');
</code>```

答:
You can create a route as you write above:-

```<code>Route::get('/paypal/return', 'User\PaypalController@payreturn')->name('user.payment.return');
</code>```

Then in User\PaypalController Controller method payreturn, you can do as following:-

```<code><?php

namespace App\Http\Controllers\User;

use Illuminate\Http\Request;
class PaypalController extends Controller
{

public function payreturn(Request $request)
{
//Here you can get the response request values
$ref = $request->flwref;
$TxRef = $request->txref;

}
}
</code>```

Body:
I'm using laravel and integrate the payment gateway.when i send the post request then after success or cancellation ,it redirect the referece id like this
http://localhost/multi_vendor/user/paypal/return?flwref=FLW-MOCK-d4f7572650fbe61ecff7fb17a7129859&txref=rave-bxw7c98dymo8so0kwosco0wwscs8ogc
so how can tackle it in laravel?

I made route for this

Route::get('/paypal/return', 'User\PaypalController@payreturn')->name('user.payment.return');

Body:
You can create a route as you write above:-

Route::get('/paypal/return', 'User\PaypalController@payreturn')->name('user.payment.return');

Then in User\PaypalController Controller method payreturn, you can do as following:-

<?php

namespace App\Http\Controllers\User;

use Illuminate\Http\Request;
class PaypalController extends Controller
{

public function payreturn(Request $request)
{
//Here you can get the response request values
$ref = $request->flwref;
$TxRef = $request->txref;

}
}


问:
Authenticate the Test User { "error_type": "OAuthException", "code": 400, "error_message": "Invalid platform app" }
I'm trying to recover the access token via the Instagram Basic Display API but when trying to authenticate the test user I get this error:

```<code>{
    "error_type": "OAuthException",
    "code": 400,
    "error_message": "Invalid platform app"
}
</code>```

I expect to see the app authorization screen

答:
I had a similar issue and was able to resolve it by setting the content type of the request to application/x-www-form-urlencoded. below is a c# example showing how to execute the request:</p>

```<code>public async Task<UserTokenResponseModel> GetUserToken(string code)
    {
        var url =
            $"https://api.instagram.com/oauth/access_token";

        var request = new HttpRequestMessage(HttpMethod.Post, url);

        var client = _httpClientFactory.CreateClient();

        var requestContent = new List<KeyValuePair<string, string>>();
        requestContent.Add(new KeyValuePair<string, string>("client_id", ClientId));
        requestContent.Add(new KeyValuePair<string, string>("client_secret", Secret));
        requestContent.Add(new KeyValuePair<string, string>("grant_type", "authorization_code"));
        requestContent.Add(new KeyValuePair<string, string>("code", code));
        requestContent.Add(new KeyValuePair<string, string>("redirect_uri", "https://localhost:44315/instagram/authorizecallback"));

        request.Content = new FormUrlEncodedContent(requestContent);

        var response = await client.SendAsync(request);
        var content = await response.Content.ReadAsStringAsync();

        if (!response.IsSuccessStatusCode)
        {
            throw new Exception(content);
        }

        return JsonConvert.DeserializeObject<UserTokenResponseModel>(content);
    }
</code>```

Body:
I'm trying to recover the access token via the Instagram Basic Display API but when trying to authenticate the test user I get this error:

{
    "error_type": "OAuthException",
    "code": 400,
    "error_message": "Invalid platform app"
}

I expect to see the app authorization screen

Body:
I had a similar issue and was able to resolve it by setting the content type of the request to application/x-www-form-urlencoded. below is a c# example showing how to execute the request:

public async Task<UserTokenResponseModel> GetUserToken(string code)
    {
        var url =
            $"https://api.instagram.com/oauth/access_token";

        var request = new HttpRequestMessage(HttpMethod.Post, url);

        var client = _httpClientFactory.CreateClient();

        var requestContent = new List<KeyValuePair<string, string>>();
        requestContent.Add(new KeyValuePair<string, string>("client_id", ClientId));
        requestContent.Add(new KeyValuePair<string, string>("client_secret", Secret));
        requestContent.Add(new KeyValuePair<string, string>("grant_type", "authorization_code"));
        requestContent.Add(new KeyValuePair<string, string>("code", code));
        requestContent.Add(new KeyValuePair<string, string>("redirect_uri", "https://localhost:44315/instagram/authorizecallback"));

        request.Content = new FormUrlEncodedContent(requestContent);

        var response = await client.SendAsync(request);
        var content = await response.Content.ReadAsStringAsync();

        if (!response.IsSuccessStatusCode)
        {
            throw new Exception(content);
        }

        return JsonConvert.DeserializeObject<UserTokenResponseModel>(content);
    }


答: You may want to try a cubic spline interpolation.  See user14717's comment here: Is there a Python library for exponential spline interpolation?.</p>

Title: Python fit data with two exponential forcing continuity

Body:
I am trying to fit the following data

-0.63711376853067669         3.9220188494898451E-011
-0.63559581662374798         4.0260809194317929E-011
-0.63285142318966769         3.7912990158726701E-011
-0.62862863903207122         3.5672466225770418E-011
-0.61915221010943133         3.7041163107924007E-011
-0.60375425889771406         3.7285669699125165E-011
-0.58732715127701596         3.7394414631650330E-011
-0.57049365955914244         3.2793779625097831E-011
-0.55124131200928772         3.3971194033698993E-011
-0.53006060696473212         3.2621926101891416E-011
-0.51035174210462519         3.1395671276394652E-011
-0.48878691498652033         3.3494235593570817E-011
-0.46512080762899560         3.3900831760049202E-011
-0.44144526036934528         3.0434293196110948E-011
-0.41209308065708727         2.4384175101726714E-011
-0.37874291229989432         2.1968353922587969E-011
-0.34595367786265058         2.3395823530179207E-011
-0.31308483194132991         2.2938006752405643E-011
-0.28065779622875503         2.3677078958452214E-011
-0.24589470583567491         2.1177013468924604E-011
-0.20893039650026693         2.2047918048544178E-011
-0.17289648629802296         2.2550123367583211E-011
-0.13712730648282492         2.0960188554218161E-011
-0.10215401377673781         2.2996586055725922E-011
-6.7845096564425861E-002     2.0922405016890511E-011
-3.3994983294004487E-002     2.1451489580936361E-011
 0.0000000000000000          2.1859042406659546E-011

by using two exponential functions. One (blue) should fit the first half of them, and the other (red) the second half. The problem is that, since there is a gap, the continuity of the function is not granted. I would like to fit the second part by requiring that the red curve starts where the blue one ends (see figure below for better clarity). How can I impose this condition? Bounding parameters is not enough since the exponential match is achieved through an equation.

import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit

def dexp(x, b, c):
    return np.exp( b*x + c )

fig1 = plt.figure( figsize=(10,10) )
ax1 = fig1.add_subplot(111)

data = np.genfromtxt('mwe.dat')
ax1.plot(data[:,0], data[:,1], 'k+')

half = len(data)//2

popt, pcov = curve_fit( dexp, data[:half,0], data[:half,1], maxfev=100000)
x = np.linspace( np.min( data[:half,0] ), np.max( data[:half,0] ), half )
ax1.plot( x, dexp( x, *popt), 'b--', linewidth=3)

popt, pcov = curve_fit(dexp, data[half-1:,0], data[half-1:,1])
x = np.linspace( np.min( data[half-1:,0] ), np.max( data[half-1:,0] ), half )
ax1.plot( x, dexp( x, *popt), 'r--', linewidth=3)

fig1.show()

Fit_picture


问:
What is a good definition of a "userdata pointer"?
I have searched for a good explanation but can't find one.

I could try to write one myself but I'd prefer if someone with better english could help me explain this for Zan Lynx in the comment here.

...and it seems like there should be a good explanation somewhere, why not here?

答:
Look at sqlite3_exec() – it calls a callback (third parameter) for each retrieved row and passes a pointer you provide (fourth parameter) into this callback. This can be a pointer to whatever object you wish – you have to cast it appropriately before you can access the pointed object. This object is called a userdata object and a pointer to it is called a userdata pointer.

In case of sqlite3_exec() you can pass a pointer to a container which is to store all the retrieved table rows upon the request completion.

OwnerDisplayName: epatel

ContentLicense: CC BY-SA 2.5


问:
Why I feel AWS SageMaker GPU not faster?
I spent 5 days configuring AWS SageMaker. ( contacting to increase GPU notebook limit costs 2 days, downloading and unzip all data cost 2 days, detours such as uploading data to S3 costs 1 day).

When I finally can run code on the SageMaker GPU notebook instance, I found the speed is not faster than my local CPU PC.

I used the following code to check GPU. Not sure what's going wrong. Does this happen to you pals? And my credits only have $200 left (Original $750).

答:
The problem should lie in video loading. When I train a Resnet model on an image dataset, the speed is pretty fast!! Thank you AWS !!

Regarding video loading strategy, I made this kernel for the comparison of different methods.

https://www.kaggle.com/muerbingsha/deepfake-face-detector-evaluate

It turns out imageio_ffmpeg is the fastest way.


问:
Multiple event listener on the same object not working
Is it possible to have two listener listening to the same event? I have an event listener listening for the oncanplay video event, and in some other class, in this example the test class, I have to listen to the same event.

```<code><!DOCTYPE html>
<html>
<body>

<button onclick="playVid()" type="button">Play Video</button>
<button onclick="pauseVid()" type="button">Pause Video</button><br>

<video id="myVideo" width="320" height="176" autoplay>
  <source src="mov_bbb.mp4" type="video/mp4">
  <source src="mov_bbb.ogg" type="video/ogg">
  Your browser does not support HTML5 video.
</video>

<script>

const test = () => {

  vid.oncanplay = function() {
  console.log("CAN PLAY 2!")
};
}

var vid = document.getElementById("myVideo");
test();

  vid.oncanplay = function() {
  console.log("CAN PLAY 1!")
};

function playVid() {
  vid.play();
}

function pauseVid() {
  vid.pause();
}
</script>

</body>
</html>
</code>```

In this case only CAN PLAY 1 will be fired. If I remove the CAN PLAY 1 listener, CAN PLAY 2 will than be fired. Can I have both event be fired?

答:
Only the LAST event handler assigned gets run, because you assigned them as properties.
Try use addEventListener() instead.

Body:
Is it possible to have two listener listening to the same event? I have an event listener listening for the oncanplay video event, and in some other class, in this example the test class, I have to listen to the same event.

<!DOCTYPE html>

<button onclick="playVid()" type="button">Play Video</button>
<button onclick="pauseVid()" type="button">Pause Video</button>

<video id="myVideo" width="320" height="176" autoplay>
  <source src="mov_bbb.mp4" type="video/mp4">
  <source src="mov_bbb.ogg" type="video/ogg">
  Your browser does not support HTML5 video.
</video>

In this case only CAN PLAY 1 will be fired. If I remove the CAN PLAY 1 listener, CAN PLAY 2 will than be fired. Can I have both event be fired?


问:
Can a JS script block a whole server? If so, how can I possibly get rid of this attack?
We are using MySQL db and Apache as our server. All of our project folders are affected by a particular script called "y.js/a.js" which is blocking our whole .js files and sits before  that triggers 404 error. The URL it all refers to is https://tom.verybeatifulantony.com/a.js (or) https://tom.verybeatifulantony.com/y.js. It calls this same js files in each and every project.

The following are the screenshots below:

答:
we have noticed this script being inserted in HTML and PHP files in many of our hosted sites as well. this appears to be some sort of malicious code.  you will need to remove this script from every file where the script has been inserted.

on Linux, go to the root directory of where all your sites are located, or to the root of each site and execute the following to get a list of all files infected.

```<code>sudo grep --include=\*.{js,html,htm,php} -rnw '.' -e "tom.verybeatifulantony.com"
</code>```

Body:
we have noticed this script being inserted in HTML and PHP files in many of our hosted sites as well. this appears to be some sort of malicious code.  you will need to remove this script from every file where the script has been inserted.

on Linux, go to the root directory of where all your sites are located, or to the root of each site and execute the following to get a list of all files infected.

sudo grep --include=\*.{js,html,htm,php} -rnw '.' -e "tom.verybeatifulantony.com"


问:
BEGIN TRY and EXECUTE dynamic simple query error
when I execute attached query I get error:

Msg 0, Level 11, State 0, Line 0 A severe error occurred on the
  current command.  The results, if any, should be discarded.

When try-catch is commented then it works, same when other column is used.
When partition by is removed it also works.

Can someone say where is the root of error here or is it some sql server bug?

Query:

```<code>BEGIN TRY
    DECLARE  @vSqlCmd NVARCHAR(MAX) = N'
    SELECT TOP 1 V = d.collation_name, C = COUNT(1) OVER (PARTITION BY d.collation_name)
    FROM sys.all_columns d;';
    SELECT @vSqlCmd;

    EXECUTE (@vSqlCmd);
END TRY
BEGIN CATCH
    PRINT 'CATCH!!!';

    THROW;
END CATCH
</code>```

答:
This is a bug. I have reported it here

It is not clear why you need this query, the following explains the issue and how to avoid it if there is some reasonable reason for needing this query.

The following query returns two object_ids -103085222 and -593

```<code>SELECT object_id ,name
FROM sys.system_columns
where system_type_id in (35,99,167,175,231,239) and collation_name IS NULL
</code>```

These relate to the objects below

```<code>+------------+----------------------------------+
|     id     |               name               |
+------------+----------------------------------+
| -103085222 | pdw_nodes_pdw_physical_databases |
|       -593 | pdw_table_mappings               |
+------------+----------------------------------+
</code>```

For some reason both of these have a string column (called physical_name) that SQL Server can not resolve the collation for. As these objects are only relevant to Parallel Data Warehouse and don't even properly exist in other versions of the product this is not usually a problem.

sys.all_columns references the sys.system_columns view which uses the following expression for collation_name : convert(sysname, ColumnPropertyEx(object_id, name, 'collation'))

A simpler case that reproduces the issue is

```<code>BEGIN TRY
    SELECT columnpropertyex(-593, 'physical_name', 'collation')
END TRY
BEGIN CATCH
END CATCH
</code>```

Or

```<code>SET XACT_ABORT ON;
SELECT columnpropertyex(-593, 'physical_name', 'collation')
</code>```

Both return

Msg 0, Level 11, State 0, Line 33

A severe error occurred on the
  current command.  The results, if any, should be discarded.

When run outside the TRY block this returns NULL (when XACT_ABORT is off). Behind the scenes it throws an exception that is handled internally and the end user is unaware. The call stack when the exception is thrown shows that GetColumnCollate function ends up using the Algebrizer to try and resolve the column and it eventually fails in CAlgTableMetadata::RaiseBadTableException (possibly as a related object definition is missing somewhere).

When run in the TRY ... CATCH context or with XACT_ABORT ON something goes wrong with the bit that is supposed to silently ignore the error and return NULL. Inserting a duplicate key into an index with ignore_dup_key ON also raises an internal error that is ignored but does not have the same problem.

So one way of resolving the issue is to wrap the reference to collation_name in a CASE expression so it is never evaluated for those two problematic object_id when run inside the TRY block.

```<code>  BEGIN TRY
    DECLARE  @vSqlCmd NVARCHAR(MAX) = N'
    SELECT TOP 1 V = ca.safe_collation_name, C = COUNT(1) OVER (PARTITION BY ca.safe_collation_name)
    FROM sys.all_columns d
    CROSS APPLY (SELECT CASE WHEN object_id NOT IN (-593,-103085222) THEN collation_name END) ca(safe_collation_name);
    ';
    SELECT @vSqlCmd;

    EXECUTE (@vSqlCmd);
END TRY
BEGIN CATCH
    PRINT 'CATCH!!!';

    THROW;
END CATCH
</code>```

This does not protect you against different cases of problematic metadata being added to the product in the future. Again I question the need for this query however. The query you have provided is so odd that it is difficult to advise you what you should replace it with.

Body:
when I execute attached query I get error:

Msg 0, Level 11, State 0, Line 0 A severe error occurred on the
  current command.  The results, if any, should be discarded.

When try-catch is commented then it works, same when other column is used.
When partition by is removed it also works.

Can someone say where is the root of error here or is it some sql server bug?

Query:

BEGIN TRY
    DECLARE  @vSqlCmd NVARCHAR(MAX) = N'
    SELECT TOP 1 V = d.collation_name, C = COUNT(1) OVER (PARTITION BY d.collation_name)
    FROM sys.all_columns d;';
    SELECT @vSqlCmd;

    EXECUTE (@vSqlCmd);
END TRY
BEGIN CATCH
    PRINT 'CATCH!!!';

    THROW;
END CATCH

Body:
This is a bug. I have reported it here

It is not clear why you need this query, the following explains the issue and how to avoid it if there is some reasonable reason for needing this query.

The following query returns two object_ids -103085222 and -593

SELECT object_id ,name
FROM sys.system_columns
where system_type_id in (35,99,167,175,231,239) and collation_name IS NULL

These relate to the objects below

+------------+----------------------------------+
|     id     |               name               |
+------------+----------------------------------+
| -103085222 | pdw_nodes_pdw_physical_databases |
|       -593 | pdw_table_mappings               |
+------------+----------------------------------+

For some reason both of these have a string column (called physical_name) that SQL Server can not resolve the collation for. As these objects are only relevant to Parallel Data Warehouse and don't even properly exist in other versions of the product this is not usually a problem.

sys.all_columns references the sys.system_columns view which uses the following expression for collation_name : convert(sysname, ColumnPropertyEx(object_id, name, 'collation'))

A simpler case that reproduces the issue is

BEGIN TRY
    SELECT columnpropertyex(-593, 'physical_name', 'collation')
END TRY
BEGIN CATCH
END CATCH

Or

SET XACT_ABORT ON;
SELECT columnpropertyex(-593, 'physical_name', 'collation')

Both return

Msg 0, Level 11, State 0, Line 33

A severe error occurred on the
  current command.  The results, if any, should be discarded.

When run outside the TRY block this returns NULL (when XACT_ABORT is off). Behind the scenes it throws an exception that is handled internally and the end user is unaware. The call stack when the exception is thrown shows that GetColumnCollate function ends up using the Algebrizer to try and resolve the column and it eventually fails in CAlgTableMetadata::RaiseBadTableException (possibly as a related object definition is missing somewhere).

When run in the TRY ... CATCH context or with XACT_ABORT ON something goes wrong with the bit that is supposed to silently ignore the error and return NULL. Inserting a duplicate key into an index with ignore_dup_key ON also raises an internal error that is ignored but does not have the same problem.

So one way of resolving the issue is to wrap the reference to collation_name in a CASE expression so it is never evaluated for those two problematic object_id when run inside the TRY block.

  BEGIN TRY
    DECLARE  @vSqlCmd NVARCHAR(MAX) = N'
    SELECT TOP 1 V = ca.safe_collation_name, C = COUNT(1) OVER (PARTITION BY ca.safe_collation_name)
    FROM sys.all_columns d
    CROSS APPLY (SELECT CASE WHEN object_id NOT IN (-593,-103085222) THEN collation_name END) ca(safe_collation_name);
    ';
    SELECT @vSqlCmd;

    EXECUTE (@vSqlCmd);
END TRY
BEGIN CATCH
    PRINT 'CATCH!!!';

    THROW;
END CATCH

This does not protect you against different cases of problematic metadata being added to the product in the future. Again I question the need for this query however. The query you have provided is so odd that it is difficult to advise you what you should replace it with.


问:
How to embed one React-Admin component inside another; multiple Admin components
Is this possible?
I'd like to use one <Admin to display other imported <Admin components.  I'm hoping to do something like this where MyTool is an imported <Admin component:

```<code>    <Admin layout={MyLayout}
           dataProvider={myDataProvider}
           customRoutes={[
               <Route
                   exact
                   path="/tools"
                   component={(props) => <MyTool {...props} />}/>

           ]}>
    </Admin>
</code>```

答:
I did try wrapping each <Admin in my own Provider without any success so I'm considering Francois Z. answer to be definitive.

react-admin maintainer here: this has never been a requirement of react-admin, and I've never tested it. It probably won't work, and I personally think it's a bad idea. – François Zaninotto 5 hours ago

Body:
Is this possible?
I'd like to use one <Admin to display other imported <Admin components.  I'm hoping to do something like this where MyTool is an imported <Admin component:

    <Admin layout={MyLayout}
           dataProvider={myDataProvider}
           customRoutes={[
               <Route
                   exact
                   path="/tools"
                   component={(props) => <MyTool {...props} />}/>

           ]}>
    </Admin>


问:
Join lookup table on lowest-level/most detailed field value first
I have two tables that I am trying to left join based on a single field in SQL Server 2014, but the problem is that this single field contains a value which relates to one of four "levels" that appear in separate columns in the main table. The SalesOrg field is also part of the key since there can be more than one sales org in both the transactional and lookup tables.

Here's the main transactional table:

```<code>SalesOrg     PHLevel1    PHLevel2    PHLevel3    PHLevel4    SalesQty
-----------------------------------------------------------------------
AB1          Z000        Y000        X000        V000        20
AB1          Z000        Y000        X000        V001        30
AB1          Z001        Y000        X001        V001        10
AB1          Z001        Y001        X000        V003        45
AB1          Z001        Y001        X000        V004        48
AB1          Z002        Y003        X002        V005        67
</code>```

Here's the lookup table I'm trying to join onto the transactional table:

```<code>SalesOrg     PH              PHLevel      SalesRep
--------------------------------------------------
AB1          <null>          0            Mr. Pink
AB1          Z000            1            Mr. White
AB1          Z001            1            Mr. White
AB1          Z001Y000        2            Mr. Orange
AB1          Z001Y001        2            Mr. Orange
AB1          Z001Y001X000    3            Mr. Blonde
</code>```

So what should happen is that the "lowest" (i.e. highest PHLevel, 3) should be matched first, i.e.:

```<code>SalesOrg     PHLevel1    PHLevel2    PHLevel3    PHLevel4    SalesQty    SalesRep
---------------------------------------------------------------------------------
AB1          Z000        Y000        X000        V000        20
AB1          Z000        Y000        X000        V001        30
AB1          Z001        Y000        X001        V001        10
AB1          Z001        Y001        X000        V003        45          Mr. Blonde
AB1          Z001        Y001        X000        V004        48          Mr. Blonde
AB1          Z002        Y003        X002        V005        67
</code>```

Then we need to match level 2 that hasn't already been matched using level 3:

```<code>SalesOrg     PHLevel1    PHLevel2    PHLevel3    PHLevel4    SalesQty    SalesRep
---------------------------------------------------------------------------------
AB1          Z000        Y000        X000        V000        20
AB1          Z000        Y000        X000        V001        30
AB1          Z001        Y000        X001        V001        10          Mr. Orange
AB1          Z001        Y001        X000        V003        45          Mr. Blonde
AB1          Z001        Y001        X000        V004        48          Mr. Blonde
AB1          Z002        Y003        X002        V005        67
</code>```

Then we need to match level 1 that hasn't already been matched using level 2 or 3:

```<code>SalesOrg     PHLevel1    PHLevel2    PHLevel3    PHLevel4    SalesQty    SalesRep
---------------------------------------------------------------------------------
AB1          Z000        Y000        X000        V000        20          Mr. White
AB1          Z000        Y000        X000        V001        30          Mr. White
AB1          Z001        Y000        X001        V001        10          Mr. Orange
AB1          Z001        Y001        X000        V003        45          Mr. Blonde
AB1          Z001        Y001        X000        V004        48          Mr. Blonde
AB1          Z002        Y003        X002        V005        67
</code>```

Finally, for any remaining items, we need to check level 0, which is the default for "unmatched" entries:

```<code>SalesOrg     PHLevel1    PHLevel2    PHLevel3    PHLevel4    SalesQty    SalesRep
---------------------------------------------------------------------------------
AB1          Z000        Y000        X000        V000        20          Mr. White
AB1          Z000        Y000        X000        V001        30          Mr. White
AB1          Z001        Y000        X001        V001        10          Mr. Orange
AB1          Z001        Y001        X000        V003        45          Mr. Blonde
AB1          Z001        Y001        X000        V004        48          Mr. Blonde
AB1          Z002        Y003        X002        V005        67          Mr. Pink
</code>```

It is no problem if a concatenated field is created in the transactional table to make it easier to match the lookup table.

I am not sure if it would be advantageous to expand the lookup table so that the PH field contains "fully-qualified" values (i.e. so that PH always contains PHLevel1/PHLevel2/PHLevel3/PHLevel4 values, e.g. Z001Y000X001V001) but this could then make the lookup table huge and then possibly slow down the join (since the transactional table can contain perhaps a million rows).

I am not sure how to start with this, since I've seen other examples with hierarchies, but the lookup table is not exactly a hierarchy - are there any elegant solutions in SQL please?

答:
This looks like an opportunity for apply:

```<code>select t.*, l.salesrep
from transactional t outer apply
     (select top (1) l.*
      from lookup l
      where l.ph in (t.PHLevel + t.PHLevel2 + t.PHLevel3, t.PHLevel + t.PHLevel2, t.PHLevel) or
            l.ph is null
      order by l.phlevel desc
     ) l;
</code>```

You can easily add PHLevel4 to the search list.  Part of your question suggests that you want to include it, but it is not in the detailed example.

Body:
I have two tables that I am trying to left join based on a single field in SQL Server 2014, but the problem is that this single field contains a value which relates to one of four "levels" that appear in separate columns in the main table. The SalesOrg field is also part of the key since there can be more than one sales org in both the transactional and lookup tables.

Here's the main transactional table:

SalesOrg     PHLevel1    PHLevel2    PHLevel3    PHLevel4    SalesQty
-----------------------------------------------------------------------
AB1          Z000        Y000        X000        V000        20
AB1          Z000        Y000        X000        V001        30
AB1          Z001        Y000        X001        V001        10
AB1          Z001        Y001        X000        V003        45
AB1          Z001        Y001        X000        V004        48
AB1          Z002        Y003        X002        V005        67

Here's the lookup table I'm trying to join onto the transactional table:

SalesOrg     PH              PHLevel      SalesRep
--------------------------------------------------
AB1          <null>          0            Mr. Pink
AB1          Z000            1            Mr. White
AB1          Z001            1            Mr. White
AB1          Z001Y000        2            Mr. Orange
AB1          Z001Y001        2            Mr. Orange
AB1          Z001Y001X000    3            Mr. Blonde

So what should happen is that the "lowest" (i.e. highest PHLevel, 3) should be matched first, i.e.:

SalesOrg     PHLevel1    PHLevel2    PHLevel3    PHLevel4    SalesQty    SalesRep
---------------------------------------------------------------------------------
AB1          Z000        Y000        X000        V000        20
AB1          Z000        Y000        X000        V001        30
AB1          Z001        Y000        X001        V001        10
AB1          Z001        Y001        X000        V003        45          Mr. Blonde
AB1          Z001        Y001        X000        V004        48          Mr. Blonde
AB1          Z002        Y003        X002        V005        67

Then we need to match level 2 that hasn't already been matched using level 3:

SalesOrg     PHLevel1    PHLevel2    PHLevel3    PHLevel4    SalesQty    SalesRep
---------------------------------------------------------------------------------
AB1          Z000        Y000        X000        V000        20
AB1          Z000        Y000        X000        V001        30
AB1          Z001        Y000        X001        V001        10          Mr. Orange
AB1          Z001        Y001        X000        V003        45          Mr. Blonde
AB1          Z001        Y001        X000        V004        48          Mr. Blonde
AB1          Z002        Y003        X002        V005        67

Then we need to match level 1 that hasn't already been matched using level 2 or 3:

SalesOrg     PHLevel1    PHLevel2    PHLevel3    PHLevel4    SalesQty    SalesRep
---------------------------------------------------------------------------------
AB1          Z000        Y000        X000        V000        20          Mr. White
AB1          Z000        Y000        X000        V001        30          Mr. White
AB1          Z001        Y000        X001        V001        10          Mr. Orange
AB1          Z001        Y001        X000        V003        45          Mr. Blonde
AB1          Z001        Y001        X000        V004        48          Mr. Blonde
AB1          Z002        Y003        X002        V005        67

Finally, for any remaining items, we need to check level 0, which is the default for "unmatched" entries:

SalesOrg     PHLevel1    PHLevel2    PHLevel3    PHLevel4    SalesQty    SalesRep
---------------------------------------------------------------------------------
AB1          Z000        Y000        X000        V000        20          Mr. White
AB1          Z000        Y000        X000        V001        30          Mr. White
AB1          Z001        Y000        X001        V001        10          Mr. Orange
AB1          Z001        Y001        X000        V003        45          Mr. Blonde
AB1          Z001        Y001        X000        V004        48          Mr. Blonde
AB1          Z002        Y003        X002        V005        67          Mr. Pink

It is no problem if a concatenated field is created in the transactional table to make it easier to match the lookup table.

I am not sure if it would be advantageous to expand the lookup table so that the PH field contains "fully-qualified" values (i.e. so that PH always contains PHLevel1/PHLevel2/PHLevel3/PHLevel4 values, e.g. Z001Y000X001V001) but this could then make the lookup table huge and then possibly slow down the join (since the transactional table can contain perhaps a million rows).

I am not sure how to start with this, since I've seen other examples with hierarchies, but the lookup table is not exactly a hierarchy - are there any elegant solutions in SQL please?

Body:
This looks like an opportunity for apply:

select t.*, l.salesrep
from transactional t outer apply
     (select top (1) l.*
      from lookup l
      where l.ph in (t.PHLevel + t.PHLevel2 + t.PHLevel3, t.PHLevel + t.PHLevel2, t.PHLevel) or
            l.ph is null
      order by l.phlevel desc
     ) l;

You can easily add PHLevel4 to the search list.  Part of your question suggests that you want to include it, but it is not in the detailed example.


问:
Allow resize to ignore max-height?
I have some code like the first snippet - I am curious if there is a way to use resize and allow it to ignore max-height?

The reason I don't just use height is I want the div to fit the first piece of content without white space. I included that at the end if you want to check it out.

Basically I am trying to get something that looks like the first one, but functions like the second one.

Thanks!

.content {
  max-height: 5em;
 overflow-y: auto;
 resize: vertical;
  white-space: pre-wrap;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content">One line</div>
<div class="content">Multi
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
line</div></code>```

This doesn't work for what I'm trying to do due to the excess whitespace:

.content {
  height: 5em;
 overflow-y: auto;
 resize: vertical;
  white-space: pre-wrap;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content">One line</div>
<div class="content">Multi
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
line</div></code>```

In response to the first answer, the content is dynamic. I have provided a dynamic example

rand1 = Math.floor((Math.random() * 10) + 1);
rand2 = Math.floor((Math.random() * 10) + 1);
document.getElementById("1").innerHTML = "Start"
for (var i = 0; i < rand1; i++) {
  document.getElementById("1").innerHTML += ".\n"
}
document.getElementById("2").innerHTML = "Start"
for (var i = 0; i < rand2; i++) {
  document.getElementById("2").innerHTML += ".\n"
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.content {
  max-height: 5em;
  overflow-y: auto;
  resize: vertical;
  white-space: pre-wrap;
}</code>```

```

答:
The question is not really clear. Seems that you want a dynamically heigh first container and a maxed height second one, is it?

If you want something that is filling up the first div as much as content in it, you can use a min-height for the first container and just use max-height just for the second one.

Title: Allow resize to ignore max-height?

Body:
I have some code like the first snippet - I am curious if there is a way to use resize and allow it to ignore max-height?

The reason I don't just use height is I want the div to fit the first piece of content without white space. I included that at the end if you want to check it out.

Basically I am trying to get something that looks like the first one, but functions like the second one.

Thanks!

.content {
  max-height: 5em;
 overflow-y: auto;
 resize: vertical;
  white-space: pre-wrap;
 }

One line

Multi
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
line

This doesn't work for what I'm trying to do due to the excess whitespace:

.content {
  height: 5em;
 overflow-y: auto;
 resize: vertical;
  white-space: pre-wrap;
 }

One line

Multi
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
line

In response to the first answer, the content is dynamic. I have provided a dynamic example

rand1 = Math.floor((Math.random() * 10) + 1);
rand2 = Math.floor((Math.random() * 10) + 1);
document.getElementById("1").innerHTML = "Start"
for (var i = 0; i < rand1; i++) {
  document.getElementById("1").innerHTML += ".\n"
}
document.getElementById("2").innerHTML = "Start"
for (var i = 0; i < rand2; i++) {
  document.getElementById("2").innerHTML += ".\n"
}

.content {
  max-height: 5em;
  overflow-y: auto;
  resize: vertical;
  white-space: pre-wrap;
}


问:
How to rename a file and overwrite existing in VBS?
I already an existing vbs script to take one file (titled "Running_12345.xlsx") from one location and put it in the folder titled "Folder". This is an hourly file that has a long name based on what time it was run.

Now, I want to rename the file just "Running.xlsx" to remove the constantly changing file name. Initially, this code works, but for any subsequent occurence, it fails because the "Running.xlsx" file has already been renamed once and now already exists. How do I add overwrite logic to this code:

```<code>dim fso
Set fso = CreateObject("Scripting.FileSystemObject")

set oFldr = fso.getfolder("folder")

for each ofile in oFldr.Files
 if lcase(fso.GetExtensionName(ofile.Name)) = "xlsx" then
  ofile.name = "Running.xlsx"
  Exit for
 end if
Next
</code>```

答:
Duh, just delete the file first. The code below does what I want:</p>
```<code>dim fso
Set fso = CreateObject("Scripting.FileSystemObject")

set oFldr = fso.getfolder("C:\Users\...\Desktop\MosaicTransforms\")

fso.DeleteFile("C:\Users\...\Desktop\MosaicTransforms\MosaicFile.xlsx")

for each ofile in oFldr.Files
 if lcase(fso.GetExtensionName(ofile.Name)) = "xlsx" then
  ofile.name = "MosaicFile.xlsx"
  Exit for
 end if
Next
</code>```

Body:
I already an existing vbs script to take one file (titled "Running_12345.xlsx") from one location and put it in the folder titled "Folder". This is an hourly file that has a long name based on what time it was run.

Now, I want to rename the file just "Running.xlsx" to remove the constantly changing file name. Initially, this code works, but for any subsequent occurence, it fails because the "Running.xlsx" file has already been renamed once and now already exists. How do I add overwrite logic to this code:

dim fso
Set fso = CreateObject("Scripting.FileSystemObject")

set oFldr = fso.getfolder("folder")

for each ofile in oFldr.Files
 if lcase(fso.GetExtensionName(ofile.Name)) = "xlsx" then
  ofile.name = "Running.xlsx"
  Exit for
 end if
Next

Body:
Duh, just delete the file first. The code below does what I want:

dim fso
Set fso = CreateObject("Scripting.FileSystemObject")

set oFldr = fso.getfolder("C:\Users\...\Desktop\MosaicTransforms\")

fso.DeleteFile("C:\Users\...\Desktop\MosaicTransforms\MosaicFile.xlsx")

for each ofile in oFldr.Files
 if lcase(fso.GetExtensionName(ofile.Name)) = "xlsx" then
  ofile.name = "MosaicFile.xlsx"
  Exit for
 end if
Next