问:
How to test an abstract superclass in Java
I'm a student studying software development (1st year) and the teaching language we are using is Java. We have covered basics, and most of OOP, but I've been practicing making a Shop Administration System and I've come up against something I can't reckon with.

I'm trying to unit test two classes which are both abstract superclasses of several other classes I plan on implementing, as per the UML below

Person Superclass and Employee subclass - both abstract

I've read through a series of posts on here and I see a lot of people were recommending things like power mock and mockito for making mock objects.  I'm probably trying to learn too much at once as it is but basically I landed on concrete "wrapper" private classes in the unit test class that i used to polymorphically create the Employee objects (technically EmployeeWrapper objects), then unit testing all the public methods through the wrapper class.

I'm vaugely familiar with the term "bad code smell" and this really stinks. Is there a standard way of testing abstract superclasses without using things like Mockito and Power Mock? Or do i just need to suck it up and use things like that?

This is the code for the classes (with all method bodies removed so you dont have to read through a load of unimportant details

```<code>    import java.time.LocalDateTime;
    import java.util.Hashtable;
    import java.util.Iterator;

    public abstract class Employee extends Person {

        private double hourlyRate;
        private double hoursPerWeek;
        private LocalDateTime dateOfEmploymentStart;
        private LocalDateTime dateOfEmploymentEnd;
        private Hashtable<LocalDateTime, Integer> shifts;

        private static final double MINIMUM_WAGE = 8.0;

        /**
         * Constructor for Employee for all fields except dateOfHire, which is set to {@code LocalDateTime.now()}
         *
         * @param name
         * @param email
         * @param phoneNumber
         * @param hourlyRate
         * @param weeklyHours
         * @throws IllegalArgumentException if name if blank or null
         */
        public Employee(String name, String email, String phoneNumber, double hourlyRate, double weeklyHours) throws IllegalArgumentException {
            super(name, email, phoneNumber);
            this.setHourlyRate(hourlyRate);
            this.setWeeklyHours(weeklyHours);
            this.setDateOfEmploymentStart(LocalDateTime.now());
            this.shifts = new Hashtable<LocalDateTime, Integer>();
        }

        /**
         * Constructor for Employee that sets name, email and phoneNumber to provided args; and sets hourly rate and weeklyHours to 0
         *
         * @param name
         * @param email
         * @param phoneNumber
         * @throws IllegalArgumentException if name is blank or null
         */
        public Employee(String name, String email, String phoneNumber) throws IllegalArgumentException {
            this(name, email, phoneNumber, MINIMUM_WAGE, 0);
        }

        /**
         * Constructor for Employee that sets only name
         *
         * @param name
         * @throws IllegalArgumentException
         */
        public Employee(String name) throws IllegalArgumentException {
            this(name, null, null);
        }
    }
</code>```

and the Unit test class (with all test cases bar one removed, and that one method body is left empty - again to stop clutter:

```<code>    import static org.junit.jupiter.api.Assertions.*;

    import java.time.LocalDateTime;
    import java.util.Hashtable;
    import java.util.Set;

    import org.junit.jupiter.api.BeforeEach;
    import org.junit.jupiter.api.Test;

    class EmployeeTest {

        private class EmployeeWrapper extends Employee {

            public EmployeeWrapper(String name, String email, String phoneNumber, double hourlyRate, double weeklyHours) throws IllegalArgumentException {
                super(name, email, phoneNumber, hourlyRate, weeklyHours);
            }

            public EmployeeWrapper(String name, String email, String phoneNumber) throws IllegalArgumentException {
                super(name, email, phoneNumber);
            }

            public EmployeeWrapper(String name) throws IllegalArgumentException {
                super(name);
            }
        }

        private String nameValid, emailValid, phoneNumberValid;
        private String nameInvalid, emailInvalid, phoneNumberInvalid;
        private double hourlyRateValid, hourlyRateInvalidLow;
        private double weeklyHoursValid, weeklyHoursInvalid;

        private final double DEFAULT_HOURLY_RATE = 8;
        private final double DEFAULT_WEEKLY_HOURS = 0;
        private final String DEFAULT_EMAIL = "no email provided";
        private final String DEFAULT_PHONE_NUMBER = "no phone number provided";
        private final double MINIMUM_WAGE = 8.0;

        private Employee employee;

        private Hashtable<LocalDateTime, Integer> shiftsValid, shiftsInvalidEmpty;

        private LocalDateTime dateTimeValid, dateTimePast, dateTimeFuture;

        @BeforeEach
        void setUp() throws Exception {

            // valid employee
            nameValid = "testname";
            phoneNumberValid = "123456789";
            emailValid = "test@test.test.com";
            hourlyRateValid = 10.50;
            weeklyHoursValid = 7.5;

            employee = new EmployeeWrapper(nameValid, emailValid, phoneNumberValid, hourlyRateValid, weeklyHoursValid);

            // test data
            nameInvalid = "";
            emailInvalid = ".test@test.com";
            phoneNumberInvalid = "";
            hourlyRateInvalidLow = 5;
            weeklyHoursInvalid = -10;

            dateTimeValid = LocalDateTime.of(2015, 6, 15, 13, 30);
            dateTimePast = LocalDateTime.MIN;
            dateTimeFuture = LocalDateTime.MAX;

            shiftsValid = new Hashtable<LocalDateTime, Integer>();
            shiftsValid.put(dateTimeValid, 6);
            shiftsValid.put(dateTimeFuture, 3);

            shiftsInvalidEmpty = new Hashtable<LocalDateTime, Integer>();

        }

        @Test
        void testEmployeeConstructorValidAllArgs() {
        }

    }

</code>```

This is my first post of Stack Overflow so i apologise profusely if i have omitted any revelent details.

If you see any other stupid things i've done in the code I'll also gladly take any criticism!

edit: thanks everyone for the responses they have been amazing, i really really appreciate it!

答:
First let me say, that your approach is absolutely viable. I am just sharing my own way of doing it, because it spares copy pasting tests common between different implementations.

I don't specifically test abstract classes. Because we are testing functionality and it can be overridden in subclasses. I'll use your Person class for this setup, but i will simplify it a bit.

```<code>public abstract class Person {

    private String name;
    private String email;

    public Person(String name, String email) {
        this.setName(name);
        this.email = email;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        if (name == null || name.isEmpty()) {
            throw new IllegalArgumentException("missing name");
        }
        this.name = name;
    }

    public String getEmail() {
        return this.email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}
</code>```

Student

```<code>public class Student extends Person {

    private String university;

    public Student(String name, String email, String university) {
        super(name, email);
        this.university = university;
    }

    public String getUniversity() {
        return this.university;
    }

    public void setUniversity(String university) {
        this.university = university;
    }
}
</code>```

Child

```<code>public class Child extends Person {

    private String school;

    public Child(String name, String email, String school) {
        super(name, email);
        this.school = school;
    }

    public String getSchool() {
        return this.school;
    }

    public void setSchool(String school) {
        this.school = school;
    }

    @Override
    public String getName() {
        return "I am not saying!";
    }
}
</code>```

So we have the abstract Person, a Student, whose specific thing is a university and a Child. Having a school is what is specific for the child, but it also changes the behaviour of getName(), it does not disclose its name. This might be desired, but for this example we'll assume it was incorrect to override getName() like this.

When dealing with abstract classes i make an abstract test class, which holds common setup and tests for common functionality provided by the abstract class - Person in this case.

```<code>public abstract class PersonBaseTests {

    protected static final String EXPECTED_NAME = "George";

    private Person person;

    @BeforeEach
    public void setUp() {
        this.person = getConcretePersonImplementation();
    }

    /**
     * @return new instance of non-abstract class extending person
     */
    protected abstract Person getConcretePersonImplementation();

    //common tests
    @Test
    public void testGetName_ShouldReturnCorrectValue() {
        assertEquals(EXPECTED_NAME, this.person.getName());
    }

    @Test
    public void testConstructor_ShouldThrowIllegalArgumentExceptionOnMissingName() {
        Executable invalidConstructorInvocation = getConstructorExecutableWithMissingName();
        IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, invalidConstructorInvocation);
        assertEquals("missing name", exception.getMessage());
    }

    protected abstract Executable getConstructorExecutableWithMissingName();

    //other common tests
}
</code>```

The test classes extending the base must provide the concrete implementation to be tested. They will also inherit the tests, so you don't need to write them again. If you still have not learned about interfaces, lambdas and stuff like that, you can ignore the constructor exception test and everything related to it, and focus on getName() test. It tests that the getter correctly returns the name of the Person. This will obviously fail for Child, but that's the idea. You can add tests for getting and setting email, phone, etc.

So, student tests

```<code>public class StudentTests extends PersonBaseTests {

    @Override
    protected Person getConcretePersonImplementation() {
        return new Student(PersonBaseTests.EXPECTED_NAME, "mail", "Cambridge");
    }

    @Override
    protected Executable getConstructorExecutableWithMissingName() {
        //setup invocation which will actually fail
        return new StudentConstructorExecutable(null, "email@email.email", "Stanford");
    }

    private static final class StudentConstructorExecutable implements Executable {

        private final String name;
        private final String email;
        private final String university;

        private StudentConstructorExecutable(String name, String email, String university) {
            this.name = name;
            this.email = email;
            this.university = university;
        }

        @Override
        public void execute() throws Throwable {
            //this will invoke the constructor with values from fields
            new Student(this.name, this.email, this.university);
        }
    }

    //write tests specific for student class
    //getUniversity() tests for example
}
</code>```

Again, ignore the Executable and everything related to the constructor test, if you have not learned it yet. Student tests provide concreete instance of Student for the common inherited tests, and you can write additional tests for specific functionality - get/set university.

Child tests

```<code>public class ChildTests extends PersonBaseTests {

    @Override
    protected Person getConcretePersonImplementation() {
        return new Child(PersonBaseTests.EXPECTED_NAME, "", "some school");
    }

    @Override
    protected Executable getConstructorExecutableWithMissingName() {
        //this can be ignored
        return () -> new Child(null, "", "");
    }

    //write tests specific for child class
    //getSchool() tests for example
}
</code>```

Again, a concrete instance is provided for the common tests - this time of type Child. And you can add tests for any additional functionality provided by Child class - get and set school in this example. Then you can write more test classes for every additional subclass of Person.

Like this you keep common tests at one place and every concrete implementation of abstract class you write is completely tested, without test duplication. About the failing test, if the change in behaviour of getName() is intentional, you can just override it in ChildTests to take that into account. If it is not intentional, you know, that Student.getName() is correct, while Child.getName() is not, but you wrote the test only once.

Body:
I'm a student studying software development (1st year) and the teaching language we are using is Java. We have covered basics, and most of OOP, but I've been practicing making a Shop Administration System and I've come up against something I can't reckon with.

I'm trying to unit test two classes which are both abstract superclasses of several other classes I plan on implementing, as per the UML below

Person Superclass and Employee subclass - both abstract

I've read through a series of posts on here and I see a lot of people were recommending things like power mock and mockito for making mock objects.  I'm probably trying to learn too much at once as it is but basically I landed on concrete "wrapper" private classes in the unit test class that i used to polymorphically create the Employee objects (technically EmployeeWrapper objects), then unit testing all the public methods through the wrapper class.

I'm vaugely familiar with the term "bad code smell" and this really stinks. Is there a standard way of testing abstract superclasses without using things like Mockito and Power Mock? Or do i just need to suck it up and use things like that?

This is the code for the classes (with all method bodies removed so you dont have to read through a load of unimportant details

    import java.time.LocalDateTime;
    import java.util.Hashtable;
    import java.util.Iterator;

    public abstract class Employee extends Person {

        private double hourlyRate;
        private double hoursPerWeek;
        private LocalDateTime dateOfEmploymentStart;
        private LocalDateTime dateOfEmploymentEnd;
        private Hashtable<LocalDateTime, Integer> shifts;

        private static final double MINIMUM_WAGE = 8.0;

        /**
         * Constructor for Employee for all fields except dateOfHire, which is set to {@code LocalDateTime.now()}
         *
         * @param name
         * @param email
         * @param phoneNumber
         * @param hourlyRate
         * @param weeklyHours
         * @throws IllegalArgumentException if name if blank or null
         */
        public Employee(String name, String email, String phoneNumber, double hourlyRate, double weeklyHours) throws IllegalArgumentException {
            super(name, email, phoneNumber);
            this.setHourlyRate(hourlyRate);
            this.setWeeklyHours(weeklyHours);
            this.setDateOfEmploymentStart(LocalDateTime.now());
            this.shifts = new Hashtable<LocalDateTime, Integer>();
        }

        /**
         * Constructor for Employee that sets name, email and phoneNumber to provided args; and sets hourly rate and weeklyHours to 0
         *
         * @param name
         * @param email
         * @param phoneNumber
         * @throws IllegalArgumentException if name is blank or null
         */
        public Employee(String name, String email, String phoneNumber) throws IllegalArgumentException {
            this(name, email, phoneNumber, MINIMUM_WAGE, 0);
        }

        /**
         * Constructor for Employee that sets only name
         *
         * @param name
         * @throws IllegalArgumentException
         */
        public Employee(String name) throws IllegalArgumentException {
            this(name, null, null);
        }
    }

and the Unit test class (with all test cases bar one removed, and that one method body is left empty - again to stop clutter:

    import static org.junit.jupiter.api.Assertions.*;

    import java.time.LocalDateTime;
    import java.util.Hashtable;
    import java.util.Set;

    import org.junit.jupiter.api.BeforeEach;
    import org.junit.jupiter.api.Test;

    class EmployeeTest {

        private class EmployeeWrapper extends Employee {

            public EmployeeWrapper(String name, String email, String phoneNumber, double hourlyRate, double weeklyHours) throws IllegalArgumentException {
                super(name, email, phoneNumber, hourlyRate, weeklyHours);
            }

            public EmployeeWrapper(String name, String email, String phoneNumber) throws IllegalArgumentException {
                super(name, email, phoneNumber);
            }

            public EmployeeWrapper(String name) throws IllegalArgumentException {
                super(name);
            }
        }

        private String nameValid, emailValid, phoneNumberValid;
        private String nameInvalid, emailInvalid, phoneNumberInvalid;
        private double hourlyRateValid, hourlyRateInvalidLow;
        private double weeklyHoursValid, weeklyHoursInvalid;

        private final double DEFAULT_HOURLY_RATE = 8;
        private final double DEFAULT_WEEKLY_HOURS = 0;
        private final String DEFAULT_EMAIL = "no email provided";
        private final String DEFAULT_PHONE_NUMBER = "no phone number provided";
        private final double MINIMUM_WAGE = 8.0;

        private Employee employee;

        private Hashtable<LocalDateTime, Integer> shiftsValid, shiftsInvalidEmpty;

        private LocalDateTime dateTimeValid, dateTimePast, dateTimeFuture;

        @BeforeEach
        void setUp() throws Exception {

            // valid employee
            nameValid = "testname";
            phoneNumberValid = "123456789";
            emailValid = "test@test.test.com";
            hourlyRateValid = 10.50;
            weeklyHoursValid = 7.5;

            employee = new EmployeeWrapper(nameValid, emailValid, phoneNumberValid, hourlyRateValid, weeklyHoursValid);

            // test data
            nameInvalid = "";
            emailInvalid = ".test@test.com";
            phoneNumberInvalid = "";
            hourlyRateInvalidLow = 5;
            weeklyHoursInvalid = -10;

            dateTimeValid = LocalDateTime.of(2015, 6, 15, 13, 30);
            dateTimePast = LocalDateTime.MIN;
            dateTimeFuture = LocalDateTime.MAX;

            shiftsValid = new Hashtable<LocalDateTime, Integer>();
            shiftsValid.put(dateTimeValid, 6);
            shiftsValid.put(dateTimeFuture, 3);

            shiftsInvalidEmpty = new Hashtable<LocalDateTime, Integer>();

        }

        @Test
        void testEmployeeConstructorValidAllArgs() {
        }

    }

This is my first post of Stack Overflow so i apologise profusely if i have omitted any revelent details.

If you see any other stupid things i've done in the code I'll also gladly take any criticism!

edit: thanks everyone for the responses they have been amazing, i really really appreciate it!

Body:
First let me say, that your approach is absolutely viable. I am just sharing my own way of doing it, because it spares copy pasting tests common between different implementations.

I don't specifically test abstract classes. Because we are testing functionality and it can be overridden in subclasses. I'll use your Person class for this setup, but i will simplify it a bit.

public abstract class Person {

    private String name;
    private String email;

    public Person(String name, String email) {
        this.setName(name);
        this.email = email;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        if (name == null || name.isEmpty()) {
            throw new IllegalArgumentException("missing name");
        }
        this.name = name;
    }

    public String getEmail() {
        return this.email;
    }

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

Student

public class Student extends Person {

    private String university;

    public Student(String name, String email, String university) {
        super(name, email);
        this.university = university;
    }

    public String getUniversity() {
        return this.university;
    }

    public void setUniversity(String university) {
        this.university = university;
    }
}

Child

public class Child extends Person {

    private String school;

    public Child(String name, String email, String school) {
        super(name, email);
        this.school = school;
    }

    public String getSchool() {
        return this.school;
    }

    public void setSchool(String school) {
        this.school = school;
    }

    @Override
    public String getName() {
        return "I am not saying!";
    }
}

So we have the abstract Person, a Student, whose specific thing is a university and a Child. Having a school is what is specific for the child, but it also changes the behaviour of getName(), it does not disclose its name. This might be desired, but for this example we'll assume it was incorrect to override getName() like this.

When dealing with abstract classes i make an abstract test class, which holds common setup and tests for common functionality provided by the abstract class - Person in this case.

public abstract class PersonBaseTests {

    protected static final String EXPECTED_NAME = "George";

    private Person person;

    @BeforeEach
    public void setUp() {
        this.person = getConcretePersonImplementation();
    }

    /**
     * @return new instance of non-abstract class extending person
     */
    protected abstract Person getConcretePersonImplementation();

    //common tests
    @Test
    public void testGetName_ShouldReturnCorrectValue() {
        assertEquals(EXPECTED_NAME, this.person.getName());
    }

    @Test
    public void testConstructor_ShouldThrowIllegalArgumentExceptionOnMissingName() {
        Executable invalidConstructorInvocation = getConstructorExecutableWithMissingName();
        IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, invalidConstructorInvocation);
        assertEquals("missing name", exception.getMessage());
    }

    protected abstract Executable getConstructorExecutableWithMissingName();

    //other common tests
}

The test classes extending the base must provide the concrete implementation to be tested. They will also inherit the tests, so you don't need to write them again. If you still have not learned about interfaces, lambdas and stuff like that, you can ignore the constructor exception test and everything related to it, and focus on getName() test. It tests that the getter correctly returns the name of the Person. This will obviously fail for Child, but that's the idea. You can add tests for getting and setting email, phone, etc.

So, student tests

public class StudentTests extends PersonBaseTests {

    @Override
    protected Person getConcretePersonImplementation() {
        return new Student(PersonBaseTests.EXPECTED_NAME, "mail", "Cambridge");
    }

    @Override
    protected Executable getConstructorExecutableWithMissingName() {
        //setup invocation which will actually fail
        return new StudentConstructorExecutable(null, "email@email.email", "Stanford");
    }

    private static final class StudentConstructorExecutable implements Executable {

        private final String name;
        private final String email;
        private final String university;

        private StudentConstructorExecutable(String name, String email, String university) {
            this.name = name;
            this.email = email;
            this.university = university;
        }

        @Override
        public void execute() throws Throwable {
            //this will invoke the constructor with values from fields
            new Student(this.name, this.email, this.university);
        }
    }

    //write tests specific for student class
    //getUniversity() tests for example
}

Again, ignore the Executable and everything related to the constructor test, if you have not learned it yet. Student tests provide concreete instance of Student for the common inherited tests, and you can write additional tests for specific functionality - get/set university.

Child tests

public class ChildTests extends PersonBaseTests {

    @Override
    protected Person getConcretePersonImplementation() {
        return new Child(PersonBaseTests.EXPECTED_NAME, "", "some school");
    }

    @Override
    protected Executable getConstructorExecutableWithMissingName() {
        //this can be ignored
        return () -> new Child(null, "", "");
    }

    //write tests specific for child class
    //getSchool() tests for example
}

Again, a concrete instance is provided for the common tests - this time of type Child. And you can add tests for any additional functionality provided by Child class - get and set school in this example. Then you can write more test classes for every additional subclass of Person.

Like this you keep common tests at one place and every concrete implementation of abstract class you write is completely tested, without test duplication. About the failing test, if the change in behaviour of getName() is intentional, you can just override it in ChildTests to take that into account. If it is not intentional, you know, that Student.getName() is correct, while Child.getName() is not, but you wrote the test only once.


来源: stackexchange

问:
Using the %%var%% with batch file
```<code>CALL SET %PROJECT%_VERSION=1_7_0
echo %%PROJECT%_VERSION%
</code>```

The result will be %PROJECT.

How can I let it to 1_7_0

答:
Using delayedexpansion makes life easier for these types of scenarios.. You do not need to get the number of % 100% either side of the variables and no need to use call:

```<code>@echo off
setlocal enabledelayedexpansion
set "PROJECT=Projectname"
SET "%PROJECT%_VERSION=1_7_0"
echo !%PROJECT%_VERSION!
</code>```

ContentLicense: CC BY-SA 4.0

Title: Using the %%var%% with batch file

Body:
CALL SET %PROJECT%_VERSION=1_7_0
echo %%PROJECT%_VERSION%

The result will be %PROJECT.

How can I let it to 1_7_0

Body:
Using delayedexpansion makes life easier for these types of scenarios.. You do not need to get the number of % 100% either side of the variables and no need to use call:

@echo off
setlocal enabledelayedexpansion
set "PROJECT=Projectname"
SET "%PROJECT%_VERSION=1_7_0"
echo !%PROJECT%_VERSION!


问:
How to change element attribute on toggle with Javascript?
I would like to add attribute "aria-label=test1" when it is fa-chevron-left and "aria-label=test2" on fa-chevron-right.

"aria-label=test1" should be there on load (default). Could anyone show me how to code it for here?

```<code>function s(e) {
  const t = n(),
    c = document.querySelector(".nav-container"),
    o = document.querySelector(".content-container"),
    s = document.querySelector(".slide-btn i.fas");
  switch (e) {
    case "toggle":
      c.classList.toggle("slided"),
        s.classList.toggle("fa-chevron-right"),
        s.classList.toggle("fa-chevron-left"),
        t && o.classList.toggle("slided");
      break;
    case "show":
      c.classList.remove("slided"),
        s.classList.remove("fa-chevron-right"),
        s.classList.add("fa-chevron-left"),
        t && o.classList.add("slided");
      break;
    case "hide":
      if (c.classList.add("slided"), s.classList.add("fa-chevron-right"), s.classList.remove("fa-chevron-left"), t) {
        o.classList.remove("slided");
        const e = document.querySelector(".body-container").getAttribute("activeTopic");
        document.getElementById(e).scrollIntoView()
      }
  }
}
</code>```

答:
You could do :

element.setAttribute("aria-label", element.classList.contains("fa-chevron-left") ? "test1" : "test2");
```

Body:
I would like to add attribute "aria-label=test1" when it is fa-chevron-left and "aria-label=test2" on fa-chevron-right.

"aria-label=test1" should be there on load (default). Could anyone show me how to code it for here?

function s(e) {
  const t = n(),
    c = document.querySelector(".nav-container"),
    o = document.querySelector(".content-container"),
    s = document.querySelector(".slide-btn i.fas");
  switch (e) {
    case "toggle":
      c.classList.toggle("slided"),
        s.classList.toggle("fa-chevron-right"),
        s.classList.toggle("fa-chevron-left"),
        t && o.classList.toggle("slided");
      break;
    case "show":
      c.classList.remove("slided"),
        s.classList.remove("fa-chevron-right"),
        s.classList.add("fa-chevron-left"),
        t && o.classList.add("slided");
      break;
    case "hide":
      if (c.classList.add("slided"), s.classList.add("fa-chevron-right"), s.classList.remove("fa-chevron-left"), t) {
        o.classList.remove("slided");
        const e = document.querySelector(".body-container").getAttribute("activeTopic");
        document.getElementById(e).scrollIntoView()
      }
  }
}


问:
Accessing a Custom Configuration Section in .Net
I am trying to access settings in my config file, which is a series of xml elements listed as such:

```<code><databases>
<database name="DatabaseOne" Value="[value]" />
<database name="DatabaseTwo" Value="[value]" />
</databases>
</code>```

Now I want to access it. I have set up classes like so:

```<code>Public Class DatabaseConfigurationHandler
    Inherits ConfigurationSection

    <ConfigurationProperty("Databases", IsDefaultCollection:=True)> _
   Public ReadOnly Property Databases() As DatabaseCollection
        Get
            Return CType(Me("Databases"), DatabaseCollection)
        End Get
    End Property
End Class

Public Class DatabaseCollection
    Inherits ConfigurationElementCollection

    Protected Overloads Overrides Function CreateNewElement() As ConfigurationElement
        Return (New Database())
    End Function

    Protected Overloads Overrides Function GetElementKey(ByVal element As ConfigurationElement) As Object
        Return (CType(element, Database).DatabaseName)
    End Function

End Class

Public Class Database
    Inherits ConfigurationElement

    <ConfigurationProperty("name", IsKey:=True, IsRequired:=True)> _
       Public Property DatabaseName() As String
        Get
            Return Me("name").ToString()
        End Get
        Set(ByVal Value As String)
            Me("name") = Value
        End Set
    End Property

    <ConfigurationProperty("value", IsRequired:=True)> _
Public Property DatabaseValue() As String
        Get
            Return Me("value").ToString()
        End Get
        Set(ByVal Value As String)
            Me("value") = Value
        End Set
    End Property

End Class
</code>```

I want to be able get the element by it's name and return the value but I can't see to do that:

```<code>Dim config As New DatabaseConfigurationHandler
                config = System.Configuration.ConfigurationManager.GetSection("databases/database")
                Return config.Databases("DatabaseOne")
</code>```

Am I missing some code, what am I doing wrong? Any other errors in the above?

Thanks.

答:
My VB isn't up to much sorry but here's how you do it in C#.

C#

```<code>public class AppState : IConfigurationSectionHandler
{
    static AppState()
    {
        xmlNode myConfigNode = (XmlNode)ConfigurationManager.GetSection("databases");
    }

    public object Create(object parent, object context, XmlNode configSection) {
        return configSection;
    }
}
</code>```

App.Config

```<code><configuration>
  <configSections>
    <section name="databases" type="MyAssembly.AppState, MyAssembly" />
  </configSections>
  <databases>
    <database name="DatabaseOne" Value="[value]" />
    <database name="DatabaseTwo" Value="[value]" />
  </databases>
</configuration>
</code>```

OwnerDisplayName: Damien

ContentLicense: CC BY-SA 2.5

Body:
I am trying to access settings in my config file, which is a series of xml elements listed as such:

<databases>
<database name="DatabaseOne" Value="[value]" />
<database name="DatabaseTwo" Value="[value]" />
</databases>

Now I want to access it. I have set up classes like so:

Public Class DatabaseConfigurationHandler
    Inherits ConfigurationSection

    <ConfigurationProperty("Databases", IsDefaultCollection:=True)> _
   Public ReadOnly Property Databases() As DatabaseCollection
        Get
            Return CType(Me("Databases"), DatabaseCollection)
        End Get
    End Property
End Class

Public Class DatabaseCollection
    Inherits ConfigurationElementCollection

    Protected Overloads Overrides Function CreateNewElement() As ConfigurationElement
        Return (New Database())
    End Function

    Protected Overloads Overrides Function GetElementKey(ByVal element As ConfigurationElement) As Object
        Return (CType(element, Database).DatabaseName)
    End Function

End Class

Public Class Database
    Inherits ConfigurationElement

    <ConfigurationProperty("name", IsKey:=True, IsRequired:=True)> _
       Public Property DatabaseName() As String
        Get
            Return Me("name").ToString()
        End Get
        Set(ByVal Value As String)
            Me("name") = Value
        End Set
    End Property

    <ConfigurationProperty("value", IsRequired:=True)> _
Public Property DatabaseValue() As String
        Get
            Return Me("value").ToString()
        End Get
        Set(ByVal Value As String)
            Me("value") = Value
        End Set
    End Property

End Class

I want to be able get the element by it's name and return the value but I can't see to do that:

Dim config As New DatabaseConfigurationHandler
                config = System.Configuration.ConfigurationManager.GetSection("databases/database")
                Return config.Databases("DatabaseOne")

Am I missing some code, what am I doing wrong? Any other errors in the above?

Thanks.

Body:
My VB isn't up to much sorry but here's how you do it in C#.

C#

public class AppState : IConfigurationSectionHandler
{
    static AppState()
    {
        xmlNode myConfigNode = (XmlNode)ConfigurationManager.GetSection("databases");
    }

    public object Create(object parent, object context, XmlNode configSection) {
        return configSection;
    }
}

App.Config

<configuration>
  <configSections>
    <section name="databases" type="MyAssembly.AppState, MyAssembly" />
  </configSections>
  <databases>
    <database name="DatabaseOne" Value="[value]" />
    <database name="DatabaseTwo" Value="[value]" />
  </databases>
</configuration>

OwnerDisplayName: sipwiz


问:
eBay Feed API -> uploadFile script working on local PC but not working on live server
Here is my script which uploads feed to ebay. The script working on local PC but when I upload to my live server, it does not work.

Here is my code.

```<code>public function createTask($feedType='FX_LISTING')
    {
        $link = "https://api.ebay.com/sell/feed/v1/task";
        //$appConfig = parse_ini_file("config.ini");

        //payload
        $payload = json_encode(array("schemaVersion"=>"1.0","feedType"=>"FX_LISTING"));

        //$appConfig['user_token'] = 'mehboob';
        $ch = curl_init($link);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Authorization:Bearer ' . $this->userToken,
            'Accept:application/json',
            'Content-Type:application/json',
            'X-EBAY-C-MARKETPLACE-ID: EBAY_US'
        ));
        curl_setopt($ch, CURLHEADER_SEPARATE, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        //scurl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:8888');
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
        $response = curl_exec($ch);
        $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $headers = substr($response, 0, $header_size);
        $body = substr($response, $header_size);
        $info = curl_getinfo($ch);

        echo($body);
        curl_close($ch);

        $headers = explode("\r\n", $headers); // The seperator used in the Response Header is CRLF (Aka. \r\n)

        $headers = array_filter($headers);

        $loc = basename(implode(preg_grep("/^location.*/", $headers)));
      return $loc;

    }

    public function uploadFile($taskID, $fName)
    {
          $link = "https://api.ebay.com/sell/feed/v1/task/$taskID/upload_file";
         $curl = curl_init();
        curl_setopt($curl, CURLINFO_HEADER_OUT, true);
        // curl_setopt($curl, CURLOPT_PROXY, '127.0.0.1:8888');
        curl_setopt_array($curl, array(
        CURLOPT_URL => $link,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_SSL_VERIFYHOST=> 1,
        CURLOPT_SSL_VERIFYPEER=> 1,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_HEADER => 1,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS => array('file'=> new CURLFILE(realpath($fName)),'type' => 'form-data'),
        CURLOPT_HTTPHEADER => array(
        'Authorization: Bearer ' . $this->userToken,
        'Content-Type: multipart/form-data',
        'X-EBAY-C-MARKETPLACE-ID: EBAY_US'
        ),

        ));

        $response = curl_exec($curl);
        var_dump($response);

        curl_close($curl);

    }
</code>```

Using the code as under:

```<code>$feedPath = __DIR__ . "/" ."feed.csv";
$taskID= createTask();
$uF = uploadFile($taskID,$feedPath);
</code>```

The above code works fine on my local PC, creating task id and uploading file to ebay. But when I am uploading code on my server, it gets failed.
I confirmed the path to the file on my server is OK.
Also I am using the same version of PHP on my server.

Please see the following response I receives from Server.

```<code>string(595) "HTTP/1.1 100 Continue HTTP/1.1 500 Internal Server Error rlogid: t6pitaf%60btuf1%3D9vjdpitaf%60btuf1*or3ah%28rbpv6775-1795f5551e5-0x2340 x-ebay-client-tls-version: TLSv1.2 content-type: application/json content-length: 228 date: Wed, 12 May 2021 06:48:18 GMT x-envoy-upstream-service-time: 125 server: ebay-proxy-server x-ebay-pop-id: UFES2-LVSAZ01-api {"errors":[{"errorId":160001,"domain":"API_FEED","subdomain":"Selling","category":"APPLICATION","message":"There was a problem with an eBay internal system or process. Contact eBay Developer Technical Support for assistance."}]}"
</code>```

The error says about "eBay internal error" but I don't think so. its due to some problem in the code.

The documentation to the above eBay service is as under:
eBay Feed File - uploadFile documentation

Your cooperation in this context will be highly appreciated.

答:
```<code>    This code is in C# - RestClient

    createTask
    ==========
    var client = new RestClient("https://api.ebay.com/sell/feed/v1/task");
    client.Timeout = -1;
    var request = new RestRequest(Method.POST);
    request.AddHeader("Authorization", "Bearer v^1.1#i^1****** YOUR USER ACCESS TOKEN *********Ql3QYER3BQAAA==");
    request.AddHeader("Accept", "application/json");
    request.AddHeader("Content-Type", "application/json");
    request.AddHeader("X-EBAY-C-MARKETPLACE-ID", "EBAY_GB");
    var body = @"{
    " + "\n" +
    @"  ""schemaVersion"": ""1149"",
    " + "\n" +
    @"  ""feedType"": ""LMS_REVISE_INVENTORY_STATUS""
    " + "\n" +
    @"}";
    request.AddParameter("application/json", body,  ParameterType.RequestBody);
    IRestResponse response = client.Execute(request);
    Console.WriteLine(response.Content);

    Response:
    location:https://api.ebay.com/sell/feed/v1/task/task-12-1127376027
</code>```

task-12-1127376027 is your TaskID

```<code>    uploadFile
    ==========
test.xml file
--------------

<?xml version="1.0" encoding="utf-8"?>
<ReviseInventoryStatusRequest xmlns="urn:ebay:apis:eBLBaseComponents">
  <RequesterCredentials>
    <eBayAuthToken></eBayAuthToken>
  </RequesterCredentials>
    <ErrorLanguage>en_US</ErrorLanguage>
    <WarningLevel>High</WarningLevel>
  <InventoryStatus>
    <SKU>test-1111</SKU>
    <Quantity>10</Quantity>
  </InventoryStatus>
  <InventoryStatus>
    <SKU>test-2222</SKU>
    <Quantity>20</Quantity>
  </InventoryStatus>
</ReviseInventoryStatusRequest>

upload code
-----------
    var client = new RestClient("https://api.ebay.com/sell/feed/v1/task/task-12-1127376027/upload_file");
    client.Timeout = -1;
    var request = new RestRequest(Method.POST);
    request.AddHeader("Authorization", "Bearer v^1.1#i^1****** YOUR USER ACCESS TOKEN *********Ql3QYER3BQAAA==");
    request.AddHeader("X-EBAY-C-MARKETPLACE-ID", "EBAY_GB");
    request.AddHeader("Accept", "application/json");
    request.AddHeader("Content-Type", "multipart/form-data");
    request.AddParameter("fileName", "test.xml");
    request.AddFile("file", "F:/test.xml");
    request.AddParameter("type", "form-data");
    IRestResponse response = client.Execute(request);
    Console.WriteLine(response.Content);

    Response: "StatusCode: OK, Content-Type: , Content-Length: 0)"

    getTask
    ========
    var client = new RestClient("https://api.ebay.com/sell/feed/v1/task/task-12-1235290549");
    client.Timeout = -1;
    var request = new RestRequest(Method.GET);
    request.AddHeader("Authorization", "Bearer v^1.1#i^1****** YOUR USER ACCESS TOKEN *********Ql3QYER3BQAAA==");
    request.AddHeader("Accept", "application/json");
    request.AddHeader("Content-Type", "application/json");
    IRestResponse response = client.Execute(request);
    Console.WriteLine(response.Content);

    Response:
    {
        "taskId": "task-12-1127376027",
        "status": "FAILED",
        "feedType": "LMS_REVISE_INVENTORY_STATUS",
        "creationDate": "2022-02-09T11:39:50.000Z",
        "completionDate": "2022-02-09T11:50:34.000Z",
        "uploadSummary": {
            "successCount": 0,
            "failureCount": 0
        }
    }
</code>```

Body:
Here is my script which uploads feed to ebay. The script working on local PC but when I upload to my live server, it does not work.

Here is my code.

public function createTask($feedType='FX_LISTING')
    {
        $link = "https://api.ebay.com/sell/feed/v1/task";
        //$appConfig = parse_ini_file("config.ini");

        //payload
        $payload = json_encode(array("schemaVersion"=>"1.0","feedType"=>"FX_LISTING"));

        //$appConfig['user_token'] = 'mehboob';
        $ch = curl_init($link);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Authorization:Bearer ' . $this->userToken,
            'Accept:application/json',
            'Content-Type:application/json',
            'X-EBAY-C-MARKETPLACE-ID: EBAY_US'
        ));
        curl_setopt($ch, CURLHEADER_SEPARATE, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        //scurl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:8888');
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
        $response = curl_exec($ch);
        $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $headers = substr($response, 0, $header_size);
        $body = substr($response, $header_size);
        $info = curl_getinfo($ch);

        echo($body);
        curl_close($ch);

        $headers = explode("\r\n", $headers); // The seperator used in the Response Header is CRLF (Aka. \r\n)

        $headers = array_filter($headers);

        $loc = basename(implode(preg_grep("/^location.*/", $headers)));
      return $loc;

    }

    public function uploadFile($taskID, $fName)
    {
          $link = "https://api.ebay.com/sell/feed/v1/task/$taskID/upload_file";
         $curl = curl_init();
        curl_setopt($curl, CURLINFO_HEADER_OUT, true);
        // curl_setopt($curl, CURLOPT_PROXY, '127.0.0.1:8888');
        curl_setopt_array($curl, array(
        CURLOPT_URL => $link,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_SSL_VERIFYHOST=> 1,
        CURLOPT_SSL_VERIFYPEER=> 1,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_HEADER => 1,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS => array('file'=> new CURLFILE(realpath($fName)),'type' => 'form-data'),
        CURLOPT_HTTPHEADER => array(
        'Authorization: Bearer ' . $this->userToken,
        'Content-Type: multipart/form-data',
        'X-EBAY-C-MARKETPLACE-ID: EBAY_US'
        ),

        ));

        $response = curl_exec($curl);
        var_dump($response);

        curl_close($curl);

    }

Using the code as under:

$feedPath = __DIR__ . "/" ."feed.csv";
$taskID= createTask();
$uF = uploadFile($taskID,$feedPath);

The above code works fine on my local PC, creating task id and uploading file to ebay. But when I am uploading code on my server, it gets failed.
I confirmed the path to the file on my server is OK.
Also I am using the same version of PHP on my server.

Please see the following response I receives from Server.

string(595) "HTTP/1.1 100 Continue HTTP/1.1 500 Internal Server Error rlogid: t6pitaf%60btuf1%3D9vjdpitaf%60btuf1*or3ah%28rbpv6775-1795f5551e5-0x2340 x-ebay-client-tls-version: TLSv1.2 content-type: application/json content-length: 228 date: Wed, 12 May 2021 06:48:18 GMT x-envoy-upstream-service-time: 125 server: ebay-proxy-server x-ebay-pop-id: UFES2-LVSAZ01-api {"errors":[{"errorId":160001,"domain":"API_FEED","subdomain":"Selling","category":"APPLICATION","message":"There was a problem with an eBay internal system or process. Contact eBay Developer Technical Support for assistance."}]}"

The error says about "eBay internal error" but I don't think so. its due to some problem in the code.

The documentation to the above eBay service is as under:
eBay Feed File - uploadFile documentation

Your cooperation in this context will be highly appreciated.

Body:
    This code is in C# - RestClient

    createTask
    ==========
    var client = new RestClient("https://api.ebay.com/sell/feed/v1/task");
    client.Timeout = -1;
    var request = new RestRequest(Method.POST);
    request.AddHeader("Authorization", "Bearer v^1.1#i^1****** YOUR USER ACCESS TOKEN *********Ql3QYER3BQAAA==");
    request.AddHeader("Accept", "application/json");
    request.AddHeader("Content-Type", "application/json");
    request.AddHeader("X-EBAY-C-MARKETPLACE-ID", "EBAY_GB");
    var body = @"{
    " + "\n" +
    @"  ""schemaVersion"": ""1149"",
    " + "\n" +
    @"  ""feedType"": ""LMS_REVISE_INVENTORY_STATUS""
    " + "\n" +
    @"}";
    request.AddParameter("application/json", body,  ParameterType.RequestBody);
    IRestResponse response = client.Execute(request);
    Console.WriteLine(response.Content);

    Response:
    location:https://api.ebay.com/sell/feed/v1/task/task-12-1127376027

task-12-1127376027 is your TaskID

    uploadFile
    ==========
test.xml file
--------------

<?xml version="1.0" encoding="utf-8"?>
<ReviseInventoryStatusRequest xmlns="urn:ebay:apis:eBLBaseComponents">
  <RequesterCredentials>
    <eBayAuthToken></eBayAuthToken>
  </RequesterCredentials>
    <ErrorLanguage>en_US</ErrorLanguage>
    <WarningLevel>High</WarningLevel>
  <InventoryStatus>
    <SKU>test-1111</SKU>
    <Quantity>10</Quantity>
  </InventoryStatus>
  <InventoryStatus>
    <SKU>test-2222</SKU>
    <Quantity>20</Quantity>
  </InventoryStatus>
</ReviseInventoryStatusRequest>

upload code
-----------
    var client = new RestClient("https://api.ebay.com/sell/feed/v1/task/task-12-1127376027/upload_file");
    client.Timeout = -1;
    var request = new RestRequest(Method.POST);
    request.AddHeader("Authorization", "Bearer v^1.1#i^1****** YOUR USER ACCESS TOKEN *********Ql3QYER3BQAAA==");
    request.AddHeader("X-EBAY-C-MARKETPLACE-ID", "EBAY_GB");
    request.AddHeader("Accept", "application/json");
    request.AddHeader("Content-Type", "multipart/form-data");
    request.AddParameter("fileName", "test.xml");
    request.AddFile("file", "F:/test.xml");
    request.AddParameter("type", "form-data");
    IRestResponse response = client.Execute(request);
    Console.WriteLine(response.Content);

    Response: "StatusCode: OK, Content-Type: , Content-Length: 0)"

    getTask
    ========
    var client = new RestClient("https://api.ebay.com/sell/feed/v1/task/task-12-1235290549");
    client.Timeout = -1;
    var request = new RestRequest(Method.GET);
    request.AddHeader("Authorization", "Bearer v^1.1#i^1****** YOUR USER ACCESS TOKEN *********Ql3QYER3BQAAA==");
    request.AddHeader("Accept", "application/json");
    request.AddHeader("Content-Type", "application/json");
    IRestResponse response = client.Execute(request);
    Console.WriteLine(response.Content);

    Response:
    {
        "taskId": "task-12-1127376027",
        "status": "FAILED",
        "feedType": "LMS_REVISE_INVENTORY_STATUS",
        "creationDate": "2022-02-09T11:39:50.000Z",
        "completionDate": "2022-02-09T11:50:34.000Z",
        "uploadSummary": {
            "successCount": 0,
            "failureCount": 0
        }
    }


问:
SQL Server ORDER BY date and nulls last
I am trying to order by date. I want the most recent dates coming in first. That's easy enough, but there are many records that are null and those come before any records that have a date.

I have tried a few things with no success:

```<code>ORDER BY ISNULL(Next_Contact_Date, 0)

ORDER BY ISNULL(Next_Contact_Date, 999999999)

ORDER BY coalesce(Next_Contact_Date, 99/99/9999)
</code>```

How can I order by date and have the nulls come in last? The data type is smalldatetime.

答:
I know this is a old thread, but in SQL Server nulls are always lower than non-null values. So it's only necessary to order by Desc

In your case Order by Next_Contact_Date Desc should be enough.

Source: order by with nulls- LearnSql

ContentLicense: CC BY-SA 3.0

Title: SQL Server ORDER BY date and nulls last

Body:
I am trying to order by date. I want the most recent dates coming in first. That's easy enough, but there are many records that are null and those come before any records that have a date.

I have tried a few things with no success:

ORDER BY ISNULL(Next_Contact_Date, 0)

ORDER BY ISNULL(Next_Contact_Date, 999999999)

ORDER BY coalesce(Next_Contact_Date, 99/99/9999)

How can I order by date and have the nulls come in last? The data type is smalldatetime.


问:
Longest word in file
My program needs to print longest word which contains only letters from a file.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int checkString(const char s[]) {
  unsigned char c;
  while ((c = *s) && (isalpha(c) || isblank(c)))
    ++s;
  return *s == '\0';
}
int main() {
  char file_name[]="document.txt";
  FILE *fp = fopen(file_name, "r");
  char *largest = str;
  int largest_len = 0;
  while (fgets(file_name, 1000, fp) != NULL) {
    char *temp = strtok(file_name, " ");
    while (temp != NULL) {
      if (strlen(temp) > largest_len) {
        strcpy(largest, temp);
        largest_len = strlen(largest);
      }
      temp = strtok(NULL, "\",.,1,2,4,5,6,7,8,9 ");
    }
  }
  if(checkString(largest))
  printf("%s", largest);
  fclose(fp);
  return 0;
}
</code>```

In my code, if the largest word contains only letters it will be printed. How to modify this code to check next words if the largest doesn't contain only letters?

答:
I think the order you do things should be a bit different, here is an example</p>
```<code>#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

int isCandidate(char* word);

int main(int argc, char* argv[])
{
  if (--argc == 0)
  {
    perror("not enough command line arguments, expecting a filename");
    return -1;
  }
  ++argv;
  FILE* fp = fopen(*argv, "r");
  if (fp == NULL)
  {
    perror(*argv);
    return -1;
  }
  // get size of file
  fseek(fp, 0L, SEEK_END);
  long fileLength = ftell(fp);
  if (fileLength < 1)
  {
    perror("file is empty");
    return -1;
  }

  fseek(fp, 0L, SEEK_SET); // position file pointer at the beginning again

  // allocate space for the whole file and then read it in
  // for a text file it should be OK to do so since they
  // normally are not that large.
  char* buffer = malloc(fileLength+1);
  if (fread(buffer, 1, fileLength, fp) != 0)
  {
    buffer[fileLength] = '\0'; // make sure the buffer ends with \0
  }
  else
  {
    perror("Failed reading into buffer");
    return -1;
  }
  fclose(fp); // we are done with the file

  const char filter[] = " \n\r";
  char* longestWord = malloc(fileLength+1); // max length in theory
  long unsigned int maxLength = 0;
  for (char* token = strtok(buffer, filter); token != NULL; token = strtok(NULL, filter))
  {
     if (isCandidate(token))
     {
       if (strlen(token) > maxLength)
       {
         strcpy(longestWord, token);
         maxLength = strlen(token);
       }
     }
  }
  printf("Longest word:'%s', len=%lu\n", longestWord, maxLength);

  free(longestWord);
  free(buffer);
}

int isCandidate(char* word)
{
  if (word == NULL)
  {
    perror("invalid argument to isCandidate");
    return 0;
  }
  for (char* ch = word; *ch; ++ch)
  {
    if (!isalpha(*ch)) return 0;
  }
  return 1;
}
</code>```

Title: Longest word in file

Body:
My program needs to print longest word which contains only letters from a file.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int checkString(const char s[]) {
  unsigned char c;
  while ((c = *s) && (isalpha(c) || isblank(c)))
    ++s;
  return *s == '\0';
}
int main() {
  char file_name[]="document.txt";
  FILE *fp = fopen(file_name, "r");
  char *largest = str;
  int largest_len = 0;
  while (fgets(file_name, 1000, fp) != NULL) {
    char *temp = strtok(file_name, " ");
    while (temp != NULL) {
      if (strlen(temp) > largest_len) {
        strcpy(largest, temp);
        largest_len = strlen(largest);
      }
      temp = strtok(NULL, "\",.,1,2,4,5,6,7,8,9 ");
    }
  }
  if(checkString(largest))
  printf("%s", largest);
  fclose(fp);
  return 0;
}

In my code, if the largest word contains only letters it will be printed. How to modify this code to check next words if the largest doesn't contain only letters?

Body:
I think the order you do things should be a bit different, here is an example

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

int isCandidate(char* word);

int main(int argc, char* argv[])
{
  if (--argc == 0)
  {
    perror("not enough command line arguments, expecting a filename");
    return -1;
  }
  ++argv;
  FILE* fp = fopen(*argv, "r");
  if (fp == NULL)
  {
    perror(*argv);
    return -1;
  }
  // get size of file
  fseek(fp, 0L, SEEK_END);
  long fileLength = ftell(fp);
  if (fileLength < 1)
  {
    perror("file is empty");
    return -1;
  }

  fseek(fp, 0L, SEEK_SET); // position file pointer at the beginning again

  // allocate space for the whole file and then read it in
  // for a text file it should be OK to do so since they
  // normally are not that large.
  char* buffer = malloc(fileLength+1);
  if (fread(buffer, 1, fileLength, fp) != 0)
  {
    buffer[fileLength] = '\0'; // make sure the buffer ends with \0
  }
  else
  {
    perror("Failed reading into buffer");
    return -1;
  }
  fclose(fp); // we are done with the file

  const char filter[] = " \n\r";
  char* longestWord = malloc(fileLength+1); // max length in theory
  long unsigned int maxLength = 0;
  for (char* token = strtok(buffer, filter); token != NULL; token = strtok(NULL, filter))
  {
     if (isCandidate(token))
     {
       if (strlen(token) > maxLength)
       {
         strcpy(longestWord, token);
         maxLength = strlen(token);
       }
     }
  }
  printf("Longest word:'%s', len=%lu\n", longestWord, maxLength);

  free(longestWord);
  free(buffer);
}

int isCandidate(char* word)
{
  if (word == NULL)
  {
    perror("invalid argument to isCandidate");
    return 0;
  }
  for (char* ch = word; *ch; ++ch)
  {
    if (!isalpha(*ch)) return 0;
  }
  return 1;
}


问:
Call a method that return a list of employee from Class Library to UI DataGridView project C# Entity Framework
Im new in Entity Framework and LINQ
I have two project one is my class library the other one is my UI project
I'm struggling to show a list of employee from method that return the list from my class library
This is my class:

```<code>    public static class ViewEmployeesDataManager
    {
        public static List<Employee> ViewManagerEmployees()
        {
            using (var context = new HRSystemContext())
            {
                var query = from empolyee in context.Employees
                            select new {
                                Name = empolyee.FullName,
                                JobTitle = empolyee.JobTitle,
                                Mobile = empolyee.Mobile};

                return query.ToList();
</code>```

this is how I call it in my form:

```<code>dataGridView1.DataSource=ViewEmployeesDataManager.ViewManagerEmployees();
</code>```

I got this error

```<code>error CS0029: Cannot implicitly convert type 'System.Collections.Generic.List<<anonymous type: string Name, string JobTitle, string Mobile>>' to 'System.Collections.Generic.List<DataAccessLayer.Employee>
</code>```

anyone can help please

答:
UPDATE:
I solved the error by adding Object instead of Employee in my list
and it's worked</p>
```<code>public static List<Object> ShowingEmployeeInfo()
    {
        using (var context = new HRSystemContext())
        {
            var employee = from row in context.Employees
                            where row.Username == EmployeeDataManager.currentUser
                            select new {
                                Id = row.Id,
                                Name = row.FullName,
                                Job = row.JobTitle,
                                Mobile = row.Mobile,
                                Manager = row.Manager.FullName
                            };
            return employee.ToList<Object>();

        }
    }
</code>```

Body:
Im new in Entity Framework and LINQ
I have two project one is my class library the other one is my UI project
I'm struggling to show a list of employee from method that return the list from my class library
This is my class:

    public static class ViewEmployeesDataManager
    {
        public static List<Employee> ViewManagerEmployees()
        {
            using (var context = new HRSystemContext())
            {
                var query = from empolyee in context.Employees
                            select new {
                                Name = empolyee.FullName,
                                JobTitle = empolyee.JobTitle,
                                Mobile = empolyee.Mobile};

                return query.ToList();

this is how I call it in my form:

dataGridView1.DataSource=ViewEmployeesDataManager.ViewManagerEmployees();

I got this error

error CS0029: Cannot implicitly convert type 'System.Collections.Generic.List<<anonymous type: string Name, string JobTitle, string Mobile>>' to 'System.Collections.Generic.List<DataAccessLayer.Employee>

anyone can help please

Body:
UPDATE:
I solved the error by adding Object instead of Employee in my list
and it's worked

public static List<Object> ShowingEmployeeInfo()
    {
        using (var context = new HRSystemContext())
        {
            var employee = from row in context.Employees
                            where row.Username == EmployeeDataManager.currentUser
                            select new {
                                Id = row.Id,
                                Name = row.FullName,
                                Job = row.JobTitle,
                                Mobile = row.Mobile,
                                Manager = row.Manager.FullName
                            };
            return employee.ToList<Object>();

        }
    }


问:
Open source Objective-C projects with high quality code?
I think one of the best ways to learn a new programming language is to dive into source code and see how experienced coders write.  I've found this kind of question asked here on Stack Overflow for other languages, but none targeted at Objective-C.  The closest I've found is this question about good-looking Cocoa user interfaces, but I'm thinking in terms of general code quality, such as good use of idioms and design patterns, and usable documentation.  Another good characteristic would be a code-base that is large enough to require real organizational discipline, but small enough that a beginner can fit his/her head around.

What do you think is a high-quality open source project that meets these criteria?

答: Check out PSTreeGraph, a view control for iPad applications.</p>


问:
Update the table if value is unique
I have a query in reactjs.

The thing is, I want to render a table on my screen, as per the updated data. I am using get api to call the data, but what i need to do is to render the latest data corresponding to unique id. Otherwise show all data.

答:
Let you received the props which has duplicate records like

```<code>data = [{
  id: 1,
  x: 40,
  y: 30,
  x: 20,
  e: 230
},{
  id: 2,
  x: 42,
  y: 32,
  x: 22,
  e: 232
},{
  id: 3,
  x: 41,
  y: 31,
  x: 21,
  e: 231
},
{
  id: 1,
  x: 4,
  y: 3,
  x: 2,
  e: 23
}];

</code>```

Requirement: As per this data you want to render for unique ids with latest value id=1,2 and 3.

```<code>import React from "react";
import "./style.css";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { data: this.getUniqueAndUpdatedRecords(props) }
    console.log(this.state.data);
  }

  getUniqueAndUpdatedRecords(data) {
    return data.data.filter(function ({ id }) {
      return !this.has(id) && this.add(id);
    }, new Set());
  }

  render() {
    return <table>
      <thead>
        <tr>
          <th>x</th>
          <th>y</th>
          <th>z</th>
          <th>e</th>
        </tr>
      </thead>
      <tbody>
        {(this.state.data && this.state.data.length ? (this.state.data.map(({ id, x, y, z, e }) => {
          return <tr key={id}>
            <td>{x}</td>
            <td>{y}</td>
            <td>{z}</td>
            <td>{e}</td>
          </tr>
        })) : "")}
      </tbody>
    </table>
  }
}

</code>```

Note: As per this code your id=1 which is first index of data will be rendered. if you want id=1 with fourth index will be latest then reverse your data array

```<code>data = data.reverse();
</code>```

Added this example as ref:
https://stackblitz.com/edit/react-jditah?file=src/index.js

Title: Update the table if value is unique

Body:
Let you received the props which has duplicate records like

data = [{
  id: 1,
  x: 40,
  y: 30,
  x: 20,
  e: 230
},{
  id: 2,
  x: 42,
  y: 32,
  x: 22,
  e: 232
},{
  id: 3,
  x: 41,
  y: 31,
  x: 21,
  e: 231
},
{
  id: 1,
  x: 4,
  y: 3,
  x: 2,
  e: 23
}];

Requirement: As per this data you want to render for unique ids with latest value id=1,2 and 3.

import React from "react";
import "./style.css";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { data: this.getUniqueAndUpdatedRecords(props) }
    console.log(this.state.data);
  }

  getUniqueAndUpdatedRecords(data) {
    return data.data.filter(function ({ id }) {
      return !this.has(id) && this.add(id);
    }, new Set());
  }

  render() {
    return <table>
      <thead>
        <tr>
          <th>x</th>
          <th>y</th>
          <th>z</th>
          <th>e</th>
        </tr>
      </thead>
      <tbody>
        {(this.state.data && this.state.data.length ? (this.state.data.map(({ id, x, y, z, e }) => {
          return <tr key={id}>
            <td>{x}</td>
            <td>{y}</td>
            <td>{z}</td>
            <td>{e}</td>
          </tr>
        })) : "")}
      </tbody>
    </table>
  }
}

Note: As per this code your id=1 which is first index of data will be rendered. if you want id=1 with fourth index will be latest then reverse your data array

data = data.reverse();

Added this example as ref:
https://stackblitz.com/edit/react-jditah?file=src/index.js


问:
React native custom drawer opening button creation
I am currently learing react native. I want to use custom button for open drawer. Tried many codes and not working.</p>

答: You can use navigation.openDrawer() and navigation.closeDrawer() as stated here


问:
Integrate Google Search Appliance with Rails Application
I wanted to integrate GSA with Rails. But the web proved to be un-helpful. Anybody knows any step-by-step tutorial.</p>

答:
First, you have to call the GSA with the search query. The reference informations for generating the GET-request is here: http://code.google.com/apis/searchappliance/documentation/610/xml_reference.html#SubmittingaSearchRequest

Then you will receive a xml response from the GSA with all needed information inside. The reference for the xml nodes are here (Look better at a xml response from your GSA and get additional informations in my link): http://code.google.com/apis/searchappliance/documentation/610/xml_reference.html#results_xml_tags

Last but not least, you have to parse the informations within the xml and generate your custom frontend.

I hope that will help you. It isn't really complicated.


问:
how to popup zoom in animation?
I need to apply many types of animations on a popup using pure CSS and javascript. I understand that I should use transition and transform. But I face a problem with applying this. (it gives me no animation)

here is my attempt zoom in.

function zoomIn(){
document.getElementById('layout').classList.add('show');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.layout{
  position: fixed;
  inset:0;

  background: rgba(0,0,0,.7);

  display: none;
  transition: transform 250ms, opacity 400ms;
}
.layout img{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
.show {
  display: block;
  transform: scale(1.2);
  opacity: 1;
}</code>```

<button onclick="zoomIn()" style="padding:20px">zoom in</button>

```

答:
The display none and block property can not be animated unfortunately. Your code looks good otherwise, so in this case you need to use visibility: visible; and visibility: hidden;. Like this:

function zoomIn(){
document.getElementById('layout').classList.add('show');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.layout{
  position: fixed;
  inset:0;
 visibility:hidden;
  background: rgba(0,0,0,.7);
  transition: transform 250ms, opacity 400ms;
}
.layout img{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);

}
.show {
  transform: scale(1.2);
    visibility: visible;
  opacity: 1;
}</code>```

<button onclick="zoomIn()" style="padding:20px">zoom in</button>

```

Title: how to popup zoom in animation?

Body:
I need to apply many types of animations on a popup using pure CSS and javascript. I understand that I should use transition and transform. But I face a problem with applying this. (it gives me no animation)

here is my attempt zoom in.

function zoomIn(){
document.getElementById('layout').classList.add('show');
}

.layout{
  position: fixed;
  inset:0;

  background: rgba(0,0,0,.7);

  display: none;
  transition: transform 250ms, opacity 400ms;
}
.layout img{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
.show {
  display: block;
  transform: scale(1.2);
  opacity: 1;
}

<button onclick="zoomIn()" style="padding:20px">zoom in</button>

Body:
The display none and block property can not be animated unfortunately. Your code looks good otherwise, so in this case you need to use visibility: visible; and visibility: hidden;. Like this:

function zoomIn(){
document.getElementById('layout').classList.add('show');
}

.layout{
  position: fixed;
  inset:0;
 visibility:hidden;
  background: rgba(0,0,0,.7);
  transition: transform 250ms, opacity 400ms;
}
.layout img{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);

}
.show {
  transform: scale(1.2);
    visibility: visible;
  opacity: 1;
}

<button onclick="zoomIn()" style="padding:20px">zoom in</button>

<div id="layout" class="layout">
<img src="https://media.istockphoto.com/illustrations/king-lion-aslan-illustration-id458017717?k=20&m=458017717&s=612x612&w=0&h=4qOseLgTPV5ZOEoZD2scNzf-LQ7AWoRXtbidR61OhG8=" width="400" />
</div>


问:
PL/SQL: ORA-01403 No data found when setting values to complex collection
I'm struggling with adding hours for specific limit in loop. I'd like to set up values from cursor c_hour to collection t_limits_in_plan (for current limit_id), but I'm doing something wrong in below loop.

I'm getting ORA-01403 No data found error, but dbms_output.put_line part is returning values, so there are hours specified for limit

I'm not sure if I can explain it well, so I'll show. I have function like this

```<code>    CREATE OR REPLACE FUNCTION testFunction (p_tLimits t_limit)
    RETURN t_limits_in_plan IS

    tLimitsInPlan t_limits_in_plan;
    tLimits       t_limit;
    nLimitId      number;

    CURSOR c_hour(LimitID number) IS
                                 SELECT *
                                   FROM hours h
                                  WHERE h.limit_id= LimitID;

  BEGIN
    tLimits := p_tLimits;

    FOR i IN tLimits.FIRST .. tLimits.LAST
    LOOP
      nLimitId := tLimits(i).id;

      FOR r_hour IN c_hour(nLimitId)
      LOOP
        --I CANNOT MAKE THIS PART TO WORK
       LimitsInPlan(tLimitsInPlan.last).hour_period_data(NVL(tLimitsInPlan(tLimitsInPlan.last).hour_period_data.last, 0) + 1).hour_from := r_hour.hour_from;
        tLimitsInPlan(tLimitsInPlan.last).hour_period_data(tLimitsInPlan(tLimitsInPlan.last).hour_period_data.last).hour_to               := r_hour.hour_to;
        dbms_output.put_line('Limit ' || nLimitId || '. Hours: ' || r_hour.hour_from || ' - ' || r_hour.hour_to);
      END LOOP;

    END LOOP;
    RETURN tLimitsInPlan;
  END testFunction;
</code>```

Types which I'm using are

```<code>  TYPE r_limits_in_plan IS RECORD (limit_in_plan_id     number
                                  ,limit                r_limit
                                  ,hour_period_data     t_hour_period_data_tab
                                  );

  TYPE t_limits_in_plan IS TABLE OF r_limits_in_plan INDEX BY binary_integer;
  -----------------------------------------------------------------------------------
  TYPE r_limit IS RECORD(limit_id   number
                        ,ind        varchar2(400)
                        );

  TYPE t_limit IS TABLE OF r_limit INDEX BY binary_integer;
  -----------------------------------------------------------------------------------
  TYPE t_hour_period_data IS RECORD(hour_from  number
                                   ,hour_to    number);

  TYPE t_hour_period_data_tab IS TABLE OF t_hour_period_data INDEX BY binary_integer;
</code>```

Edit:

```<code>I'm passing below Limit IDs to this functions
Limit ID: 26
Limit ID: 41
Limit ID: 81

So result that I'm expecting is
For LimitID 26 hours 2-3 / 12-15 / 20-23
            41 hours 5-7
            81 no hours
</code>```

Sample data in hour table

```<code>CREATE TABLE hours
(
  hour_from NUMBER not null,
  hour_to   NUMBER not null,
  limit_id  NUMBER(17) not null
)

INSERT INTO hours (hour_from, hour_to, limit_id) VALUES (12, 13, 23);
INSERT INTO hours (hour_from, hour_to, limit_id) VALUES (2, 3, 26);
INSERT INTO hours (hour_from, hour_to, limit_id) VALUES (12, 15, 26);
INSERT INTO hours (hour_from, hour_to, limit_id) VALUES (20, 23, 26);
INSERT INTO hours (hour_from, hour_to, limit_id) VALUES (5, 7, 41);
</code>```

Can anyone help? I think I added all requred informations, but if something needs clarification, I'll update

答:
The simplest solution is to pass data in using an SQL defined nested table collection and objects (rather than a PL/SQL defined associative array collection and records) and then you can do all the processing in a single query:

CREATE TYPE r_limit IS OBJECT(
   column1    number
  ,column2    varchar2(400)
  ,column3    varchar2(400)
  ,column4    number
);

CREATE TYPE t_limit IS TABLE OF r_limit;

CREATE TYPE t_hour_period_data IS OBJECT(
   hour_from  number
  ,hour_to    number
);

CREATE TYPE t_hour_period_data_tab IS TABLE OF t_hour_period_data;

CREATE TYPE r_limits_in_plan IS OBJECT(
   column1              number
  ,column2              varchar2(400)
  ,column3              varchar2(400)
  ,column4              varchar2(400)
  ,limit                r_limit
  ,hour_period_data     t_hour_period_data_tab
);

CREATE TYPE t_limits_in_plan IS TABLE OF r_limits_in_plan;
```
<p>You can define the function as:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE FUNCTION testFunction (p_tLimits t_limit)
RETURN t_limits_in_plan
IS
  tLimitsInPlan t_limits_in_plan;
BEGIN
  SELECT r_limits_in_plan(
           l.column1,
           l.column2,
           l.column3,
           l.column4,
           VALUE(l),
           ( SELECT CAST(
                      COLLECT(
                        t_hour_period_data(
                          h.hour_from,
                          h.hour_to
                        )
                      ) AS t_hour_period_data_tab
                    )
             FROM   hours h
             WHERE  l.column1 = h.limit_id
           )
         )
  BULK COLLECT INTO tLimitsInPlan
  FROM   TABLE(p_tLimits) l;

  RETURN tLimitsInPlan;
END testFunction;
/
</code>```

Then:

DECLARE
  v_limits t_limit := t_limit(
                        r_limit(26, '26 - Col2', '26 - Col3', 26.4),
                        r_limit(41, '41 - Col2', '41 - Col3', 41.4),
                        r_limit(81, '81 - Col2', '81 - Col3', 81.4)
                      );
  v_lip t_limits_in_plan;
BEGIN
  v_lip := testFunction(v_limits);
  FOR i IN 1 .. v_lip.COUNT LOOP
    DBMS_OUTPUT.PUT( v_lip(i).column1 || ': ' );

    FOR j IN 1 .. v_lip(i).hour_period_data.COUNT LOOP
      DBMS_OUTPUT.PUT( v_lip(i).hour_period_data(j).hour_from || '-' );
      DBMS_OUTPUT.PUT( v_lip(i).hour_period_data(j).hour_to || ' / ' );
    END LOOP;
    DBMS_OUTPUT.NEW_LINE();
  END LOOP;
END;
/
```
<p>Outputs:</p>
<blockquote>
```26: 2-3 / 12-15 / 20-23 /
41: 5-7 /
81:
```

db<>fiddle here

Body:
I'm struggling with adding hours for specific limit in loop. I'd like to set up values from cursor c_hour to collection t_limits_in_plan (for current limit_id), but I'm doing something wrong in below loop.

I'm getting ORA-01403 No data found error, but dbms_output.put_line part is returning values, so there are hours specified for limit

I'm not sure if I can explain it well, so I'll show. I have function like this

    CREATE OR REPLACE FUNCTION testFunction (p_tLimits t_limit)
    RETURN t_limits_in_plan IS

    tLimitsInPlan t_limits_in_plan;
    tLimits       t_limit;
    nLimitId      number;

    CURSOR c_hour(LimitID number) IS
                                 SELECT *
                                   FROM hours h
                                  WHERE h.limit_id= LimitID;

  BEGIN
    tLimits := p_tLimits;

    FOR i IN tLimits.FIRST .. tLimits.LAST
    LOOP
      nLimitId := tLimits(i).id;

      FOR r_hour IN c_hour(nLimitId)
      LOOP
        --I CANNOT MAKE THIS PART TO WORK
       LimitsInPlan(tLimitsInPlan.last).hour_period_data(NVL(tLimitsInPlan(tLimitsInPlan.last).hour_period_data.last, 0) + 1).hour_from := r_hour.hour_from;
        tLimitsInPlan(tLimitsInPlan.last).hour_period_data(tLimitsInPlan(tLimitsInPlan.last).hour_period_data.last).hour_to               := r_hour.hour_to;
        dbms_output.put_line('Limit ' || nLimitId || '. Hours: ' || r_hour.hour_from || ' - ' || r_hour.hour_to);
      END LOOP;

    END LOOP;
    RETURN tLimitsInPlan;
  END testFunction;

Types which I'm using are

  TYPE r_limits_in_plan IS RECORD (limit_in_plan_id     number
                                  ,limit                r_limit
                                  ,hour_period_data     t_hour_period_data_tab
                                  );

  TYPE t_limits_in_plan IS TABLE OF r_limits_in_plan INDEX BY binary_integer;
  -----------------------------------------------------------------------------------
  TYPE r_limit IS RECORD(limit_id   number
                        ,ind        varchar2(400)
                        );

  TYPE t_limit IS TABLE OF r_limit INDEX BY binary_integer;
  -----------------------------------------------------------------------------------
  TYPE t_hour_period_data IS RECORD(hour_from  number
                                   ,hour_to    number);

  TYPE t_hour_period_data_tab IS TABLE OF t_hour_period_data INDEX BY binary_integer;

Edit:

I'm passing below Limit IDs to this functions
Limit ID: 26
Limit ID: 41
Limit ID: 81

So result that I'm expecting is
For LimitID 26 hours 2-3 / 12-15 / 20-23
            41 hours 5-7
            81 no hours

Sample data in hour table

CREATE TABLE hours
(
  hour_from NUMBER not null,
  hour_to   NUMBER not null,
  limit_id  NUMBER(17) not null
)

INSERT INTO hours (hour_from, hour_to, limit_id) VALUES (12, 13, 23);
INSERT INTO hours (hour_from, hour_to, limit_id) VALUES (2, 3, 26);
INSERT INTO hours (hour_from, hour_to, limit_id) VALUES (12, 15, 26);
INSERT INTO hours (hour_from, hour_to, limit_id) VALUES (20, 23, 26);
INSERT INTO hours (hour_from, hour_to, limit_id) VALUES (5, 7, 41);

Can anyone help? I think I added all requred informations, but if something needs clarification, I'll update

Body:
The simplest solution is to pass data in using an SQL defined nested table collection and objects (rather than a PL/SQL defined associative array collection and records) and then you can do all the processing in a single query:

CREATE TYPE r_limit IS OBJECT(
   column1    number
  ,column2    varchar2(400)
  ,column3    varchar2(400)
  ,column4    number
);

CREATE TYPE t_limit IS TABLE OF r_limit;

CREATE TYPE t_hour_period_data IS OBJECT(
   hour_from  number
  ,hour_to    number
);

CREATE TYPE t_hour_period_data_tab IS TABLE OF t_hour_period_data;

CREATE TYPE r_limits_in_plan IS OBJECT(
   column1              number
  ,column2              varchar2(400)
  ,column3              varchar2(400)
  ,column4              varchar2(400)
  ,limit                r_limit
  ,hour_period_data     t_hour_period_data_tab
);

CREATE TYPE t_limits_in_plan IS TABLE OF r_limits_in_plan;

You can define the function as:

CREATE FUNCTION testFunction (p_tLimits t_limit)
RETURN t_limits_in_plan
IS
  tLimitsInPlan t_limits_in_plan;
BEGIN
  SELECT r_limits_in_plan(
           l.column1,
           l.column2,
           l.column3,
           l.column4,
           VALUE(l),
           ( SELECT CAST(
                      COLLECT(
                        t_hour_period_data(
                          h.hour_from,
                          h.hour_to
                        )
                      ) AS t_hour_period_data_tab
                    )
             FROM   hours h
             WHERE  l.column1 = h.limit_id
           )
         )
  BULK COLLECT INTO tLimitsInPlan
  FROM   TABLE(p_tLimits) l;

  RETURN tLimitsInPlan;
END testFunction;
/

Then:

DECLARE
  v_limits t_limit := t_limit(
                        r_limit(26, '26 - Col2', '26 - Col3', 26.4),
                        r_limit(41, '41 - Col2', '41 - Col3', 41.4),
                        r_limit(81, '81 - Col2', '81 - Col3', 81.4)
                      );
  v_lip t_limits_in_plan;
BEGIN
  v_lip := testFunction(v_limits);
  FOR i IN 1 .. v_lip.COUNT LOOP
    DBMS_OUTPUT.PUT( v_lip(i).column1 || ': ' );

    FOR j IN 1 .. v_lip(i).hour_period_data.COUNT LOOP
      DBMS_OUTPUT.PUT( v_lip(i).hour_period_data(j).hour_from || '-' );
      DBMS_OUTPUT.PUT( v_lip(i).hour_period_data(j).hour_to || ' / ' );
    END LOOP;
    DBMS_OUTPUT.NEW_LINE();
  END LOOP;
END;
/

Outputs:

26: 2-3 / 12-15 / 20-23 /
41: 5-7 /
81:

db<>fiddle here


问:
What does cv2.cornerHarris return?
I have been reading about cornerHarris in OpenCV. I read through the documentation but I am not sure what does this function return.

While reading through the examples, there is a statement written as:

```<code>dst = cv2.cornerHarris(gray,2,3,0.04)

img[dst>0.01*dst.max()]=[0,0,255]
</code>```

I just cannot understand the second statement above, may be because I do not understand, what is cornerHarris actually returning.

I do sense, that there is some kind of threshold being applied, but I cannot explain.

答:
```<code>dst = cv2.cornerHarris(gray,2,3,0.04)
</code>```

dst is resultant 2D probability array with the same shape as of input image.

```<code>img[dst>0.01*dst.max()]=[0,0,255]
</code>```

The above code is marely a post-processing technique, where "low-confidence-corners" are filtered out.

or to interpret differently:

Filter in those probabilities whose confidence is more than 1% of the max. probability in the resultant 2D probability array

From the examples documentation. If the image is less complex as given below, Even the below code will work fine:

```<code>img[dst == dst.max()]=[0,0,255]
</code>```

For more clarity, plot the resultant 2D probability array using matplotlib:

```<code>def display(img, mapp='gray'):
    plt.imshow(img, cmap=mapp)
    plt.show()
</code>```

Title: What does cv2.cornerHarris return?

Body:
I have been reading about cornerHarris in OpenCV. I read through the documentation but I am not sure what does this function return.

While reading through the examples, there is a statement written as:

dst = cv2.cornerHarris(gray,2,3,0.04)

img[dst>0.01*dst.max()]=[0,0,255]

I just cannot understand the second statement above, may be because I do not understand, what is cornerHarris actually returning.

I do sense, that there is some kind of threshold being applied, but I cannot explain.

Body:
dst = cv2.cornerHarris(gray,2,3,0.04)

dst is resultant 2D probability array with the same shape as of input image.

img[dst>0.01*dst.max()]=[0,0,255]

The above code is marely a post-processing technique, where "low-confidence-corners" are filtered out.

or to interpret differently:

Filter in those probabilities whose confidence is more than 1% of the max. probability in the resultant 2D probability array

From the examples documentation. If the image is less complex as given below, Even the below code will work fine:

img[dst == dst.max()]=[0,0,255]

For more clarity, plot the resultant 2D probability array using matplotlib:

def display(img, mapp='gray'):
    plt.imshow(img, cmap=mapp)
    plt.show()


问:
Why can I access Admin APIs with user credentials in basic auth Spring?
On hitting Admin Api GET http://localhost:8080/v1/admin/hello Spring Security is asking for credentials but by providing user credential (Username: user and password: user) api is returning with 200 Status.
I believe it should return 401 UnAuthorised for Admin Apis as i have passed user credentials instead of Admin creds.

What am I missing?

Following is my Controller class

```<code>@RestController
@RequestMapping("/v1")
public class HelloController {

    @GetMapping("/admin/hello")
    public String print123() {
        return "Hello admin";
    }

    @GetMapping("/user/hello")
    public String printAbc() {
        return "Hello user";
    }
}
</code>```

Following is spring securityConfig

```<code>@Configuration
@EnableWebSecurity
public class AuthConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  private BasicAuthenticationPoint basicAuthenticationPoint;

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
    http.authorizeRequests().antMatchers("/user/**").hasRole("USER")
                            .antMatchers("/admin/**").hasRole("ADMIN")
                            .anyRequest().authenticated();
    http.httpBasic().authenticationEntryPoint(basicAuthenticationPoint);

  }

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
          auth.inMemoryAuthentication()
              .withUser("user").password("{noop}user").roles("USER")
              .and()
              .withUser("admin").password("{noop}admin").roles("ADMIN", "USER");
  }

}
</code>```

答:
The matchers in AuthConfig are for "/user/**" and "/admin/**".

A request to http://localhost:8080/v1/admin/hello doesn't match either of those, so it is falls into the .anyRequest().authenticated() access rule.

Perhaps you meant to say .antMatchers("/v1/admin/**").hasRole("ADMIN").

Body:
On hitting Admin Api GET http://localhost:8080/v1/admin/hello Spring Security is asking for credentials but by providing user credential (Username: user and password: user) api is returning with 200 Status.
I believe it should return 401 UnAuthorised for Admin Apis as i have passed user credentials instead of Admin creds.

What am I missing?

Following is my Controller class

@RestController
@RequestMapping("/v1")
public class HelloController {

    @GetMapping("/admin/hello")
    public String print123() {
        return "Hello admin";
    }

    @GetMapping("/user/hello")
    public String printAbc() {
        return "Hello user";
    }
}

Following is spring securityConfig

@Configuration
@EnableWebSecurity
public class AuthConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  private BasicAuthenticationPoint basicAuthenticationPoint;

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
    http.authorizeRequests().antMatchers("/user/**").hasRole("USER")
                            .antMatchers("/admin/**").hasRole("ADMIN")
                            .anyRequest().authenticated();
    http.httpBasic().authenticationEntryPoint(basicAuthenticationPoint);

  }

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
          auth.inMemoryAuthentication()
              .withUser("user").password("{noop}user").roles("USER")
              .and()
              .withUser("admin").password("{noop}admin").roles("ADMIN", "USER");
  }

}


问:
How to properly define destructor
I am relatively new to C++ (and programming in general) so please forgive me if the question is not perfectly clear immediately.

What I have is a program in which a certain number of objects of a internally defined class [let's call this "class1"] are created.
The program works perfectly fine and the objects do what they should.

The problem that I am currently trying to solve is the following: these objects are not destroyed (and thus memory is not de-allocated) until the program exits, but I need that memory earlier.

Among the other members of the class there are objects of other internally defined classes (who also have members that are objects of a third class).

My question is the following: how do I properly define a destructor for the objects of "class1" so that all the data is cancelled and the memory deallocated?

I found out (probably this was obvious for you already) that a destructor like

```<code>class1::~class1(void) {

}
</code>```

won't work (I defined similar destructors for all internally defined classes).

Reading around I understood that my mistake could be that that is a destructor that does nothing. How do I solve this?

Thanks to anyone who will answer/help/comment.

Federico

答:
In C++ you need to free the memory manually. There's no garbage collector. You obviously need to free the memory manually inside your destructor. If you allocated the memory using new, you need to use delete for each resource you allocated with new inside the deconstructor, for example:

```<code>class1::~class1(void)
{
    delete resource1;
    delete resource2;
    etc...
}
</code>```

Title: How to properly define destructor

Body:
I am relatively new to C++ (and programming in general) so please forgive me if the question is not perfectly clear immediately.

What I have is a program in which a certain number of objects of a internally defined class [let's call this "class1"] are created.
The program works perfectly fine and the objects do what they should.

The problem that I am currently trying to solve is the following: these objects are not destroyed (and thus memory is not de-allocated) until the program exits, but I need that memory earlier.

Among the other members of the class there are objects of other internally defined classes (who also have members that are objects of a third class).

My question is the following: how do I properly define a destructor for the objects of "class1" so that all the data is cancelled and the memory deallocated?

I found out (probably this was obvious for you already) that a destructor like

class1::~class1(void) {

}

won't work (I defined similar destructors for all internally defined classes).

Reading around I understood that my mistake could be that that is a destructor that does nothing. How do I solve this?

Thanks to anyone who will answer/help/comment.

Federico

Body:
In C++ you need to free the memory manually. There's no garbage collector. You obviously need to free the memory manually inside your destructor. If you allocated the memory using new, you need to use delete for each resource you allocated with new inside the deconstructor, for example:

class1::~class1(void)
{
    delete resource1;
    delete resource2;
    etc...
}


问:
What HTTP method type should be used for recalculating the related resources
In my application I maintain couple of Shapes. And these shapes are calculated with respect to some reference point. And this reference point is considered as (0, 0). For example someone wants to move this reference point by (x, y), then distance of all existing Shapes need to be re-calculated with new reference point.

I have an REST API, to change this reference point, so internally all the Shapes distance is re-calculated with that (x, y) movement.

What HTTP method should be used for such operation POST, PUT or PATCH? As I don't find any one of these correct in the context, if I go by the definition of these HTTP method.

答:
What HTTP method should be used for such operation POST, PUT or PATCH? As I don't find any one of these correct in the context, if I go by the definition of these HTTP method.

It depends.

We use PUT/PATCH when the client edits a local copy of a resource, and sends the edited version of the document back to the server (aka "remote authoring").  Think "Save File".

We use POST when... well, pretty much for everything else.

POST serves many useful purposes in HTTP, including the general purpose of “this action isn’t worth standardizing.” -- Fielding, 2009

Think HTML forms here - information is dispatched to the origin server in a representation that is completely unrelated to the representation of the resource itself.

For example, in a resource model where we have a resource for the reference point itself

```<code>GET /example
</code>```
```<code>200 OK
Content-Type: appplication/json

{ "referencePoint": { "x": 0, "y": 0 } }
</code>```

The using remote authoring semantics is pretty reasonable

```<code>PUT /example
Content-Type: appplication/json

{ "referencePoint": { "x": 0, "y": 999 } }
</code>```

If the representation of the resource were very big (much bigger than the HTTP headers), and the changes were small, then we might use a patch document to communicate the information, rather than a complete document.

```<code>PATCH /example
Content-Type: application:json-patch+json

[ { "op": "replace", "path": "referencePoint/y", "value": 999 } ]
</code>```

In both cases, the basic idea is the same - we are requesting that the origin server change its copy of the resource to match the edited version on the client.

It is okay to use POST for everything else.

Body:
What HTTP method should be used for such operation POST, PUT or PATCH? As I don't find any one of these correct in the context, if I go by the definition of these HTTP method.

It depends.

We use PUT/PATCH when the client edits a local copy of a resource, and sends the edited version of the document back to the server (aka "remote authoring").  Think "Save File".

We use POST when... well, pretty much for everything else.

POST serves many useful purposes in HTTP, including the general purpose of “this action isn’t worth standardizing.” -- Fielding, 2009

Think HTML forms here - information is dispatched to the origin server in a representation that is completely unrelated to the representation of the resource itself.

For example, in a resource model where we have a resource for the reference point itself

GET /example

200 OK
Content-Type: appplication/json

{ "referencePoint": { "x": 0, "y": 0 } }

The using remote authoring semantics is pretty reasonable

PUT /example
Content-Type: appplication/json

{ "referencePoint": { "x": 0, "y": 999 } }

If the representation of the resource were very big (much bigger than the HTTP headers), and the changes were small, then we might use a patch document to communicate the information, rather than a complete document.

PATCH /example
Content-Type: application:json-patch+json

[ { "op": "replace", "path": "referencePoint/y", "value": 999 } ]

In both cases, the basic idea is the same - we are requesting that the origin server change its copy of the resource to match the edited version on the client.

It is okay to use POST for everything else.


问:
Code should kill the terminal before generating a loop because it found the value but it is only killing it after looping
For this project I'm using Visual Studio Code on Windows 11

In this file example StackOverflowTest.py, if there are 5 values in the list, I want the terminal to be killed:

```<code>import os
import signal

def kill_terminal():
    os.kill(os.getppid(), signal.SIGTERM)

def test_kill():
    list_test = [1,2,3,4,5]
    if (len(list_test) == 5):
        kill_terminal()

def main():
    print('Start Process')
    test_kill()

</code>```

I created a loop to activate the main() function from the previous file, but in theory it was to kill the terminal on the first call that is made, but that doesn't happen, it only kills the terminal in the second looping:

```<code>from random import randint
import time
import schedule
import StackOverflowTest
import sys

StackOverflowTest.main()
def trigger():
    StackOverflowTest.main()
schedule.every(1).seconds.do(trigger)

while 1:
    schedule.run_pending()
    for remaining in range(randint(5,10), 0, -1):
        sys.stdout.write('\r')
        sys.stdout.write('Next activation in {:2d} seconds'.format(remaining))
        sys.stdout.flush()
        time.sleep(1)
    sys.stdout.write('\r                               \n')
</code>```

The correct way it should happen would be like this:

As it finds the value 5, the correct thing was to kill the terminal after the first Start Process.

```<code>Start Process
~~~~KILL TERMINAL~~~~
</code>```

However as it is not working correctly, it is happening like this:

```<code>Start Process
Next activation in 3 seconds
Next activation in 2 seconds
Next activation in 1 seconds
Start Process
~~~~KILL TERMINAL~~~~
</code>```

As can be seen he kill the terminal only in the second time run main().

How should I go about solving this problem?

答:
In Windows, signal has a CTRL_C_EVENT that can be sent to console processes that share a common console window. See the documentation here.

So if you replace the kill_terminal function for the following:

```<code>def kill_terminal():
    os.kill(os.getppid(), signal.CTRL_C_EVENT)
</code>```

the terminal closes immediately.

I think the reason why SIGTERM doesn't work is that the Python interpreter process is a child of the cmd.exe process and therefore waits for it. SIGKILL is only available for Unix, so it seems that CTRL_C_EVENT does the job for Windows.

The implementation of signals for Windows is a bit confusing. Read more in this answer.

Body:
For this project I'm using Visual Studio Code on Windows 11

In this file example StackOverflowTest.py, if there are 5 values in the list, I want the terminal to be killed:

import os
import signal

def kill_terminal():
    os.kill(os.getppid(), signal.SIGTERM)

def test_kill():
    list_test = [1,2,3,4,5]
    if (len(list_test) == 5):
        kill_terminal()

def main():
    print('Start Process')
    test_kill()

I created a loop to activate the main() function from the previous file, but in theory it was to kill the terminal on the first call that is made, but that doesn't happen, it only kills the terminal in the second looping:

from random import randint
import time
import schedule
import StackOverflowTest
import sys

StackOverflowTest.main()
def trigger():
    StackOverflowTest.main()
schedule.every(1).seconds.do(trigger)

while 1:
    schedule.run_pending()
    for remaining in range(randint(5,10), 0, -1):
        sys.stdout.write('\r')
        sys.stdout.write('Next activation in {:2d} seconds'.format(remaining))
        sys.stdout.flush()
        time.sleep(1)
    sys.stdout.write('\r                               \n')

The correct way it should happen would be like this:

As it finds the value 5, the correct thing was to kill the terminal after the first Start Process.

Start Process
~~~~KILL TERMINAL~~~~

However as it is not working correctly, it is happening like this:

Start Process
Next activation in 3 seconds
Next activation in 2 seconds
Next activation in 1 seconds
Start Process
~~~~KILL TERMINAL~~~~

As can be seen he kill the terminal only in the second time run main().

How should I go about solving this problem?

Body:
In Windows, signal has a CTRL_C_EVENT that can be sent to console processes that share a common console window. See the documentation here.

So if you replace the kill_terminal function for the following:

def kill_terminal():
    os.kill(os.getppid(), signal.CTRL_C_EVENT)

the terminal closes immediately.

I think the reason why SIGTERM doesn't work is that the Python interpreter process is a child of the cmd.exe process and therefore waits for it. SIGKILL is only available for Unix, so it seems that CTRL_C_EVENT does the job for Windows.

The implementation of signals for Windows is a bit confusing. Read more in this answer.