问:
How to create a macro in VBA that can automatically determine the boundaries of a matrix
I've started programing in VBA yesterday, and as such I am still quite the newbie at it.

I've tried to make a macro that automatically defines certain areas for me, and while it works quite well in my sheet, it is still limited in the sense that all sheets I use it on have to be identical in setup.

I am currently defining 5 areas

A_mål - Single Cell

Tank_Tabel - Matrix

Int_Tabel - Matrix

Bund - Single Cell

HF - Single Cell

The optimal macro for my problem would be one that prompts the user to enter a number of a container, and then uses that number to automatically determine what sheet the information of said container can be found on, and the automatically determine where the listed areas are, and define them with the given names and the number that the user has entered.

The code can be seen here:

```<code>Option Compare Text
Sub Definer()
    Dim TankNr As Integer, rHF As Range, rAM As Range, rBV As Range, rTT As Range, rIT As Range

    If MsgBox("Vil du definere nye områder for en tank", vbYesNo, "Confirm") = vbYes Then

        TankNr = Application.InputBox("Indtast tank nr på den tank du vil definere områder for", "Tank Nummer", Type:=1)
        If TankNr <> 0 Then

            Set rHF = Sheets("Tank " & TankNr).Cells.Find(What:="HØJESTE FYLDEGRÆNSE =", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
            If Not rHF Is Nothing Then
                rHF.Offset(, 3).Name = "HF_" & TankNr
            End If

            Set rTT = Sheets("Tank " & TankNr).Cells.Find(What:="Enhed i tabellen : Liter", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
            If Not rTT Is Nothing Then
                rTT.CurrentRegion.Offset(2, 0).Resize(rTT.CurrentRegion.Rows.Count - 2).Name = "Tabel_tank" & TankNr
            End If

            Set rIT = Sheets("Tank " & TankNr).Cells.Find(What:="Interpolationstabel", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
            If Not rIT Is Nothing Then
                rIT.Resize(11, 11).Offset(1, 0).Name = "Int_tank" & TankNr
            End If

            Set rBV = Sheets("Tank " & TankNr).Cells.Find(What:="Bundvolumen =", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
            If Not rBV Is Nothing Then
                rBV.Offset(, 2).Name = "Bund" & TankNr
            End If

            Set rAM = Sheets("Tank " & TankNr).Cells.Find(What:="A-MÅL =", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
            If Not rAM Is Nothing Then
                rAM.Offset(, 1).Name = "A_mål" & TankNr
            End If

            MsgBox "Områder er blevet defineret"

        End If
    End If
End Sub
</code>```

There are several problems with this:

If the user enters a non integer in the input box, the code ends up with an error, rather than just ending the macro. Solved

If the user hits cancel in the input box, the code also ends up with an error rather than ending the macro. Solved

I tried to use the input "TankNr" as a reference, but it doesn't return the value of the cell, but just what I've written as the reference Solved

Finally, the current boundaries of each defined area is determined by me manually, and it works fine if the values I am looking for is actually in those specific cells. Sometimes the setup of the sheets might vary, and as such I need the macro to be able to automatically determine where the boundaries of the defined areas should be  Solved

The sheets in question can be seen

Due to my reputation, I can only include these two links, but if there's a way to provide more documentation of my work, tell me and I'll happily do so.

答:
I am not sure, if my understanding is correct. You may iterate a loop through starting range of Sheet 2, to get the addresses.
For example, if the labels like "A_Mål", "HF","Bundvolumen" will remain same in Sheet 2, you may use:

```<code>Sub GetRanges()
Dim A2, HF2, BV2, TT2, IT
For Each c In Range("A1:Z100")
' A1:Z100 is Random range, which might contain the ranges required
    If c.Value = "A_Mål" Then
    ' Check if this cell value matches A_Mål
        A2 = c.Offset(rowOffset:=0, columnOffset:=1).Address
        ' Use Offset to take the one cell to right of matching cell
    ElseIf c.Value = "HF" Then
    ' Check if this cell value matches HF
        HF2 = c.Offset(rowOffset:=0, columnOffset:=1).Address
        ' Use Offset to take the one cell to right of matching cell
    ElseIf c.Value = "Bundvolumen" Then
    ' Check if this cell value matches Bundvolumen
        BV2 = c.Offset(rowOffset:=0, columnOffset:=1).Address
        ' Use Offset to take the one cell to right of matching cell
    ElseIf c.Value = "CM" Then
    ' Check if this cell value matches HF
        TT2 = c.CurrentRegion.Address
        ' Use CurrentRegion to take the current continous data of matching cell
    ElseIf c.Value = "INTERPOLCATIONSTABEL" Then
    ' Check if this cell value matches INTERPOLCATIONSTABEL
        IT2 = c.Offset(rowOffset:=0, columnOffset:=1).CurrentRegion.Address
        ' Use Offset to take the one cell to right of matching cell
        ' Use CurrentRegion to take the current continous data of matching cell
    End If
End Sub
</code>```

Note: These variables gives you addresses of ranges in string data type
If you want actual ranges, simply remove ".address" from each line wherever mentions it.

Note2: A checked, label "Bundvolumen" has changed to "Volume" in Sheet 2.
The macro given above wont work in such cases.
But if you know the exhaustive list of names, which can be used to refer, it can be included with "OR" conditions in "IF" statements. Such as:

```<code>ElseIf c.Value = "Bundvolumen" or c.Value = "Volume" Then
</code>```

Body:
I've started programing in VBA yesterday, and as such I am still quite the newbie at it.

I've tried to make a macro that automatically defines certain areas for me, and while it works quite well in my sheet, it is still limited in the sense that all sheets I use it on have to be identical in setup.

I am currently defining 5 areas

A_mål - Single Cell

Tank_Tabel - Matrix

Int_Tabel - Matrix

Bund - Single Cell

HF - Single Cell

The optimal macro for my problem would be one that prompts the user to enter a number of a container, and then uses that number to automatically determine what sheet the information of said container can be found on, and the automatically determine where the listed areas are, and define them with the given names and the number that the user has entered.

The code can be seen here:

Option Compare Text
Sub Definer()
    Dim TankNr As Integer, rHF As Range, rAM As Range, rBV As Range, rTT As Range, rIT As Range

    If MsgBox("Vil du definere nye områder for en tank", vbYesNo, "Confirm") = vbYes Then

        TankNr = Application.InputBox("Indtast tank nr på den tank du vil definere områder for", "Tank Nummer", Type:=1)
        If TankNr <> 0 Then

            Set rHF = Sheets("Tank " & TankNr).Cells.Find(What:="HØJESTE FYLDEGRÆNSE =", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
            If Not rHF Is Nothing Then
                rHF.Offset(, 3).Name = "HF_" & TankNr
            End If

            Set rTT = Sheets("Tank " & TankNr).Cells.Find(What:="Enhed i tabellen : Liter", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
            If Not rTT Is Nothing Then
                rTT.CurrentRegion.Offset(2, 0).Resize(rTT.CurrentRegion.Rows.Count - 2).Name = "Tabel_tank" & TankNr
            End If

            Set rIT = Sheets("Tank " & TankNr).Cells.Find(What:="Interpolationstabel", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
            If Not rIT Is Nothing Then
                rIT.Resize(11, 11).Offset(1, 0).Name = "Int_tank" & TankNr
            End If

            Set rBV = Sheets("Tank " & TankNr).Cells.Find(What:="Bundvolumen =", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
            If Not rBV Is Nothing Then
                rBV.Offset(, 2).Name = "Bund" & TankNr
            End If

            Set rAM = Sheets("Tank " & TankNr).Cells.Find(What:="A-MÅL =", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
            If Not rAM Is Nothing Then
                rAM.Offset(, 1).Name = "A_mål" & TankNr
            End If

            MsgBox "Områder er blevet defineret"

        End If
    End If
End Sub

There are several problems with this:

If the user enters a non integer in the input box, the code ends up with an error, rather than just ending the macro. Solved

If the user hits cancel in the input box, the code also ends up with an error rather than ending the macro. Solved

I tried to use the input "TankNr" as a reference, but it doesn't return the value of the cell, but just what I've written as the reference Solved

Finally, the current boundaries of each defined area is determined by me manually, and it works fine if the values I am looking for is actually in those specific cells. Sometimes the setup of the sheets might vary, and as such I need the macro to be able to automatically determine where the boundaries of the defined areas should be  Solved

The sheets in question can be seen

Due to my reputation, I can only include these two links, but if there's a way to provide more documentation of my work, tell me and I'll happily do so.

Body:
I am not sure, if my understanding is correct. You may iterate a loop through starting range of Sheet 2, to get the addresses.
For example, if the labels like "A_Mål", "HF","Bundvolumen" will remain same in Sheet 2, you may use:

Sub GetRanges()
Dim A2, HF2, BV2, TT2, IT
For Each c In Range("A1:Z100")
' A1:Z100 is Random range, which might contain the ranges required
    If c.Value = "A_Mål" Then
    ' Check if this cell value matches A_Mål
        A2 = c.Offset(rowOffset:=0, columnOffset:=1).Address
        ' Use Offset to take the one cell to right of matching cell
    ElseIf c.Value = "HF" Then
    ' Check if this cell value matches HF
        HF2 = c.Offset(rowOffset:=0, columnOffset:=1).Address
        ' Use Offset to take the one cell to right of matching cell
    ElseIf c.Value = "Bundvolumen" Then
    ' Check if this cell value matches Bundvolumen
        BV2 = c.Offset(rowOffset:=0, columnOffset:=1).Address
        ' Use Offset to take the one cell to right of matching cell
    ElseIf c.Value = "CM" Then
    ' Check if this cell value matches HF
        TT2 = c.CurrentRegion.Address
        ' Use CurrentRegion to take the current continous data of matching cell
    ElseIf c.Value = "INTERPOLCATIONSTABEL" Then
    ' Check if this cell value matches INTERPOLCATIONSTABEL
        IT2 = c.Offset(rowOffset:=0, columnOffset:=1).CurrentRegion.Address
        ' Use Offset to take the one cell to right of matching cell
        ' Use CurrentRegion to take the current continous data of matching cell
    End If
End Sub

Note: These variables gives you addresses of ranges in string data type
If you want actual ranges, simply remove ".address" from each line wherever mentions it.

Note2: A checked, label "Bundvolumen" has changed to "Volume" in Sheet 2.
The macro given above wont work in such cases.
But if you know the exhaustive list of names, which can be used to refer, it can be included with "OR" conditions in "IF" statements. Such as:

ElseIf c.Value = "Bundvolumen" or c.Value = "Volume" Then


来源: stackexchange

问:
Python: subclass inherits super class attributes, but loses it's other attributes
So, I've written a class to represent vectors called Vector, and i'm trying to write a subclass called Visual_vector that contains additional attributes pertaining to how the vector will be displayed on screen, such as the origin and endpoint of the line to be drawn. My issue is that when I create an instance of Visual_vector, it loses self.origin and self.end_point:

```<code>>>> a = Visual_vector((0, 0), (45, 330))
>>> a.x
45
>>> a.y
330
>>> a.length
333.0540496676178
>>> a.origin
>>> a.end_point
</code>```

I suspect this might have something to do with my use of getattr and setattr in the super class, but other than that I have no idea what the issue is

Vector class:

```<code>class Vector():
    """A class to represent a 2D vector"""
    def __init__(self, tup):
        self.x = tup[0]
        self.y = tup[1]

    # retrieving attributes
    def __getattr__(self, name):
        if name == 'vector':
            # returns the vector as a tuple
            # (x, y)
            return (self.x, self.y)

        elif name == 'length' or name == 'magnitude':
            # returns the length as a float
            # sqrt(x^2 + y^2)
            return float( sqrt(self.x**2 + self.y**2) )

        elif name == 'normal':
            # returns a normalized vector as a tuple
            # (x/l, y/l)
            if self.length == 0:
                return (0, 0)
            else:
                x = self.x / self.length
                y = self.y / self.length
                return (x, y)
                #return (self.x / self.length, self.y / self.length)

    # setting attributes
    def __setattr__(self, name, value):
        if name == 'x' or name == 'y':
            # assign value normally
            self.__dict__[name] = value

        elif name == 'length':
            # |(x, y)| * length
            # create a new, normalized vector of the same trajectory
            new_vector = Vector(self.normal)
            # then multiply it by a scalar to get the desired length
            self.x = new_vector.x * value
            self.y = new_vector.y * value

        elif name == 'vector':
            # does the same as setting both x and y at the same time
            if len(value) == 2:     # must be a list or tuple
                self.x = value[0]
                self.y = value[1]

    # mathematical operations
    def __add__(self, other):
        # (x1 + x2, y1 + y2)
        x = self.x + other.x
        y = self.y + other.y
        return Vector((x, y))

    def __iadd__(self, other):
        return self + other

    def __sub__(self, other):
        # (x1 - x2, y1 - y2)
        x = self.x - other.x
        y = self.y - other.y
        return Vector((x, y))

    def __isub__(self, other):
        return self - other
</code>```

Visual_vector class:

```<code>class Visual_vector(Vector):
    """A class to represent the vectors shown on screen"""
    def __init__(self, origin, end_point):
        # qualities relative to a coord system
        Vector.__init__(self, end_point)

        # qualities relative to the screen
        self.origin = origin
        self.end_point = end_point
</code>```

答:
You should not use such a __setattr__-Method because of your observed wired behaviour. Replace it with a length- or vector-property

```<code>class Vector(object):
    """A class to represent a 2D vector"""
    def __init__(self, tup):
        self.x = tup[0]
        self.y = tup[1]

    # retrieving attributes
    @property
    def vector(self):
        # returns the vector as a tuple
        # (x, y)
        return (self.x, self.y)

    @vector.setter
    def vector(self, value):
        self.x = value[0]
        self.y = value[1]

    @property
    def length(self):
        # returns the length as a float
        # sqrt(x^2 + y^2)
        return float( sqrt(self.x**2 + self.y**2) )
    magnitude = length

    @length.setter
    def length(self, value):
        # |(x, y)| * length
        # create a new, normalized vector of the same trajectory
        x, y = self.normal
        # then multiply it by a scalar to get the desired length
        self.x = x * value
        self.y = y * value

    @property
    def normal(self):
        # returns a normalized vector as a tuple
        # (x/l, y/l)
        len = self.length
        if len == 0:
            return (0, 0)
        else:
            x = self.x / len
            y = self.y / len
            return (x, y)

    # mathematical operations
    def __add__(self, other):
        # (x1 + x2, y1 + y2)
        x = self.x + other.x
        y = self.y + other.y
        return Vector((x, y))

    def __iadd__(self, other):
        self.x += other.x
        self.y += other.y
        return self

    def __sub__(self, other):
        # (x1 - x2, y1 - y2)
        x = self.x - other.x
        y = self.y - other.y
        return Vector((x, y))

    def __isub__(self, other):
        self.x -= other.x
        self.y -= other.y
        return self

class Visual_vector(Vector):
    """A class to represent the vectors shown on screen"""
    def __init__(self, origin, end_point):
        # qualities relative to a coord system
        Vector.__init__(self, end_point)

        # qualities relative to the screen
        self.origin = origin
        self.end_point = end_point
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So, I've written a class to represent vectors called Vector, and i'm trying to write a subclass called Visual_vector that contains additional attributes pertaining to how the vector will be displayed on screen, such as the origin and endpoint of the line to be drawn. My issue is that when I create an instance of Visual_vector, it loses self.origin and self.end_point:

>>> a = Visual_vector((0, 0), (45, 330))
>>> a.x
45
>>> a.y
330
>>> a.length
333.0540496676178
>>> a.origin
>>> a.end_point

I suspect this might have something to do with my use of getattr and setattr in the super class, but other than that I have no idea what the issue is

Vector class:

class Vector():
    """A class to represent a 2D vector"""
    def __init__(self, tup):
        self.x = tup[0]
        self.y = tup[1]

    # retrieving attributes
    def __getattr__(self, name):
        if name == 'vector':
            # returns the vector as a tuple
            # (x, y)
            return (self.x, self.y)

        elif name == 'length' or name == 'magnitude':
            # returns the length as a float
            # sqrt(x^2 + y^2)
            return float( sqrt(self.x**2 + self.y**2) )

        elif name == 'normal':
            # returns a normalized vector as a tuple
            # (x/l, y/l)
            if self.length == 0:
                return (0, 0)
            else:
                x = self.x / self.length
                y = self.y / self.length
                return (x, y)
                #return (self.x / self.length, self.y / self.length)

    # setting attributes
    def __setattr__(self, name, value):
        if name == 'x' or name == 'y':
            # assign value normally
            self.__dict__[name] = value

        elif name == 'length':
            # |(x, y)| * length
            # create a new, normalized vector of the same trajectory
            new_vector = Vector(self.normal)
            # then multiply it by a scalar to get the desired length
            self.x = new_vector.x * value
            self.y = new_vector.y * value

        elif name == 'vector':
            # does the same as setting both x and y at the same time
            if len(value) == 2:     # must be a list or tuple
                self.x = value[0]
                self.y = value[1]

    # mathematical operations
    def __add__(self, other):
        # (x1 + x2, y1 + y2)
        x = self.x + other.x
        y = self.y + other.y
        return Vector((x, y))

    def __iadd__(self, other):
        return self + other

    def __sub__(self, other):
        # (x1 - x2, y1 - y2)
        x = self.x - other.x
        y = self.y - other.y
        return Vector((x, y))

    def __isub__(self, other):
        return self - other

Visual_vector class:

class Visual_vector(Vector):
    """A class to represent the vectors shown on screen"""
    def __init__(self, origin, end_point):
        # qualities relative to a coord system
        Vector.__init__(self, end_point)

        # qualities relative to the screen
        self.origin = origin
        self.end_point = end_point

Body:
You should not use such a __setattr__-Method because of your observed wired behaviour. Replace it with a length- or vector-property

class Vector(object):
    """A class to represent a 2D vector"""
    def __init__(self, tup):
        self.x = tup[0]
        self.y = tup[1]

    # retrieving attributes
    @property
    def vector(self):
        # returns the vector as a tuple
        # (x, y)
        return (self.x, self.y)

    @vector.setter
    def vector(self, value):
        self.x = value[0]
        self.y = value[1]

    @property
    def length(self):
        # returns the length as a float
        # sqrt(x^2 + y^2)
        return float( sqrt(self.x**2 + self.y**2) )
    magnitude = length

    @length.setter
    def length(self, value):
        # |(x, y)| * length
        # create a new, normalized vector of the same trajectory
        x, y = self.normal
        # then multiply it by a scalar to get the desired length
        self.x = x * value
        self.y = y * value

    @property
    def normal(self):
        # returns a normalized vector as a tuple
        # (x/l, y/l)
        len = self.length
        if len == 0:
            return (0, 0)
        else:
            x = self.x / len
            y = self.y / len
            return (x, y)

    # mathematical operations
    def __add__(self, other):
        # (x1 + x2, y1 + y2)
        x = self.x + other.x
        y = self.y + other.y
        return Vector((x, y))

    def __iadd__(self, other):
        self.x += other.x
        self.y += other.y
        return self

    def __sub__(self, other):
        # (x1 - x2, y1 - y2)
        x = self.x - other.x
        y = self.y - other.y
        return Vector((x, y))

    def __isub__(self, other):
        self.x -= other.x
        self.y -= other.y
        return self

class Visual_vector(Vector):
    """A class to represent the vectors shown on screen"""
    def __init__(self, origin, end_point):
        # qualities relative to a coord system
        Vector.__init__(self, end_point)

        # qualities relative to the screen
        self.origin = origin
        self.end_point = end_point


问:
Java Annotation attached to new objects?
Is it possible to attach an annotation to a new object?

Let's say we have a simple house object, House house = new House ()
and annotations @Large and @Spooky.

My idea was to have a switch statement so a house marked as @Spooky does something different than a house marked as @Large.

```<code>@Spooky
House house = new House();

System.out.println(house.getClass().getAnnotations().length);
</code>```

Apparently there is no annotation on my new house object as length == 0.

Why is that?

答:
In General

You can't annotate an object (that exists at runtime only). You just can annotate a declaration or, since Java 8, a type usage (that exists already at compile time).

See The Java™ Tutorials, Annotations, Annotations Basics:

Where Annotations Can Be Used

Annotations can be applied to declarations: declarations of classes, fields, methods, and other program elements. [...]
  As of the Java SE 8 release, annotations can also be applied to the use of types.

and The Java™ Tutorials, Annotations, Type Annotations [...]:

Before the Java SE 8 release, annotations could only be applied to declarations. As of the Java SE 8 release, annotations can also be applied to any type use. This means that annotations can be used anywhere you use a type. A few examples of where types are used are class instance creation expressions (new), casts, implements clauses, and throws clauses. This form of annotation is called a type annotation [...].

and the unfailingly ultimate source The Java® Language Specification, 9.6.4. Predefined Annotation Types:

9.6.4.1. @Target

Annotation types may be applicable in declaration contexts, where annotations apply to declarations, or in type contexts, where annotations apply to types used in declarations and expressions.

[Emphases by me.]

Anwer to your question

As  @M.Prokhorov mentions in his comment to your question you're not annotating your House class but the local variable declaration of house, that is of type House.

See also this Java Annotations Tutorial:

Annotation Placement

You can place Java [declaration] annotations above classes, interfaces, methods, method parameters, fields and local variables.
  [...]

Creating Your Own Annotations

[...]

@Retention

[...]

```<code>@Retention(RetentionPolicy.RUNTIME)
</code>```

This is what signals to the Java compiler and JVM that the annotation should be available via reflection at runtime.

[...]

RetentionPolicy.CLASS means that the annotation is stored in the .class file, but not available at runtime. This is the default retention policy, if you do not specify any retention policy at all.

[Emphases by me.]

That means you have to declare your Spooky annotation with:

```<code>@Retention( RetentionPolicy.RUNTIME )
public @interface Spooky {}
</code>```

However, as @LouisWasserman mentions in his comment to your question:

I don't believe there's any way to get the annotations from a local variable.

See also the SO question ElementType.LOCAL_VARIABLE annotation type and the aforementioned JLS:

9.6.4.1. @Target

[...]

An annotation on a local variable declaration is never retained in the binary representation.

So, if you'd make house a field (a.k.a. member variable):

```<code>@Spooky
private House house = new House();
</code>```

you could use:

```<code>Stream.of( this.getClass().getDeclaredFields() )
    .forEach( field -> Stream.of( field.getAnnotations() )
        .forEach( annotation -> System.out.printf( "@%s%n%s %s %s;%n",
            annotation.annotationType().getSimpleName(),
            Modifier.toString( field.getModifiers() ),
            field.getType().getSimpleName(),
            field.getName() ) ) );
</code>```

or if you want to get the house field specifically:

```<code>try {
    final Field field = this.getClass().getDeclaredField( "house" );
    final Spooky spooky = field.getAnnotation( Spooky.class );
    if ( spooky != null ) {
        System.out.printf( "@%s%n%s %s %s;%n",
            spooky.annotationType().getSimpleName(),
            Modifier.toString( field.getModifiers() ),
            field.getType().getSimpleName(),
            field.getName() );
    }
}
catch ( NoSuchFieldException | SecurityException e ) {
    e.printStackTrace();
}
</code>```

Output in both cases:

```<code>@Spooky
private House house;
</code>```

But, as you see, even with the conciseness of streams your code doesn't become clearer with that. I'd consider the suggestions made in the comments to your questions.

Body:
Is it possible to attach an annotation to a new object?

Let's say we have a simple house object, House house = new House ()
and annotations @Large and @Spooky.

My idea was to have a switch statement so a house marked as @Spooky does something different than a house marked as @Large.

@Spooky
House house = new House();

System.out.println(house.getClass().getAnnotations().length);

Apparently there is no annotation on my new house object as length == 0.

Why is that?

Body:
In General

You can't annotate an object (that exists at runtime only). You just can annotate a declaration or, since Java 8, a type usage (that exists already at compile time).

See The Java™ Tutorials, Annotations, Annotations Basics:

Where Annotations Can Be Used

Annotations can be applied to declarations: declarations of classes, fields, methods, and other program elements. [...]
  As of the Java SE 8 release, annotations can also be applied to the use of types.

and The Java™ Tutorials, Annotations, Type Annotations [...]:

Before the Java SE 8 release, annotations could only be applied to declarations. As of the Java SE 8 release, annotations can also be applied to any type use. This means that annotations can be used anywhere you use a type. A few examples of where types are used are class instance creation expressions (new), casts, implements clauses, and throws clauses. This form of annotation is called a type annotation [...].

and the unfailingly ultimate source The Java® Language Specification, 9.6.4. Predefined Annotation Types:

9.6.4.1. @Target

Annotation types may be applicable in declaration contexts, where annotations apply to declarations, or in type contexts, where annotations apply to types used in declarations and expressions.

[Emphases by me.]

Anwer to your question

As  @M.Prokhorov mentions in his comment to your question you're not annotating your House class but the local variable declaration of house, that is of type House.

See also this Java Annotations Tutorial:

Annotation Placement

You can place Java [declaration] annotations above classes, interfaces, methods, method parameters, fields and local variables.
  [...]

Creating Your Own Annotations

[...]

@Retention

[...]

@Retention(RetentionPolicy.RUNTIME)

This is what signals to the Java compiler and JVM that the annotation should be available via reflection at runtime.

[...]

RetentionPolicy.CLASS means that the annotation is stored in the .class file, but not available at runtime. This is the default retention policy, if you do not specify any retention policy at all.

[Emphases by me.]

That means you have to declare your Spooky annotation with:

@Retention( RetentionPolicy.RUNTIME )
public @interface Spooky {}

However, as @LouisWasserman mentions in his comment to your question:

I don't believe there's any way to get the annotations from a local variable.

See also the SO question ElementType.LOCAL_VARIABLE annotation type and the aforementioned JLS:

9.6.4.1. @Target

[...]

An annotation on a local variable declaration is never retained in the binary representation.

So, if you'd make house a field (a.k.a. member variable):

@Spooky
private House house = new House();

you could use:

Stream.of( this.getClass().getDeclaredFields() )
    .forEach( field -> Stream.of( field.getAnnotations() )
        .forEach( annotation -> System.out.printf( "@%s%n%s %s %s;%n",
            annotation.annotationType().getSimpleName(),
            Modifier.toString( field.getModifiers() ),
            field.getType().getSimpleName(),
            field.getName() ) ) );

or if you want to get the house field specifically:

try {
    final Field field = this.getClass().getDeclaredField( "house" );
    final Spooky spooky = field.getAnnotation( Spooky.class );
    if ( spooky != null ) {
        System.out.printf( "@%s%n%s %s %s;%n",
            spooky.annotationType().getSimpleName(),
            Modifier.toString( field.getModifiers() ),
            field.getType().getSimpleName(),
            field.getName() );
    }
}
catch ( NoSuchFieldException | SecurityException e ) {
    e.printStackTrace();
}

Output in both cases:

@Spooky
private House house;

But, as you see, even with the conciseness of streams your code doesn't become clearer with that. I'd consider the suggestions made in the comments to your questions.


问:
How to pass password to scp?
I know it is not recommended, but is it at all possible to pass the user's password to scp?

I'd like to copy a file via scp as part of a batch job and the receiving server does, of course, need a password and, no, I cannot easily change that to key-based authentication.

答:
If you are connecting to the server from Windows, the Putty version of scp ("pscp") lets you pass the password with the -pw parameter.

This is mentioned in the documentation here.

OwnerDisplayName: Argelbargel

Title: How to pass password to scp?


问:
Mapping of user level and kernel level thread
While going through OPERATING SYSTEM PRINCIPLES, 7TH ED

(By Abraham Silberschatz, Peter Baer Galvin, Greg Gagne), i encountered a

statement in Thread Scheduling Section.It is given as -:

To run on a CPU, user-level threads must ultimately be mapped
  to an associated kernel-level thread, although this mapping may
  be indirect and may use a lightweight process (LWP).

The first half of the statement i.e

To run on a CPU, user-level threads must ultimately be mapped  to an associated kernel-level

is trying to say that When a user level thread is executed ,it will need support from kernel thread like system calls.

But i am completely stuck in other half i.e

although this mapping may
  be indirect and may use a lightweight process (LWP)

What does it really mean ???

Please help me out !

答:
These days the term Light Weight Processes and threads are used interchangeably.

although this mapping may be indirect and may use a lightweight
  process (LWP)

I know the above statement is confusing(Notice the 2 mays). I can think only 1 thing which the above statement signifies is that:

Earlier when linux supported only user-level threads, the kernel was unaware of the fact that there are multiple user-level threads, and the way it handled these multiple threads was by associating all of them to a light weight process(which kernel sees as a single scheduling and execution unit) at kernel level.

So associating a kernel-level thread with each user-level thread is kind of direct mapping and associating a single light weight process with each user-level thread is indirect mapping.


问:
What does size of the GRU or LSTM cell in the TensorFlow seq2seq tutorial represent?
I'm working with the seq2seq model in the TensorFlow tutorials, and I'm having trouble understanding some of the details. One thing that is confusing to me is what the "size" of a cell represents. I think I have a high level understanding of images like

I believe this is showing that the output from the last step in the encoder is the input to the first step in the encoder. In this case each box is the GRU or LSTM cell at a different time-step in the sequence.

I also think I understand, at a superficial level, diagrams like this:
 from colah's blog post about LSTM and GRU cells. My understanding is that a "cell" is a neural network that feeds the output from one step back into itself along with the new input for the subsequent step. The gates control how much it "remembers" and "forgets."

I think I am getting confused at the level between this superficial, high level understanding and the low-level details. It sounds like the "size" of a cell is the number of nodes in the sigmoid and tanh boxes. Is that correct? If so, how does that relate to the input size for the seq2seq model? For example, the default vocabulary size is 40,000, and the default cell size is 1024. How does the 40,000 element one-hot vocabulary vector for each step of the sequence get matched to the 1024 node internal cell size? Is that what the embedding wrapper does?

Most importantly, what effect would increasing or decreasing the size of the cell have? Would a larger cell be better at learning embeddings? Or at predicting outputs? Both?

答:
It sounds like the "size" of a cell is the number of nodes in the
  sigmoid and tanh boxes. Is that correct?

The size of the cell is the size of the RNN state vector h. In the case of LSTM it's also the size of c. It's not "the number of nodes" (I'm not sure what you mean by nodes).

If so, how does that relate to the input size for the seq2seq model?
  For example, the default vocabulary size is 40,000, and the default
  cell size is 1024. How does the 40,000 element one-hot vocabulary
  vector for each step of the sequence get matched to the 1024 node
  internal cell size?

The input size for the model is independent of the state size. The two vectors (input and state) are concatenated and multiplied by a matrix of shape [state_size + input_size, state_size] to get the next state (simplified version).

Is that what the embedding wrapper does?

No, the embedding is the result of multiplying the 1-hot input vector with a matrix of size [vocab_size, input_size], before doing the multiplication.


问:
AngularJS 1 ui-router ignore the url changes triggered by hash
I am extending an angularjs 1.5 project that uses the ui-router.

I need to store an array of parameters in the URL, and the parameters are changed constantly by the interface.

The app is set into html5Mode but each change of the hash triggers the app to try and find a route resulting in an unstable error being thrown.

```<code>app.config(['$locationProvider', '$stateProvider', '$urlRouterProvider',
    function($locationProvider, $stateProvider, $urlRouterProvider){

    $locationProvider.html5Mode(true);

    $urlRouterProvider.otherwise('/app/dashboard');

    $stateProvider.
        // Main Layout Structure
        state('app', {
            abstract: true,
            url: '/app',
            templateUrl: 'layout/app-body'
        }).
        // Dashboard
        state('app.dashboard', {
            url: '/dashboard',
            templateUrl: 'page/dashboard',
            controller: 'dashboardController'
        })..... etc etc
</code>```

Is it possible to tell angular, or the ui-router to not act when a change is heard in the hash?

The controller that updates the hash just calls a simple replace state:

```<code>window.history.replaceState( '','', window.location.pathname + '#!test=true' );
</code>```

答:
If you need set anchor link, for example app/dashboard#value - you can use $location.hash

$location.hash('value');

or for search parameters you can set optional parameters ? -  app/dashboard?test=value

```<code>         state('app.dashboard', {
            url: '/dashboard',
            templateUrl: 'page/dashboard',
            controller: 'dashboardController',
            reloadOnSearch: false // do not reload on search param
        })
</code>```

use $location.search

```<code>$location.search('test','value');
</code>```

Body:
I am extending an angularjs 1.5 project that uses the ui-router.

I need to store an array of parameters in the URL, and the parameters are changed constantly by the interface.

The app is set into html5Mode but each change of the hash triggers the app to try and find a route resulting in an unstable error being thrown.

app.config(['$locationProvider', '$stateProvider', '$urlRouterProvider',
    function($locationProvider, $stateProvider, $urlRouterProvider){

    $locationProvider.html5Mode(true);

    $urlRouterProvider.otherwise('/app/dashboard');

    $stateProvider.
        // Main Layout Structure
        state('app', {
            abstract: true,
            url: '/app',
            templateUrl: 'layout/app-body'
        }).
        // Dashboard
        state('app.dashboard', {
            url: '/dashboard',
            templateUrl: 'page/dashboard',
            controller: 'dashboardController'
        })..... etc etc

Is it possible to tell angular, or the ui-router to not act when a change is heard in the hash?

The controller that updates the hash just calls a simple replace state:

window.history.replaceState( '','', window.location.pathname + '#!test=true' );

Body:
If you need set anchor link, for example app/dashboard#value - you can use $location.hash

$location.hash('value');

or for search parameters you can set optional parameters ? -  app/dashboard?test=value

         state('app.dashboard', {
            url: '/dashboard',
            templateUrl: 'page/dashboard',
            controller: 'dashboardController',
            reloadOnSearch: false // do not reload on search param
        })

use $location.search

$location.search('test','value');


问:
Can i make graphs in php using SVG? without any 3rd party library or packages?
I had done a API which would take inputs from the users and produce necessary analysis in mathematical way.But i would like to visualize the analysis in graphical form.Can i make graphs in php using SVG? without any 3rd party library or packages?If possible how to make it? I am working on PHP which would take inputs from user and generate the graphs .I had seen many people suggesting to use packages or libraries.I would like to do it by my own .Is it possible? If yes how to start?.</p>

答:
You could do it. SVG is a markup language like HTML, so at the most basic level it's just writing a string to a file.  Try opening up an SVG file in a text editor, it can be quite readable if it's just simple shapes.

However, you'll have to learn SVG markup to determine what to put in that file, which would be the bulk of the work. You can find the standard for SVG at https://www.w3.org/TR/SVG/.


问:
jQuery reset star-rating.js
I am using this plugin https://danielupshaw.com/jquery-star-rating/

I want to reset my form. But how can I reset these stars??

```<code> $("#btn-reset").on('click', function() {
  //some other inputs reset
  $('#starrating').star_rating.remove();
  $('#starrating').star_rating.reload();
 }
</code>```

Please help on how to reset these stars to zero or null.

Here is the full code.

```<code> $("#btn-reset").on('click', function() {
   $('#starrating').star_rating.reload();
});
  jQuery(function($) {
    $('#starrating').star_rating({
        click: function(clicked_rating, event) {
            event.preventDefault();
            $('input[name=\'rating\']').val(clicked_rating);
            this.rating(clicked_rating);
        }
    });
});
</code>```

答:
It looks like all you need to do is set the content to 0. Then re initialize the method.</p>

```<code>$("#starrating").html("0");
$("#starrating").star_rating();
</code>```

Title: jQuery reset star-rating.js

Body:
I am using this plugin https://danielupshaw.com/jquery-star-rating/

I want to reset my form. But how can I reset these stars??

 $("#btn-reset").on('click', function() {
  //some other inputs reset
  $('#starrating').star_rating.remove();
  $('#starrating').star_rating.reload();
 }

Please help on how to reset these stars to zero or null.

Here is the full code.

 $("#btn-reset").on('click', function() {
   $('#starrating').star_rating.reload();
});
  jQuery(function($) {
    $('#starrating').star_rating({
        click: function(clicked_rating, event) {
            event.preventDefault();
            $('input[name=\'rating\']').val(clicked_rating);
            this.rating(clicked_rating);
        }
    });
});

Body:
It looks like all you need to do is set the content to 0. Then re initialize the method.

$("#starrating").html("0");
$("#starrating").star_rating();


问:
How to get a keyboard code for an Android project?
i'm trying to check a condition which says:

```<code>  keyCode = event.getKeyCode();
  Log.e("key",keyCode+"");
    if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN)
    //logic
</code>```

On the log window, the 'keyCode' arent getting any keyboard code, except the value from KEYCODE_DEL which is 67 but doing this ONLY if the EditText is empty!

```<code>    editTextPrincipal.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            keyCode = event.getKeyCode();
            Log.e("key",keyCode+"");
            if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN){
                usuarioDeletouCaracter = true;
                return usuarioDeletouCaracter;
            }
            return usuarioDeletouCaracter;

        }
    });

    editTextPrincipal.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!usuarioDeletouCaracter){
                editTextPrincipal.addTextChangedListener(textWatcher);
            }else{
                Toast.makeText(getApplicationContext(), "O usuario apagou", Toast.LENGTH_SHORT).show();
            }
        }
    });
</code>```

wherever a key is pressed on the keybaord, the keycode on the log window, should returns her value but this is not happen =\

答:
Try This

```<code>editTextPrincipal.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKeyDown(View v, int keyCode, KeyEvent event) {
Log.e("key",keyCode);
if (keyCode == KeyEvent.KEYCODE_DEL){
                usuarioDeletouCaracter = true;
                return usuarioDeletouCaracter;
            }
     return usuarioDeletouCaracter;
}
});
</code>```

reference https://developer.android.com/training/keyboard-input/commands.html

Body:
i'm trying to check a condition which says:

  keyCode = event.getKeyCode();
  Log.e("key",keyCode+"");
    if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN)
    //logic

On the log window, the 'keyCode' arent getting any keyboard code, except the value from KEYCODE_DEL which is 67 but doing this ONLY if the EditText is empty!

    editTextPrincipal.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            keyCode = event.getKeyCode();
            Log.e("key",keyCode+"");
            if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN){
                usuarioDeletouCaracter = true;
                return usuarioDeletouCaracter;
            }
            return usuarioDeletouCaracter;

        }
    });

    editTextPrincipal.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!usuarioDeletouCaracter){
                editTextPrincipal.addTextChangedListener(textWatcher);
            }else{
                Toast.makeText(getApplicationContext(), "O usuario apagou", Toast.LENGTH_SHORT).show();
            }
        }
    });

wherever a key is pressed on the keybaord, the keycode on the log window, should returns her value but this is not happen =\

Body:
Try This

editTextPrincipal.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKeyDown(View v, int keyCode, KeyEvent event) {
Log.e("key",keyCode);
if (keyCode == KeyEvent.KEYCODE_DEL){
                usuarioDeletouCaracter = true;
                return usuarioDeletouCaracter;
            }
     return usuarioDeletouCaracter;
}
});

reference https://developer.android.com/training/keyboard-input/commands.html


问:
Change runtime research for a compile time one
I'm trying to implement a generic ECS library in C++ for learning purpose. I was thinking about a lot of way to implement things but I always run into a problem. So if you could help me with this one :

Let say I have a constexpr hana::tuple of hana::type_c Components, something like :

```<code>struct C1 {};
struct C2 {};
struct C3 {};

constexpr auto components = hana::to_tuple(hana::tuple_t<C1, C2, C3>);
</code>```

And now I have a component storage type, which is not a problem here, so let's call it Storage (the type differ for each component):

```<code>struct Storage {};
</code>```

I want to link each component or each component group, with their Storage type. So the easy way is to do something like that:

```<code>constexpr auto component_storage = hana::make_tuple(
hana::make_pair(hana::to_tuple(hana::tuple_t<C1, C2>), type_c<Storage>),
hana::make_pair(hana::to_tuple(hana::tuple_t<C3>), type_c<Storage>)
);
</code>```

But the problem now is runtime. If I initialize that tuple but with the real Storage and no longer type_c<Storage>, I'll have to loop through the tuple to find the Storage that I need. All of this at runtime no?
And this is really bad, my last version had something like Component::getStorage() and it was free (but more restrictive).

So the question is : how can I manage to have some getStorage<Component>() function which will cost nothing at runtime? Well by nothing I mean just return the reference of the Storage.

EDIT: The only way I have think so far is quite simple (sounds like a good point).

Pseudo-Code

```<code>struct LinkedStorage {

  hana::tuple<...>            storages;
  hana::tuple<hana::pair...>  index;
};
</code>```

At lest something like:

```<code>constexpr auto components = hana::to_tuple(hana::tuple_t<C1, C2, C3>);
constexpr auto storage = hana::to_tuple(hana::tuple_t<Storage, Storage>);
constexpr auto index = hana::make_tuple(
hana::make_pair(hana::to_tuple(hana::tuple_t<C1>, 0),
hana::make_pair(hana::to_tuple(hana::tuple_t<C2, C3>, 1)
);
</code>```

Like that I should be able to found the index at compile time and just access the right element at runtime. But I'm new at metaprogramming, so I guess someone could make something far better.

答:
It looks like you are trying to make a map that can look up a single instance using different keys. Here is a snippet from an old implementation that I wrote. I modified it a bit, but it should convey the idea.

```<code>namespace detail {
    // extractKeys - returns pairs of each element and itself
    struct extract_keys_fn
    {
        template<typename TypesType>
        constexpr auto operator()(TypesType s) const {
            return decltype(hana::unpack(typename TypesType::type{},
                hana::make_tuple
                ^hana::on^
                hana::reverse_partial(hana::make_pair, s)
            )){};
        }
    };
    constexpr extract_keys_fn extract_keys{};
}//detail

template<typename ...Pair>
struct multi_map
{
    // the keys must be `type<tuple<path...>>`
    using Storage = decltype(hana::make_map(std::declval<Pair>()...));

    // each key is a hana::tuple which contain the keys we
    // want to use to lookup an element
    using Lookup = decltype(hana::unpack(
        hana::flatten(hana::unpack(hana::keys(std::declval<Storage>()),
            hana::make_tuple ^hana::on^ detail::extract_keys)),
        hana::make_map
    ));

    constexpr multi_map()
        : storage()
    { }

    constexpr multi_map(Pair&&... p)
        : storage(hana::make_map(std::forward<Pair>(p)...))
    { }

    constexpr multi_map(Pair const&... p)
        : storage(hana::make_map(p...))
    { }

    constexpr multi_map(Pair&... p)
        : storage(hana::make_map(p...))
    { }

    template<typename T>
    constexpr decltype(auto) operator[](T t) const&
    {
        return hana::at_key(storage, hana::at_key(Lookup{}, t));
    }

    template<typename T>
    constexpr decltype(auto) operator[](T t) &
    {
        return hana::at_key(storage, hana::at_key(Lookup{}, t));
    }

    template<typename T>
    constexpr decltype(auto) operator[](T t) &&
    {
        return hana::at_key(storage, hana::at_key(Lookup{}, t));
    }

    Storage storage;
};
</code>```

The basics of what is happening above is that storage is a hana::map containing the instances that you need references to. Then Lookup is a hana::map that points each key to the key that is used in storage (which is a tuple of all the keys that point to it). It's basically just a map to map, but with it you can get a reference to a single instance using any one of the keys.

Body:
I'm trying to implement a generic ECS library in C++ for learning purpose. I was thinking about a lot of way to implement things but I always run into a problem. So if you could help me with this one :

Let say I have a constexpr hana::tuple of hana::type_c Components, something like :

struct C1 {};
struct C2 {};
struct C3 {};

constexpr auto components = hana::to_tuple(hana::tuple_t<C1, C2, C3>);

And now I have a component storage type, which is not a problem here, so let's call it Storage (the type differ for each component):

struct Storage {};

I want to link each component or each component group, with their Storage type. So the easy way is to do something like that:

constexpr auto component_storage = hana::make_tuple(
hana::make_pair(hana::to_tuple(hana::tuple_t<C1, C2>), type_c<Storage>),
hana::make_pair(hana::to_tuple(hana::tuple_t<C3>), type_c<Storage>)
);

But the problem now is runtime. If I initialize that tuple but with the real Storage and no longer type_c<Storage>, I'll have to loop through the tuple to find the Storage that I need. All of this at runtime no?
And this is really bad, my last version had something like Component::getStorage() and it was free (but more restrictive).

So the question is : how can I manage to have some getStorage<Component>() function which will cost nothing at runtime? Well by nothing I mean just return the reference of the Storage.

EDIT: The only way I have think so far is quite simple (sounds like a good point).

Pseudo-Code

struct LinkedStorage {

  hana::tuple<...>            storages;
  hana::tuple<hana::pair...>  index;
};

At lest something like:

constexpr auto components = hana::to_tuple(hana::tuple_t<C1, C2, C3>);
constexpr auto storage = hana::to_tuple(hana::tuple_t<Storage, Storage>);
constexpr auto index = hana::make_tuple(
hana::make_pair(hana::to_tuple(hana::tuple_t<C1>, 0),
hana::make_pair(hana::to_tuple(hana::tuple_t<C2, C3>, 1)
);

Like that I should be able to found the index at compile time and just access the right element at runtime. But I'm new at metaprogramming, so I guess someone could make something far better.

Body:
It looks like you are trying to make a map that can look up a single instance using different keys. Here is a snippet from an old implementation that I wrote. I modified it a bit, but it should convey the idea.

namespace detail {
    // extractKeys - returns pairs of each element and itself
    struct extract_keys_fn
    {
        template<typename TypesType>
        constexpr auto operator()(TypesType s) const {
            return decltype(hana::unpack(typename TypesType::type{},
                hana::make_tuple
                ^hana::on^
                hana::reverse_partial(hana::make_pair, s)
            )){};
        }
    };
    constexpr extract_keys_fn extract_keys{};
}//detail

template<typename ...Pair>
struct multi_map
{
    // the keys must be `type<tuple<path...>>`
    using Storage = decltype(hana::make_map(std::declval<Pair>()...));

    // each key is a hana::tuple which contain the keys we
    // want to use to lookup an element
    using Lookup = decltype(hana::unpack(
        hana::flatten(hana::unpack(hana::keys(std::declval<Storage>()),
            hana::make_tuple ^hana::on^ detail::extract_keys)),
        hana::make_map
    ));

    constexpr multi_map()
        : storage()
    { }

    constexpr multi_map(Pair&&... p)
        : storage(hana::make_map(std::forward<Pair>(p)...))
    { }

    constexpr multi_map(Pair const&... p)
        : storage(hana::make_map(p...))
    { }

    constexpr multi_map(Pair&... p)
        : storage(hana::make_map(p...))
    { }

    template<typename T>
    constexpr decltype(auto) operator[](T t) const&
    {
        return hana::at_key(storage, hana::at_key(Lookup{}, t));
    }

    template<typename T>
    constexpr decltype(auto) operator[](T t) &
    {
        return hana::at_key(storage, hana::at_key(Lookup{}, t));
    }

    template<typename T>
    constexpr decltype(auto) operator[](T t) &&
    {
        return hana::at_key(storage, hana::at_key(Lookup{}, t));
    }

    Storage storage;
};

The basics of what is happening above is that storage is a hana::map containing the instances that you need references to. Then Lookup is a hana::map that points each key to the key that is used in storage (which is a tuple of all the keys that point to it). It's basically just a map to map, but with it you can get a reference to a single instance using any one of the keys.


问:
How to auto-generate externs for the Google Closure Compiler
Suppose you are working in a javascript project with several external library dependencies, and want to compile your sources using the Google Closure Compiler in ADVANCED_OPTIMIZATIONS mode.

Since in this mode the compiler will rename your code calls to the external libraries objects and functions, you must provide externs, to prevent this renaming from happening.

But, it is a lot of work to produce the externs by hand, so, what is the best way to auto-generate the appropriate extern from a given javascript lib?

答:
See the following URL as a starting point. I would also recommend adding type information to your externs to maximize compiler benefit.

http://www.dotnetwise.com/Code/Externs/

ContentLicense: CC BY-SA 2.5


问:
How To Shrink My Loading Screen (CSS, HTML)
So, I found this loading screen on the internet and I made a bunch of tweaks to it but I am not sure how to shrink it. Here is my code:

CSS

```<code>body {
background-color: #90EE90;
}

#loading-wrapper {
position: fixed;
width: 100%;
height: 100%;
left: 0;
top: 0;
}

#loading-text {
display: block;
position: absolute;
top: 100%;
left: 100%;
color: #999;
width: 100px;
height: 30px;
margin: -7px 0 0 -45px;
text-align: center;
font-family: 'PT Sans Narrow', sans-serif;
font-size: 20px;
}

#loading-content {
display: block;
position: relative;
left: 50%;
top: 50%;
width: 170px;
height: 170px;
margin: -85px 0 0 -85px;
border: 3px solid #F00;
}

#loading-content:after {
content: "";
position: absolute;
border: 3px solid #0F0;
left: 15px;
right: 15px;
top: 15px;
bottom: 15px;
}

#loading-content:before {
content: "";
position: absolute;
border: 3px solid #00F;
left: 5px;
right: 5px;
top: 5px;
bottom: 5px;
}

#loading-content {
border: 3px solid transparent;
border-top-color: #20B2AA;
border-bottom-color: #20B2AA;
border-radius: 50%;
-webkit-animation: loader 3.5s linear infinite;
-moz-animation: loader 3.5s linear infinite;
-o-animation: loader 3.5s linear infinite;
animation: loader 3.5s linear infinite;
}
#loading-content:before {
border: 3px solid transparent;
border-top-color: #778899;
border-bottom-color: #778899;
border-radius: 50%;
-webkit-animation: loader 2.5s linear infinite;
-moz-animation: loader 2.5s linear infinite;
-o-animation: loader 2.5s linear infinite;
animation: loader 3s linear infinite;
}

#loading-content:after {
border: 3px solid transparent;
border-top-color: #84417C;
border-bottom-color: #84417C;
border-radius: 50%;
-webkit-animation: loader 1s linear infinite;
animation: loader 1s linear infinite;
-moz-animation: loader 1.5s linear infinite;
-o-animation: loader 1.5s linear infinite;
}

@-webkit-keyframes loaders {
0% {
-webkit-transform: rotate(0deg);
-ms-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(360deg);
-ms-transform: rotate(360deg);
transform: rotate(360deg);
}
}

@keyframes loader {
0% {
-webkit-transform: rotate(0deg);
-ms-transform: rotate(0deg);
Transform: rotate (0deg);
}
100% {
-webkit-transform: rotate(360deg);
-ms-transform: rotate(360deg);
transform: rotate(360deg);
}
}

#content-wrapper {
color: #FFF;
position: fixed;
left: 0;
top: 20px;
width: 100%;
height: 100%;
}

#header
{
width: 800px;
margin: 0 auto;
text-align: center;
height: 100px;
background-color: #666;
}

#content
{
width: 800px;
height: 1000px;
margin: 0 auto;
text-align: center;
background-color: #888;
}
</code>```

HTML

```<code><div id="loading-wrapper">
<div id="loading-text">LOADING</div>
<div id="loading-content"></div>
</div>
</code>```

So, I am trying to get my loading screen to be smaller so it doesn't take up so much of the page please. Thanks in advance!

答:
Change the width, height, and margin inside #loading-content proportionally:

```<code>#loading-content {
  width: 100px;
  height: 100px;
  margin: -50px 0 0 -50px;
}
</code>```

Demo Snippet:

body {
background-color: #90EE90;
}

#loading-wrapper {
position: fixed;
width: 100%;
height: 100%;
left: 0;
top: 0;
}

#loading-text {
display: block;
position: absolute;
top: 100%;
left: 100%;
color: #999;
width: 100px;
height: 30px;
margin: -7px 0 0 -45px;
text-align: center;
font-family: 'PT Sans Narrow', sans-serif;
font-size: 20px;
}

#loading-content {
display: block;
position: relative;
left: 50%;
top: 50%;
width: 100px;
height: 100px;
margin: -50px 0 0 -50px;
border: 3px solid #F00;
}

#loading-content:after {
content: "";
position: absolute;
border: 3px solid #0F0;
left: 15px;
right: 15px;
top: 15px;
bottom: 15px;
}

#loading-content:before {
content: "";
position: absolute;
border: 3px solid #00F;
left: 5px;
right: 5px;
top: 5px;
bottom: 5px;
}

#loading-content {
border: 3px solid transparent;
border-top-color: #20B2AA;
border-bottom-color: #20B2AA;
border-radius: 50%;
-webkit-animation: loader 3.5s linear infinite;
-moz-animation: loader 3.5s linear infinite;
-o-animation: loader 3.5s linear infinite;
animation: loader 3.5s linear infinite;
}
#loading-content:before {
border: 3px solid transparent;
border-top-color: #778899;
border-bottom-color: #778899;
border-radius: 50%;
-webkit-animation: loader 2.5s linear infinite;
-moz-animation: loader 2.5s linear infinite;
-o-animation: loader 2.5s linear infinite;
animation: loader 3s linear infinite;
}

#loading-content:after {
border: 3px solid transparent;
border-top-color: #84417C;
border-bottom-color: #84417C;
border-radius: 50%;
-webkit-animation: loader 1s linear infinite;
animation: loader 1s linear infinite;
-moz-animation: loader 1.5s linear infinite;
-o-animation: loader 1.5s linear infinite;
}

@-webkit-keyframes loaders {
0% {
-webkit-transform: rotate(0deg);
-ms-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(360deg);
-ms-transform: rotate(360deg);
transform: rotate(360deg);
}
}

@keyframes loader {
0% {
-webkit-transform: rotate(0deg);
-ms-transform: rotate(0deg);
Transform: rotate (0deg);
}
100% {
-webkit-transform: rotate(360deg);
-ms-transform: rotate(360deg);
transform: rotate(360deg);
}
}

#content-wrapper {
color: #FFF;
position: fixed;
left: 0;
top: 20px;
width: 100%;
height: 100%;
}

#header
{
width: 800px;
margin: 0 auto;
text-align: center;
height: 100px;
background-color: #666;
}

#content
{
width: 800px;
height: 1000px;
margin: 0 auto;
text-align: center;
background-color: #888;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="loading-wrapper">
<div id="loading-text">LOADING</div>
<div id="loading-content"></div>
</div></code>```

Body:
So, I found this loading screen on the internet and I made a bunch of tweaks to it but I am not sure how to shrink it. Here is my code:

CSS

body {
background-color: #90EE90;
}

#loading-wrapper {
position: fixed;
width: 100%;
height: 100%;
left: 0;
top: 0;
}

#loading-text {
display: block;
position: absolute;
top: 100%;
left: 100%;
color: #999;
width: 100px;
height: 30px;
margin: -7px 0 0 -45px;
text-align: center;
font-family: 'PT Sans Narrow', sans-serif;
font-size: 20px;
}

#loading-content {
display: block;
position: relative;
left: 50%;
top: 50%;
width: 170px;
height: 170px;
margin: -85px 0 0 -85px;
border: 3px solid #F00;
}

#loading-content:after {
content: "";
position: absolute;
border: 3px solid #0F0;
left: 15px;
right: 15px;
top: 15px;
bottom: 15px;
}

#loading-content:before {
content: "";
position: absolute;
border: 3px solid #00F;
left: 5px;
right: 5px;
top: 5px;
bottom: 5px;
}

#loading-content {
border: 3px solid transparent;
border-top-color: #20B2AA;
border-bottom-color: #20B2AA;
border-radius: 50%;
-webkit-animation: loader 3.5s linear infinite;
-moz-animation: loader 3.5s linear infinite;
-o-animation: loader 3.5s linear infinite;
animation: loader 3.5s linear infinite;
}
#loading-content:before {
border: 3px solid transparent;
border-top-color: #778899;
border-bottom-color: #778899;
border-radius: 50%;
-webkit-animation: loader 2.5s linear infinite;
-moz-animation: loader 2.5s linear infinite;
-o-animation: loader 2.5s linear infinite;
animation: loader 3s linear infinite;
}

#loading-content:after {
border: 3px solid transparent;
border-top-color: #84417C;
border-bottom-color: #84417C;
border-radius: 50%;
-webkit-animation: loader 1s linear infinite;
animation: loader 1s linear infinite;
-moz-animation: loader 1.5s linear infinite;
-o-animation: loader 1.5s linear infinite;
}

@-webkit-keyframes loaders {
0% {
-webkit-transform: rotate(0deg);
-ms-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(360deg);
-ms-transform: rotate(360deg);
transform: rotate(360deg);
}
}

@keyframes loader {
0% {
-webkit-transform: rotate(0deg);
-ms-transform: rotate(0deg);
Transform: rotate (0deg);
}
100% {
-webkit-transform: rotate(360deg);
-ms-transform: rotate(360deg);
transform: rotate(360deg);
}
}

#content-wrapper {
color: #FFF;
position: fixed;
left: 0;
top: 20px;
width: 100%;
height: 100%;
}

#header
{
width: 800px;
margin: 0 auto;
text-align: center;
height: 100px;
background-color: #666;
}

#content
{
width: 800px;
height: 1000px;
margin: 0 auto;
text-align: center;
background-color: #888;
}

HTML

LOADING

So, I am trying to get my loading screen to be smaller so it doesn't take up so much of the page please. Thanks in advance!

Body:
Change the width, height, and margin inside #loading-content proportionally:

#loading-content {
  width: 100px;
  height: 100px;
  margin: -50px 0 0 -50px;
}

Demo Snippet:

body {
background-color: #90EE90;
}

#loading-wrapper {
position: fixed;
width: 100%;
height: 100%;
left: 0;
top: 0;
}

#loading-text {
display: block;
position: absolute;
top: 100%;
left: 100%;
color: #999;
width: 100px;
height: 30px;
margin: -7px 0 0 -45px;
text-align: center;
font-family: 'PT Sans Narrow', sans-serif;
font-size: 20px;
}

#loading-content {
display: block;
position: relative;
left: 50%;
top: 50%;
width: 100px;
height: 100px;
margin: -50px 0 0 -50px;
border: 3px solid #F00;
}

#loading-content:after {
content: "";
position: absolute;
border: 3px solid #0F0;
left: 15px;
right: 15px;
top: 15px;
bottom: 15px;
}

#loading-content:before {
content: "";
position: absolute;
border: 3px solid #00F;
left: 5px;
right: 5px;
top: 5px;
bottom: 5px;
}

#loading-content {
border: 3px solid transparent;
border-top-color: #20B2AA;
border-bottom-color: #20B2AA;
border-radius: 50%;
-webkit-animation: loader 3.5s linear infinite;
-moz-animation: loader 3.5s linear infinite;
-o-animation: loader 3.5s linear infinite;
animation: loader 3.5s linear infinite;
}
#loading-content:before {
border: 3px solid transparent;
border-top-color: #778899;
border-bottom-color: #778899;
border-radius: 50%;
-webkit-animation: loader 2.5s linear infinite;
-moz-animation: loader 2.5s linear infinite;
-o-animation: loader 2.5s linear infinite;
animation: loader 3s linear infinite;
}

#loading-content:after {
border: 3px solid transparent;
border-top-color: #84417C;
border-bottom-color: #84417C;
border-radius: 50%;
-webkit-animation: loader 1s linear infinite;
animation: loader 1s linear infinite;
-moz-animation: loader 1.5s linear infinite;
-o-animation: loader 1.5s linear infinite;
}

@-webkit-keyframes loaders {
0% {
-webkit-transform: rotate(0deg);
-ms-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(360deg);
-ms-transform: rotate(360deg);
transform: rotate(360deg);
}
}

@keyframes loader {
0% {
-webkit-transform: rotate(0deg);
-ms-transform: rotate(0deg);
Transform: rotate (0deg);
}
100% {
-webkit-transform: rotate(360deg);
-ms-transform: rotate(360deg);
transform: rotate(360deg);
}
}

#content-wrapper {
color: #FFF;
position: fixed;
left: 0;
top: 20px;
width: 100%;
height: 100%;
}

#header
{
width: 800px;
margin: 0 auto;
text-align: center;
height: 100px;
background-color: #666;
}

#content
{
width: 800px;
height: 1000px;
margin: 0 auto;
text-align: center;
background-color: #888;
}

<div id="loading-wrapper">
<div id="loading-text">LOADING</div>
<div id="loading-content"></div>
</div>


问:
How do I reset axis 1 in pandas?
I want to reset my column headers in pandas.  I want my column names to be my top row and then my column headers to be reset to 0,1,2,3 in pandas dataframe.  How do i perform this operation?</p>

答:
one-liner</p>

```<code>df.T.reset_index().T
</code>```

Title: How do I reset axis 1 in pandas?

Body:
one-liner

df.T.reset_index().T


问:
Azure Service Bus Continuous WebJob pause
Is there a way to pause a continuous webjob - to stop receive messages from the service bus for time interval?
I have a system that is receiving post data constantly. Then the posted data is send to the Service Bus. I am wondering if there is a way to stop processing the messages. Of course the other solution would be not to send those messages - keep them in a queue in the sender system.</p>

答:
You already have the queuing mechanism... the Service Bus. It sounds like you are declaratively connecting to the queue by using the ServiceBusTrigger attribute. i.e.

```<code>public static void ProcessQueueMessage([QueueTrigger("queue")] string message, TextWriter log)
</code>```

But this isn't the only way to receive a message in a continuous webjob. You can use a QueueClient object to receive these messages just as easily:

```<code>var connectionString = "//connection string here//";
var queueName = "samplequeue";

var client = QueueClient.CreateFromConnectionString(cnStr, queueName);

client.OnMessage(message =>
{
   string msg = message.GetBody<string>();
   // Process message here...
});

Console.ReadLine();
</code>```

(See https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dotnet-get-started-with-queues for more information.)

So in your webjob, you can listen to two busses: the first is the operational bus you are already using to process your business messages. The new topic is a control bus. It's always listening, but you only send it a message when you wish to change the behavior of the operational queue.

So you send "START" to the control bus. Receipt of that message would invoke the code above and cause the operational bus to start processing messages.

If you want to stop processing, send "STOP" to the control bus. When this message is received, call client.Close(); on the operational bus. This pauses processing of the messages until the next "START" message is received.

Of course, you can expand on this. You could, for instance send "PAUSE 10 MINUTES" to the control bus, which could stop the operational bus, and then set a timer to restart it 10 minutes later. You're limited only by your imagination!

Personally, I would likely use Json messages rather than plain text, but whatever fits your needs.

Body:
You already have the queuing mechanism... the Service Bus. It sounds like you are declaratively connecting to the queue by using the ServiceBusTrigger attribute. i.e.

public static void ProcessQueueMessage([QueueTrigger("queue")] string message, TextWriter log)

But this isn't the only way to receive a message in a continuous webjob. You can use a QueueClient object to receive these messages just as easily:

var connectionString = "//connection string here//";
var queueName = "samplequeue";

var client = QueueClient.CreateFromConnectionString(cnStr, queueName);

client.OnMessage(message =>
{
   string msg = message.GetBody<string>();
   // Process message here...
});

Console.ReadLine();

(See https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dotnet-get-started-with-queues for more information.)

So in your webjob, you can listen to two busses: the first is the operational bus you are already using to process your business messages. The new topic is a control bus. It's always listening, but you only send it a message when you wish to change the behavior of the operational queue.

So you send "START" to the control bus. Receipt of that message would invoke the code above and cause the operational bus to start processing messages.

If you want to stop processing, send "STOP" to the control bus. When this message is received, call client.Close(); on the operational bus. This pauses processing of the messages until the next "START" message is received.

Of course, you can expand on this. You could, for instance send "PAUSE 10 MINUTES" to the control bus, which could stop the operational bus, and then set a timer to restart it 10 minutes later. You're limited only by your imagination!

Personally, I would likely use Json messages rather than plain text, but whatever fits your needs.


问:
Render Component in iframe using vuejs without src attribute
```<code><iframe id="frame" width="100%" height="100%">

</ifrme>
</code>```

I want to render component in this iframe. Is there any option of creating html element or rendering component in iframe?

```<code>new Vue({
   el:'#frame',
   store:store,
   router:router,
   render: component
})
</code>```

答:
You can refer below link That helped me a lot.
Here is the link and the code snippets.

Vue.component('i-frame', {
  render(h) {
    return  h('iframe', {
      on: { load: this.renderChildren }
    })
  },
  beforeUpdate() {
    //freezing to prevent unnessessary Reactifiation of vNodes
    this.iApp.children = Object.freeze(this.$slots.default)
  },
  methods: {
    renderChildren() {
      const children = this.$slots.default
      const body = this.$el.contentDocument.body
      const el = document.createElement('DIV') // we will mount or nested app to this element
      body.appendChild(el)

      const iApp = new Vue({
        name: 'iApp',
        //freezing to prevent unnessessary Reactifiation of vNodes
        data: { children: Object.freeze(children) },
        render(h) {
          return h('div', this.children)
        },
      })

      iApp.$mount(el) // mount into iframe

      this.iApp = iApp // cache instance for later updates

    }
  }
})

Vue.component('test-child', {
  template: `

{{ title }}

  <slot/>

`,
  props: ['title'],
  methods: {
    log:  _.debounce(function() {
      console.log('resize!')
    }, 200)
  },
  mounted() {
    this.$nextTick(() => {
      const doc = this.$el.ownerDocument
      const win = doc.defaultView
      win.addEventListener('resize', this.log)
    })
  },
  beforeDestroy() {
    const doc = this.$el.ownerDocument
    const win = doc.defaultView
    win.removeEventListener('resize', this.log)
  }
})

new Vue({
  el: '#app',
  data: {
    dynamicPart: 'InputContent',
    show: false,
  }
})
```

https://jsfiddle.net/Linusborg/ohznser9/

Body:
</ifrme>

I want to render component in this iframe. Is there any option of creating html element or rendering component in iframe?

new Vue({
   el:'#frame',
   store:store,
   router:router,
   render: component
})

Body:
You can refer below link That helped me a lot.
Here is the link and the code snippets.

Vue.component('i-frame', {
  render(h) {
    return  h('iframe', {
      on: { load: this.renderChildren }
    })
  },
  beforeUpdate() {
    //freezing to prevent unnessessary Reactifiation of vNodes
    this.iApp.children = Object.freeze(this.$slots.default)
  },
  methods: {
    renderChildren() {
      const children = this.$slots.default
      const body = this.$el.contentDocument.body
      const el = document.createElement('DIV') // we will mount or nested app to this element
      body.appendChild(el)

      const iApp = new Vue({
        name: 'iApp',
        //freezing to prevent unnessessary Reactifiation of vNodes
        data: { children: Object.freeze(children) },
        render(h) {
          return h('div', this.children)
        },
      })

      iApp.$mount(el) // mount into iframe

      this.iApp = iApp // cache instance for later updates

    }
  }
})

Vue.component('test-child', {
  template: `<div>
  <h3>{{ title }}</h3>
  <p>
  <slot/>
  </p>
  </div>`,
  props: ['title'],
  methods: {
    log:  _.debounce(function() {
      console.log('resize!')
    }, 200)
  },
  mounted() {
    this.$nextTick(() => {
      const doc = this.$el.ownerDocument
      const win = doc.defaultView
      win.addEventListener('resize', this.log)
    })
  },
  beforeDestroy() {
    const doc = this.$el.ownerDocument
    const win = doc.defaultView
    win.removeEventListener('resize', this.log)
  }
})

new Vue({
  el: '#app',
  data: {
    dynamicPart: 'InputContent',
    show: false,
  }
})

https://jsfiddle.net/Linusborg/ohznser9/

ContentLicense: CC BY-SA 4.0


问:
Mongoengine check if object exists without fetching the object
On Django we can use the QuerySet.exists() to check if an object exists in the DB in the most efficient way, without actually fetching the record.

Is there an equivalent function on Mongoengine?

答:
According to official documentation, here is solution how to make this if you have object id.Its the best solution for your case, that i have seen in mongoengine documentation.It works as below:

```<code># Returns None or Object if it exists
result = Collection.objects.with_id(object_id=*your object id*)
if result is None:
  # raise error
else:
  # make some actions with this object
</code>```

Is this is what are you looking for?

Body:
According to official documentation, here is solution how to make this if you have object id.Its the best solution for your case, that i have seen in mongoengine documentation.It works as below:

# Returns None or Object if it exists
result = Collection.objects.with_id(object_id=*your object id*)
if result is None:
  # raise error
else:
  # make some actions with this object

Is this is what are you looking for?


问:
Counting in TWIG
I'm using SILEX with twig and I'm trying to achieve an count for an array from db with a specific value
Here is the piece of code to be more specific:

```<code> <p>There are in total {{ items|length }}</p> // returns the GOOD amount of total rows in db
 <p>There are  {{ items.stare=='activ'|length }} requests not answered.</p> // returns nothing
</code>```

How can I achieve what I want?

items is an array with information from a SELECT *

EDIT

I'm sorry , the second returns nothing only when using an for(items as item)
When I use items.stare I get a twig error:

```<code>Key "stare" for array with keys "0, 1, 2, 3, 4" does not exist in "index.twig" at line 78
</code>```

答:
You should probably count them in SQL, with a SELECT COUNT(*) FROM ... WHERE stare == 'active' or something, and pass that into your twig template.

Or, you could filter it in PHP and pass the filtered array to your template:

```<code>$activ_items = array_filter($items, function($item) {
    return $item['stare'] == 'active';
});

<p>There are in total {{ items|length }}</p> // returns the GOOD amount of total rows in db
<p>There are  {{ activ_items|length }} requests not answered.</p> // returns nothing
</code>```

If you really want to do it all in twig, which I don't recommend, you could do:

```<code><p>There are in total {{ items|length }}</p> // returns the GOOD amount of total rows in db
{% set count = 0 %}
{% for item in items %}
    {% if item.stare == "activ" %}
        {% set count = count + 1 %}
    {% endif %}
{% endfor %}
<p>There are  {{ count }} requests not answered.</p> // returns nothing
</code>```

Title: Counting in TWIG

Body:
I'm using SILEX with twig and I'm trying to achieve an count for an array from db with a specific value
Here is the piece of code to be more specific:

There are in total {{ items|length }}
 // returns the GOOD amount of total rows in db

There are  {{ items.stare=='activ'|length }} requests not answered.
 // returns nothing

How can I achieve what I want?

items is an array with information from a SELECT *

EDIT

I'm sorry , the second returns nothing only when using an for(items as item)
When I use items.stare I get a twig error:

Key "stare" for array with keys "0, 1, 2, 3, 4" does not exist in "index.twig" at line 78

Body:
You should probably count them in SQL, with a SELECT COUNT(*) FROM ... WHERE stare == 'active' or something, and pass that into your twig template.

Or, you could filter it in PHP and pass the filtered array to your template:

$activ_items = array_filter($items, function($item) {
    return $item['stare'] == 'active';
});

<p>There are in total {{ items|length }}</p> // returns the GOOD amount of total rows in db
<p>There are  {{ activ_items|length }} requests not answered.</p> // returns nothing

If you really want to do it all in twig, which I don't recommend, you could do:

<p>There are in total {{ items|length }}</p> // returns the GOOD amount of total rows in db
{% set count = 0 %}
{% for item in items %}
    {% if item.stare == "activ" %}
        {% set count = count + 1 %}
    {% endif %}
{% endfor %}
<p>There are  {{ count }} requests not answered.</p> // returns nothing


问:
Error when parsing through items in list and finding product Error: can't multiply sequence by non-int of type 'list'
So I'm trying to make a program to find the thirteen adjacent digits in the 1000-digit number that have the greatest product. This is a problem for the Euler project and i keep running into error message:

```<code>TypeError: can't multiply sequence by non-int of type 'list'
</code>```

here is the code though i shortend the 1000 digit number down for this post:

```<code>import operator
from functools import reduce
allDigits = 73167176531330624919225119674426574742355349194934969835203127745063262395783180169848018694788518438586156078911294949545950173795833195285320880551112540698747158

d = [int(d) for d in str(allDigits)]

digits = d[:13]

products = []

del d[:13]

while len(d) > 0:

    tempProd = 1

    for i in digits:

        tempProd *= i

    products.append(tempProd)

    nextDigit = d[:1]

    del digits[:1]
    digits.append(nextDigit)

    del d[:1]

products.sort()

print(products)
</code>```

I am running into the problem in the line where it says:

```<code>tempProd *= i
</code>```

This is really confusing me as neither of the values should be a list, i have tried using the numpy product function aswell as creating my own function which runs into the same problem and looks like this:

```<code>def prod(x):
    return reduce(operator.mul, int(x), 1)
</code>```

Any help would be much apreciated you can find more information about the problem im trying to solve here:
https://projecteuler.net/problem=8

答:
The problem is these two lines:

```<code>nextDigit = d[:1] # returns a list
digits.append(nextDigit)
</code>```

d[:1] returns a list which is then appended to the digits list so when you read it in the for loop you are multiplying i by a list value.

One way to fix this is to simply just do

```<code>nextDigit = d[:1][0]
</code>```

Body:
So I'm trying to make a program to find the thirteen adjacent digits in the 1000-digit number that have the greatest product. This is a problem for the Euler project and i keep running into error message:

TypeError: can't multiply sequence by non-int of type 'list'

here is the code though i shortend the 1000 digit number down for this post:

import operator
from functools import reduce
allDigits = 73167176531330624919225119674426574742355349194934969835203127745063262395783180169848018694788518438586156078911294949545950173795833195285320880551112540698747158

d = [int(d) for d in str(allDigits)]

digits = d[:13]

products = []

del d[:13]

while len(d) > 0:

    tempProd = 1

    for i in digits:

        tempProd *= i

    products.append(tempProd)

    nextDigit = d[:1]

    del digits[:1]
    digits.append(nextDigit)

    del d[:1]

products.sort()

print(products)

I am running into the problem in the line where it says:

tempProd *= i

This is really confusing me as neither of the values should be a list, i have tried using the numpy product function aswell as creating my own function which runs into the same problem and looks like this:

def prod(x):
    return reduce(operator.mul, int(x), 1)

Any help would be much apreciated you can find more information about the problem im trying to solve here:
https://projecteuler.net/problem=8

Body:
The problem is these two lines:

nextDigit = d[:1] # returns a list
digits.append(nextDigit)

d[:1] returns a list which is then appended to the digits list so when you read it in the for loop you are multiplying i by a list value.

One way to fix this is to simply just do

nextDigit = d[:1][0]


问:
Why does gprof significantly underestimate the program's running time?
I have this program that takes 2.34 seconds to run, and gprof says it only takes 1.18 seconds. I've read answers elsewhere suggesting that gprof can get it wrong if e.g the program is I/O bound, but this program clearly isn't.

This also happens for a useful program I'm trying to profile. It's not specific to this trivial test case.

(Also in this case gprof says that main() takes more than 100% of the program's running time, which is a pretty stupid bug but not really causing problems for me.)

```<code>$ cat test.c
int main() {
    int i;
    for (i=0;i<1000000000;i++);
}

$ gcc test.c -o test

$ time ./test

real    0m2.342s
user    0m2.340s
sys 0m0.000s

$ gcc test.c -o test -pg

$ time ./test

real    0m2.342s
user    0m2.340s
sys 0m0.000s

$ gprof test |head
Flat profile:

Each sample counts as 0.01 seconds.
  %   cumulative   self              self     total
 time   seconds   seconds    calls  Ts/call  Ts/call  name
101.33      1.18     1.18                             main

 %         the percentage of the total running time of the
time       program used by this function.
</code>```

答: I would recommend dropping gprof and switching to oprofile. Any profiling that inserts instrumentation into your program will inherently affect the performance in ways that might skew or invalidate the results. With oprofile you don't have to build your program with profiling support or get special profiling-enabled libraries; it works by statistical methods, basically sampling the instruction pointer (with kernel assistance) and using the sample counts to estimate how much time was spent in each function.

Body:
I have this program that takes 2.34 seconds to run, and gprof says it only takes 1.18 seconds. I've read answers elsewhere suggesting that gprof can get it wrong if e.g the program is I/O bound, but this program clearly isn't.

This also happens for a useful program I'm trying to profile. It's not specific to this trivial test case.

(Also in this case gprof says that main() takes more than 100% of the program's running time, which is a pretty stupid bug but not really causing problems for me.)

$ cat test.c
int main() {
    int i;
    for (i=0;i<1000000000;i++);
}

$ gcc test.c -o test

$ time ./test

real    0m2.342s
user    0m2.340s
sys 0m0.000s

$ gcc test.c -o test -pg

$ time ./test

real    0m2.342s
user    0m2.340s
sys 0m0.000s

$ gprof test |head
Flat profile:

Each sample counts as 0.01 seconds.
  %   cumulative   self              self     total
 time   seconds   seconds    calls  Ts/call  Ts/call  name
101.33      1.18     1.18                             main

 %         the percentage of the total running time of the
time       program used by this function.


问:
How to use AWS Windows ec2 instance in fedora?
I am trying to connect aws Windows ec2 instance from Fedora 25, I connect it on windows machine without any issue as Windows has mstsc by default but this time I used below command on fedora-25 to connect to windows ec2 instance:

```<code>rdesktop -u administrator ec2-35-144-210-177.ap-south1.compute.amazonaws.com
###failed after 2 mins
</code>```

I got below error -  ERROR:
  ec2-35-144-210-177.ap-south-1.compute.amazonaws.com: unable to connect

I am able to connect ec2 windows instance from windows machine using mstsc but not able to connect from fedora as rdesktop is not working as expected. Any Suggestion to resolve this issue?

答:
It was a silly mistake and Below is my finding on this issue, consider this scenario-

```<code>laptop1 - running on Windows10 - connected to network1
laptop2 - running on fedora25  - connected to network2
</code>```

aws Instance was created from windows10 with network1 that is why inbound rules of security group by default create an entry and it will allow network1 to connect to Windows ec2 instant without any issue.

In my Situation -

```<code>From the error - unable to connect, it is difficult to find out the root cause.
</code>```

I created Windows ec2 instance from Windows10 which was running on
  network1 but I was trying to access from fedora25 which is running on
  network2, network1 is different from network2 and if you want to
  connect from a network which is different from the network which you
  used to create Windows ec2 instance then you need to create one more
  entry in the security group for inbound Rules to add the ip address of your current network. And when I deleted the
  old machine and created new machine from fedora25+network2 it worked
  because by default it created one inbound rule in the Security Group
  for network2.

Body:
I am trying to connect aws Windows ec2 instance from Fedora 25, I connect it on windows machine without any issue as Windows has mstsc by default but this time I used below command on fedora-25 to connect to windows ec2 instance:

rdesktop -u administrator ec2-35-144-210-177.ap-south1.compute.amazonaws.com
###failed after 2 mins

I got below error -  ERROR:
  ec2-35-144-210-177.ap-south-1.compute.amazonaws.com: unable to connect

I am able to connect ec2 windows instance from windows machine using mstsc but not able to connect from fedora as rdesktop is not working as expected. Any Suggestion to resolve this issue?

Body:
It was a silly mistake and Below is my finding on this issue, consider this scenario-

laptop1 - running on Windows10 - connected to network1
laptop2 - running on fedora25  - connected to network2

aws Instance was created from windows10 with network1 that is why inbound rules of security group by default create an entry and it will allow network1 to connect to Windows ec2 instant without any issue.

In my Situation -

From the error - unable to connect, it is difficult to find out the root cause.

I created Windows ec2 instance from Windows10 which was running on
  network1 but I was trying to access from fedora25 which is running on
  network2, network1 is different from network2 and if you want to
  connect from a network which is different from the network which you
  used to create Windows ec2 instance then you need to create one more
  entry in the security group for inbound Rules to add the ip address of your current network. And when I deleted the
  old machine and created new machine from fedora25+network2 it worked
  because by default it created one inbound rule in the Security Group
  for network2.


问:
Mule not rolling back JMS message on Openwire connected ActiveMQ queue
We have a scenario where we are using Mule (Version 3.4 - old, I know) to rollback a JMS transaction after a catch exception. ActiveMQ should keep the message on the queue (to make persistent) until the transaction is committed, or redeliver as per the rollback settings after a Mule initiated rollback.

However, it seems like after a rollback, the message is not redelivered and sits on the queue connection "blocking" further messages. It is as if the rollback message is not received. Does anyone have any idea why this would not be returned?

Extract from logs:

```<code>2017-03-29 11:23:26,345 [Session Task-16] DEBUG SingleResourceCollectionTransaction - Rolling back a transaction collection in the following order: [org.mule.transport.jms.JmsTransaction@bea1685a-1469-11e7-9d1d-5ba5419e6645[status=STATUS_MARKED_ROLLBACK, key=ActiveMQConnection {id=ID:serveradd-50176-1490782511241-3:1,clientId=ID:serveradd-50176-1490782511241-2:1,started=false}, resource=org.mule.transport.jms.ReusableTopicSessionWrapper@c2149e58]]
2017-03-29 11:23:26,345 [Session Task-16] DEBUG SingleResourceCollectionTransaction - Rolling back transaction
2017-03-29 11:23:26,345 [Session Task-16] DEBUG g.mule.transport.jms.JmsTransaction - Rolling back transaction
2017-03-29 11:23:26,345 [Session Task-16] DEBUG g.mule.transport.jms.JmsTransaction - Rolling back transaction: bea1685a-1469-11e7-9d1d-5ba5419e6645
2017-03-29 11:23:26,345 [Session Task-16] DEBUG org.apache.activemq.ActiveMQSession - ID:serveradd-50176-1490782511241-3:1:6 Transaction Rollback, txid:TX:ID:serveradd-50176-1490782511241-3:1:21
2017-03-29 11:23:26,345 [Session Task-16] DEBUG .apache.activemq.TransactionContext - Rollback: TX:ID:serveradd-50176-1490782511241-3:1:21 syncCount: 1
2017-03-29 11:23:26,346 [Session Task-16] DEBUG transaction.TransactionCoordination - Unbinding transaction (14) com.mulesoft.mule.transaction.SingleResourceCollectionTransaction@bea11a39-1469-11e7-9d1d-5ba5419e6645[status=STATUS_ROLLEDBACK, key=null, resource=null]
2017-03-29 11:23:26,346 [Session Task-16] DEBUG n.InterceptingChainLifecycleWrapper - Invoking InterceptingChainLifecycleWrapper 'wrapper for null'
[
  org.mule.api.processor.LoggerMessageProcessor@7e9d1d0b
] with event MuleEvent: 0-bea2c7f2-1469-11e7-9d1d-5ba5419e6645, stop processing=false, jms://myQueue
2017-03-29 11:23:26,347 [Session Task-16] DEBUG .chain.DefaultMessageProcessorChain - Invoking DefaultMessageProcessorChain '(inner iterating chain) of null'
[
  org.mule.api.processor.LoggerMessageProcessor@7e9d1d0b
] with event MuleEvent: 0-bea2c7f2-1469-11e7-9d1d-5ba5419e6645, stop processing=false, jms://myQueue
2017-03-29 11:23:26,347 [Session Task-16] INFO  pi.processor.LoggerMessageProcessor - Rolling back...
2017-03-29 11:23:26,347 [Session Task-16] DEBUG .support.DefaultListableBeanFactory - Returning cached instance of singleton bean '_muleStreamCloserService'
2017-03-29 11:23:26,347 [Session Task-16] DEBUG .support.DefaultListableBeanFactory - Returning cached instance of singleton bean '_muleStreamCloserService'
2017-03-29 11:23:26,347 [Session Task-16] DEBUG ule.util.DefaultStreamCloserService - Unable to find an StreamCloser for the stream type: class net.MyBean, the stream: net.MyBean@e341f050 will not be closed.
</code>```

答: I have no working knowledge on Mule, but, since it is JMS/J2EE I would check the redelivery option the mule queue. There is a property on it to make the  N number of attempts before sending the fail message to the dead letter queue(i know activemq has it). </p>

Body:
We have a scenario where we are using Mule (Version 3.4 - old, I know) to rollback a JMS transaction after a catch exception. ActiveMQ should keep the message on the queue (to make persistent) until the transaction is committed, or redeliver as per the rollback settings after a Mule initiated rollback.

However, it seems like after a rollback, the message is not redelivered and sits on the queue connection "blocking" further messages. It is as if the rollback message is not received. Does anyone have any idea why this would not be returned?

Extract from logs:

2017-03-29 11:23:26,345 [Session Task-16] DEBUG SingleResourceCollectionTransaction - Rolling back a transaction collection in the following order: [org.mule.transport.jms.JmsTransaction@bea1685a-1469-11e7-9d1d-5ba5419e6645[status=STATUS_MARKED_ROLLBACK, key=ActiveMQConnection {id=ID:serveradd-50176-1490782511241-3:1,clientId=ID:serveradd-50176-1490782511241-2:1,started=false}, resource=org.mule.transport.jms.ReusableTopicSessionWrapper@c2149e58]]
2017-03-29 11:23:26,345 [Session Task-16] DEBUG SingleResourceCollectionTransaction - Rolling back transaction
2017-03-29 11:23:26,345 [Session Task-16] DEBUG g.mule.transport.jms.JmsTransaction - Rolling back transaction
2017-03-29 11:23:26,345 [Session Task-16] DEBUG g.mule.transport.jms.JmsTransaction - Rolling back transaction: bea1685a-1469-11e7-9d1d-5ba5419e6645
2017-03-29 11:23:26,345 [Session Task-16] DEBUG org.apache.activemq.ActiveMQSession - ID:serveradd-50176-1490782511241-3:1:6 Transaction Rollback, txid:TX:ID:serveradd-50176-1490782511241-3:1:21
2017-03-29 11:23:26,345 [Session Task-16] DEBUG .apache.activemq.TransactionContext - Rollback: TX:ID:serveradd-50176-1490782511241-3:1:21 syncCount: 1
2017-03-29 11:23:26,346 [Session Task-16] DEBUG transaction.TransactionCoordination - Unbinding transaction (14) com.mulesoft.mule.transaction.SingleResourceCollectionTransaction@bea11a39-1469-11e7-9d1d-5ba5419e6645[status=STATUS_ROLLEDBACK, key=null, resource=null]
2017-03-29 11:23:26,346 [Session Task-16] DEBUG n.InterceptingChainLifecycleWrapper - Invoking InterceptingChainLifecycleWrapper 'wrapper for null'
[
  org.mule.api.processor.LoggerMessageProcessor@7e9d1d0b
] with event MuleEvent: 0-bea2c7f2-1469-11e7-9d1d-5ba5419e6645, stop processing=false, jms://myQueue
2017-03-29 11:23:26,347 [Session Task-16] DEBUG .chain.DefaultMessageProcessorChain - Invoking DefaultMessageProcessorChain '(inner iterating chain) of null'
[
  org.mule.api.processor.LoggerMessageProcessor@7e9d1d0b
] with event MuleEvent: 0-bea2c7f2-1469-11e7-9d1d-5ba5419e6645, stop processing=false, jms://myQueue
2017-03-29 11:23:26,347 [Session Task-16] INFO  pi.processor.LoggerMessageProcessor - Rolling back...
2017-03-29 11:23:26,347 [Session Task-16] DEBUG .support.DefaultListableBeanFactory - Returning cached instance of singleton bean '_muleStreamCloserService'
2017-03-29 11:23:26,347 [Session Task-16] DEBUG .support.DefaultListableBeanFactory - Returning cached instance of singleton bean '_muleStreamCloserService'
2017-03-29 11:23:26,347 [Session Task-16] DEBUG ule.util.DefaultStreamCloserService - Unable to find an StreamCloser for the stream type: class net.MyBean, the stream: net.MyBean@e341f050 will not be closed.