问:
How to update user password in Django Rest Framework?
I want to ask that following code provides updating password but I want to update password after current password confirmation process. So what should I add for it? Thank you.</p>

```<code>class UserPasswordSerializer(ModelSerializer):

    class Meta:
        model = User
        fields = [
            'password'
        ]

        extra_kwargs = {
            "password": {"write_only": True},
        }

    def update(self, instance, validated_data):
        for attr, value in validated_data.items():
            if attr == 'password':
                instance.set_password(value)
            else:
                setattr(instance, attr, value)
        instance.save()
        return instance
</code>```

答:
@Yiğit Güler give a good answer, thanks, but it could be better in some minor points.

As long you don't really works with UpdateModelMixin, but directly with the request user instance, you don't need to use a UpdateAPIView. A simple APIView is enough.

Also, when the password is changed, you can return a status.HTTP_204_NO_CONTENT instead of a 200 with some random content.

By the way, don't forgot to validate your new password before save. It's too bad if you allow "password" at update while you don't at create.

So I use the following code in my project:

```<code>from django.contrib.auth.password_validation import validate_password

class ChangePasswordSerializer(serializers.Serializer):
    """
    Serializer for password change endpoint.
    """
    old_password = serializers.CharField(required=True)
    new_password = serializers.CharField(required=True)

    def validate_new_password(self, value):
        validate_password(value)
        return value
</code>```

And for the view:

```<code>class UpdatePassword(APIView):
    """
    An endpoint for changing password.
    """
    permission_classes = (permissions.IsAuthenticated, )

    def get_object(self, queryset=None):
        return self.request.user

    def put(self, request, *args, **kwargs):
        self.object = self.get_object()
        serializer = ChangePasswordSerializer(data=request.data)

        if serializer.is_valid():
            # Check old password
            old_password = serializer.data.get("old_password")
            if not self.object.check_password(old_password):
                return Response({"old_password": ["Wrong password."]},
                                status=status.HTTP_400_BAD_REQUEST)
            # set_password also hashes the password that the user will get
            self.object.set_password(serializer.data.get("new_password"))
            self.object.save()
            return Response(status=status.HTTP_204_NO_CONTENT)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
</code>```

Body:
I want to ask that following code provides updating password but I want to update password after current password confirmation process. So what should I add for it? Thank you.

class UserPasswordSerializer(ModelSerializer):

    class Meta:
        model = User
        fields = [
            'password'
        ]

        extra_kwargs = {
            "password": {"write_only": True},
        }

    def update(self, instance, validated_data):
        for attr, value in validated_data.items():
            if attr == 'password':
                instance.set_password(value)
            else:
                setattr(instance, attr, value)
        instance.save()
        return instance

Body:
@Yiğit Güler give a good answer, thanks, but it could be better in some minor points.

As long you don't really works with UpdateModelMixin, but directly with the request user instance, you don't need to use a UpdateAPIView. A simple APIView is enough.

Also, when the password is changed, you can return a status.HTTP_204_NO_CONTENT instead of a 200 with some random content.

By the way, don't forgot to validate your new password before save. It's too bad if you allow "password" at update while you don't at create.

So I use the following code in my project:

from django.contrib.auth.password_validation import validate_password

class ChangePasswordSerializer(serializers.Serializer):
    """
    Serializer for password change endpoint.
    """
    old_password = serializers.CharField(required=True)
    new_password = serializers.CharField(required=True)

    def validate_new_password(self, value):
        validate_password(value)
        return value

And for the view:

class UpdatePassword(APIView):
    """
    An endpoint for changing password.
    """
    permission_classes = (permissions.IsAuthenticated, )

    def get_object(self, queryset=None):
        return self.request.user

    def put(self, request, *args, **kwargs):
        self.object = self.get_object()
        serializer = ChangePasswordSerializer(data=request.data)

        if serializer.is_valid():
            # Check old password
            old_password = serializer.data.get("old_password")
            if not self.object.check_password(old_password):
                return Response({"old_password": ["Wrong password."]},
                                status=status.HTTP_400_BAD_REQUEST)
            # set_password also hashes the password that the user will get
            self.object.set_password(serializer.data.get("new_password"))
            self.object.save()
            return Response(status=status.HTTP_204_NO_CONTENT)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


来源: stackexchange

问:
Regexp.last_match - why is it useful?
In "Comprehensive Ruby programming course' e-book, I faced a chapter, where author (Jordan Hudgens) describes it like:

“The last thing we are going to try is to return all the integer values from the sentence.”

And he does it like this:

```<code>string = "The quick 12 brown foxes jumped over 10 lazy dogs"
p string.to_enum(:scan, /\d+/).map { Regexp.last_match }
</code>```

And it returns:

```<code>=> [#<MatchData "3">, #<MatchData "34">, #<MatchData "23">]
</code>```

I wonder why / when, this Regexp.last_match might be used or better to say - why this way is not more efficient than:

```<code>p string.to_enum(:scan, /\d+/).map { |i| p i }
</code>```

This outputs only an array of integers and seems for me as a more efficient way to get those numbers..

Anyone maybe could explain what might was the reasons for author to pick Regesp.last_match ?

答:
This is a nifty trick (read: hack).

```<code>string = "The quick 12 brown foxes jumped over 10 lazy dogs"
p string.to_enum(:scan, /\d+/).map { Regexp.last_match }
</code>```

The thing is there is no handy way to yield instances of MatchData from inside String#scan.

```<code>p string.to_enum(:scan, /\d+/).map { |i| p i }
</code>```

makes not much sense, you probably meant:

```<code>p string.to_enum(:scan, /\d+/).map(&:itself) # or { |i| i } # or .to_a
</code>```

or even

```<code>p string.scan(/\d+/)
</code>```

The results differ, though; the latter returns strings, while the former is a way to return MatchData instances.

ContentLicense: CC BY-SA 3.0

Title: Regexp.last_match - why is it useful?

Body:
In "Comprehensive Ruby programming course' e-book, I faced a chapter, where author (Jordan Hudgens) describes it like:

“The last thing we are going to try is to return all the integer values from the sentence.”

And he does it like this:

string = "The quick 12 brown foxes jumped over 10 lazy dogs"
p string.to_enum(:scan, /\d+/).map { Regexp.last_match }

And it returns:

=> [#<MatchData "3">, #<MatchData "34">, #<MatchData "23">]

I wonder why / when, this Regexp.last_match might be used or better to say - why this way is not more efficient than:

p string.to_enum(:scan, /\d+/).map { |i| p i }

This outputs only an array of integers and seems for me as a more efficient way to get those numbers..

Anyone maybe could explain what might was the reasons for author to pick Regesp.last_match ?

Body:
This is a nifty trick (read: hack).

string = "The quick 12 brown foxes jumped over 10 lazy dogs"
p string.to_enum(:scan, /\d+/).map { Regexp.last_match }

The thing is there is no handy way to yield instances of MatchData from inside String#scan.

p string.to_enum(:scan, /\d+/).map { |i| p i }

makes not much sense, you probably meant:

p string.to_enum(:scan, /\d+/).map(&:itself) # or { |i| i } # or .to_a

or even

p string.scan(/\d+/)

The results differ, though; the latter returns strings, while the former is a way to return MatchData instances.


问:
Getting the first date of current quarter
I'm trying to get the first and the last date of current quarter, i'm using it:

```<code>NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitQuarter | NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];

components.quarter = 1;

funStartDate = [[NSCalendar currentCalendar] dateFromComponents: components];
NSLog(@"First day of quater: %@", funStartDate);

[components setQuarter:[components quarter]+1];

funEndDate = [[NSCalendar currentCalendar] dateFromComponents: components];
NSLog(@"Last day of quater: %@", [funEndDate descriptionWithLocale:[NSLocale currentLocale]]);
</code>```

But in both console print I see today's date. What I'm doing wrong?

答:
Swift 3.1. Quarter component still not working. Workaround:

```<code>extension Date {
    public var startOfQuarter: Date {
        let startOfMonth = Calendar.current.date(from: Calendar.current.dateComponents([.year, .month], from: Calendar.current.startOfDay(for: self)))!

        var components = Calendar.current.dateComponents([.month, .day, .year], from: startOfMonth)

        let newMonth: Int
        switch components.month! {
        case 1,2,3: newMonth = 1
        case 4,5,6: newMonth = 4
        case 7,8,9: newMonth = 7
        case 10,11,12: newMonth = 10
        default: newMonth = 1
        }
        components.month = newMonth
        return Calendar.current.date(from: components)!
    }
}
</code>```

Usage:

```<code>Date().startOfQuarter
</code>```

Body:
I'm trying to get the first and the last date of current quarter, i'm using it:

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitQuarter | NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];

components.quarter = 1;

funStartDate = [[NSCalendar currentCalendar] dateFromComponents: components];
NSLog(@"First day of quater: %@", funStartDate);

[components setQuarter:[components quarter]+1];

funEndDate = [[NSCalendar currentCalendar] dateFromComponents: components];
NSLog(@"Last day of quater: %@", [funEndDate descriptionWithLocale:[NSLocale currentLocale]]);

But in both console print I see today's date. What I'm doing wrong?

Body:
Swift 3.1. Quarter component still not working. Workaround:

extension Date {
    public var startOfQuarter: Date {
        let startOfMonth = Calendar.current.date(from: Calendar.current.dateComponents([.year, .month], from: Calendar.current.startOfDay(for: self)))!

        var components = Calendar.current.dateComponents([.month, .day, .year], from: startOfMonth)

        let newMonth: Int
        switch components.month! {
        case 1,2,3: newMonth = 1
        case 4,5,6: newMonth = 4
        case 7,8,9: newMonth = 7
        case 10,11,12: newMonth = 10
        default: newMonth = 1
        }
        components.month = newMonth
        return Calendar.current.date(from: components)!
    }
}

Usage:

Date().startOfQuarter


问:
String.replaceAll without RegEx
I'd like to replace all instances of a substring in a string but String.replaceAll() only accepts a pattern. The string that I have came from a previous match. Is it possible to add escapes to the pattern that I have or is there a version of replaceAll() in another class which accepts a literal string instead of a pattern?

答:
The method to add escapes is Pattern.quote().

```<code>String replaced = myString.replaceAll(Pattern.quote(matchingStr), replacementStr)
</code>```

But as Jon says you can just use replace().  Despite the fact that it deviates from the replaceAll name, it does replace all occurrences just like replaceAll().

Title: String.replaceAll without RegEx

Body:
The method to add escapes is Pattern.quote().

String replaced = myString.replaceAll(Pattern.quote(matchingStr), replacementStr)

But as Jon says you can just use replace().  Despite the fact that it deviates from the replaceAll name, it does replace all occurrences just like replaceAll().

ContentLicense: CC BY-SA 2.5


问:
How to get the first element of a string split with space
I am trying to get the name of the user after su in a bash script. I used the following code:

```<code>user=`who am i`
#user <- "user4035     pts/0        2017-04-02 05:13 (my-hostname)"
userarray=($user)
#userarray <- ["user4035", "pts/0", "2017-04-02 05:13", "(my-hostname)"]
user=${userarray[0]}
#outputs "user4035"
echo $user
</code>```

It works correctly, but is it possible to achieve the same result with less number of commands?

答:
You can remove one line of commands by creating the array on one line, but it's not worth doing any more than that because at least you're only using shell builtins, and not forking any additional commands:</p>

```<code>who=(`who am i`)
user=${who[0]}
</code>```

Body:
I am trying to get the name of the user after su in a bash script. I used the following code:

user=`who am i`
#user <- "user4035     pts/0        2017-04-02 05:13 (my-hostname)"
userarray=($user)
#userarray <- ["user4035", "pts/0", "2017-04-02 05:13", "(my-hostname)"]
user=${userarray[0]}
#outputs "user4035"
echo $user

It works correctly, but is it possible to achieve the same result with less number of commands?

Body:
You can remove one line of commands by creating the array on one line, but it's not worth doing any more than that because at least you're only using shell builtins, and not forking any additional commands:

who=(`who am i`)
user=${who[0]}


问:
How do I insert variable values into DOM style value in JavaScript
I have the following code: When the slide value changes the transform property for the element should take the slide value which by default are 0deg, i want it to change gradually for the slide value, but i don't know why but it's not working as it should.

```<code>```

<input type="range" min="0" max="360" id="mxConcept" oninput="shthis()"
onchange="shthis()">

```
</code>```

Codepen

答:
You must apply the value x to the transform property like this:

```<code> function shthis(){
        var x = document.getElementById('mxConcept').value;
            document.getElementById('callme').innerHTML=x;
            document.getElementById("trsScript").style.webkitTransform = "rotate("+x+"deg)";
    }
</code>```

update:

```<code>document.getElementById("trsScript").style.webkitTransform = `rotate(${x}deg)`
</code>```

also works using template literals.

Body:
I have the following code: When the slide value changes the transform property for the element should take the slide value which by default are 0deg, i want it to change gradually for the slide value, but i don't know why but it's not working as it should.

<input type="range" min="0" max="360" id="mxConcept" oninput="shthis()"
onchange="shthis()">

Codepen

Body:
You must apply the value x to the transform property like this:

 function shthis(){
        var x = document.getElementById('mxConcept').value;
            document.getElementById('callme').innerHTML=x;
            document.getElementById("trsScript").style.webkitTransform = "rotate("+x+"deg)";
    }

update:

document.getElementById("trsScript").style.webkitTransform = `rotate(${x}deg)`

also works using template literals.


问:
python error where __str__ returns a NoneType
```<code>class Pixel:
  """Representing a 'pixel' aka one character on the screen
  is mostly gonne be used in Map using a tuple location and a
  character that can be changed"""

  def __init__(self, char='#', location=(0,0)):
    assert type(char) == str
    assert type(location[0]) == int and type(location[1]) == int
    self.location = location
    self.x = self.location[0]
    self.y = self.location[1]
    self.char = char

  def __str__(self):
    return(self.char)

class Map:
  """Representing a map by having diffferent characters
  on different lines and being able to manipulate the
  characters, thus playing a game"""

  def __init__(self, file=None):
    self.pixels = {}
    if not file:
      self.rows = 3
      self.colls = 3
      for r in range(self.rows):
        for c in range(self.colls):
          self.pixels[(r, c)] = Pixel('#', (r, c))

  def __str__(self):
    print(self.pixels)
    for c in range(self.colls):
      print('')
      for r in range(self.rows):
        print(self.pixels[(r, c)], end='')

a = Map()
print(a)
</code>```

I am trying to make a class that defines a grid where each place in the grid has a character, but when I run the code I get an error that tells me that __str__ returns a NoneType. I know I am not yet handeling file imput when initiating Map but that isn't the problem here, here is the output I got.

```<code>{(0, 1): <__main__.Pixel object at 0x7f31612a3080>,
 (1, 2): <__main__.Pixel object at 0x7f31612a3470>,
 (0, 0): <__main__.Pixel object at 0x7f31612a3048>,
 (2, 0): <__main__.Pixel object at 0x7f31612a34a8>,
 (1, 0): <__main__.Pixel object at 0x7f31612a32b0>,
 (2, 2): <__main__.Pixel object at 0x7f31612a3390>,
 (0, 2): <__main__.Pixel object at 0x7f31612a30b8>,
 (2, 1): <__main__.Pixel object at 0x7f31612a3358>,
 (1, 1): <__main__.Pixel object at 0x7f31612a32e8>}

###
###
###Traceback (most recent call last):
  File "main.py", line 45, in <module>
    print(a)
TypeError: __str__ returned non-string (type NoneType)
exited with non-zero status
</code>```

I am also confused why the print in __str__ from Map refered me to the __main__.Pixel objects instead of using they __str__ method, but that is probably just my lack of knowlage

what am I missing?

答: I forgot to returnanything, i had the __str__print everything i needed but i didn't return anything for my print(a), thus i got a NoneType error.

Body:
class Pixel:
  """Representing a 'pixel' aka one character on the screen
  is mostly gonne be used in Map using a tuple location and a
  character that can be changed"""

  def __init__(self, char='#', location=(0,0)):
    assert type(char) == str
    assert type(location[0]) == int and type(location[1]) == int
    self.location = location
    self.x = self.location[0]
    self.y = self.location[1]
    self.char = char

  def __str__(self):
    return(self.char)

class Map:
  """Representing a map by having diffferent characters
  on different lines and being able to manipulate the
  characters, thus playing a game"""

  def __init__(self, file=None):
    self.pixels = {}
    if not file:
      self.rows = 3
      self.colls = 3
      for r in range(self.rows):
        for c in range(self.colls):
          self.pixels[(r, c)] = Pixel('#', (r, c))

  def __str__(self):
    print(self.pixels)
    for c in range(self.colls):
      print('')
      for r in range(self.rows):
        print(self.pixels[(r, c)], end='')

a = Map()
print(a)

I am trying to make a class that defines a grid where each place in the grid has a character, but when I run the code I get an error that tells me that __str__ returns a NoneType. I know I am not yet handeling file imput when initiating Map but that isn't the problem here, here is the output I got.

{(0, 1): <__main__.Pixel object at 0x7f31612a3080>,
 (1, 2): <__main__.Pixel object at 0x7f31612a3470>,
 (0, 0): <__main__.Pixel object at 0x7f31612a3048>,
 (2, 0): <__main__.Pixel object at 0x7f31612a34a8>,
 (1, 0): <__main__.Pixel object at 0x7f31612a32b0>,
 (2, 2): <__main__.Pixel object at 0x7f31612a3390>,
 (0, 2): <__main__.Pixel object at 0x7f31612a30b8>,
 (2, 1): <__main__.Pixel object at 0x7f31612a3358>,
 (1, 1): <__main__.Pixel object at 0x7f31612a32e8>}

###
###
###Traceback (most recent call last):
  File "main.py", line 45, in <module>
    print(a)
TypeError: __str__ returned non-string (type NoneType)
exited with non-zero status

I am also confused why the print in __str__ from Map refered me to the __main__.Pixel objects instead of using they __str__ method, but that is probably just my lack of knowlage

what am I missing?


问:
AsyncCalls AsyncCallEx E2036 Variable required
Delphi 10.1 Berlin

I am unable to understood why I am getting error.

I get the error message when compile this (while TestRec is simple function - all is ok):

```<code>type
  TData = record
    Value: string;
  end;

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    function TestRec(var Data: TData): Integer;
  end;

...

function TForm1.TestRec(var Data: TData): Integer;
begin
  Data.Value := 'TestOut';

  Result := 0;
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  MyData: TData;

  a: IAsyncCall;
begin
  MyData.Value := 'TestIn';

  a := AsyncCallEx(@TestRec, MyData); //[dcc32 Error] Unit1.pas(47): E2036 Variable required
end;
</code>```

Error Shown:
[dcc32 Error] Unit1.pas(47): E2036 Variable required

答:
The signature for the overloaded AsyncCallEx() that accepts a method is:

```<code>function AsyncCallEx(Method: TAsyncCallArgRecordMethod; var Arg{: TRecordType}): IAsyncCall;
</code>```

The correct way to reference the method in the call is:

```<code>a := AsyncCallEx(TestRec, MyData);
</code>```

Since the method declaration of the method is:

```<code>TAsyncCallArgRecordMethod = function(var Arg{: TRecordType}): integer of object;
</code>```

you will have to strip the data type from the method argument in TestRec.

```<code>function TestRec(var Data{: TData}): Integer;
</code>```

The AsyncCallEx is from the library AsyncCalls.

Body:
Delphi 10.1 Berlin

I am unable to understood why I am getting error.

I get the error message when compile this (while TestRec is simple function - all is ok):

type
  TData = record
    Value: string;
  end;

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    function TestRec(var Data: TData): Integer;
  end;

...

function TForm1.TestRec(var Data: TData): Integer;
begin
  Data.Value := 'TestOut';

  Result := 0;
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  MyData: TData;

  a: IAsyncCall;
begin
  MyData.Value := 'TestIn';

  a := AsyncCallEx(@TestRec, MyData); //[dcc32 Error] Unit1.pas(47): E2036 Variable required
end;

Error Shown:
[dcc32 Error] Unit1.pas(47): E2036 Variable required

Body:
The signature for the overloaded AsyncCallEx() that accepts a method is:

function AsyncCallEx(Method: TAsyncCallArgRecordMethod; var Arg{: TRecordType}): IAsyncCall;

The correct way to reference the method in the call is:

a := AsyncCallEx(TestRec, MyData);

Since the method declaration of the method is:

TAsyncCallArgRecordMethod = function(var Arg{: TRecordType}): integer of object;

you will have to strip the data type from the method argument in TestRec.

function TestRec(var Data{: TData}): Integer;

The AsyncCallEx is from the library AsyncCalls.


问:
SMS gateway for Dynamics 365
First of all, I have to say that I am NET developer (C#) and my knowledge on Dynamics 365 is pretty limited. Nevertheless my employer thought that I am good enough to make that thingy from post title :)

After couple of hours researching and reading, I found this video https://www.youtube.com/watch?v=6LwZLoXS6jo which address on how to create and send SMS from Dynamics. I am aware that this require me to create new Dynamics entities, at least SMSMessage and SMSMessageTemplate, but at least I found out how to do this :)

I understood everything stated there, but as i  already said, due to my lack of knowledge on Dynamics 365, I got problems with (probably) basic things regarding Dynamics.

Here are those problems:

1. As far as I can tell, in order to build SMS gateway, first thing I need to do is to add new menu item inside Dynamics 365. I presume that this new menu item should reside inside 'Contacts' menu (contacts.jpg, marked with red box) but I am not sure on how to achieve this. Please note, I do not want someone to provide me with some magic solution, I just need someone to provide me with valid links that I can use to learn about this and solve my own problem :)

2. When new menu item is in place, and user click on it, I would like to open up a form for user to select SMS template that will be used and maybe setup some other values. Same again, U do not need to help me with exact code, just with some usable links :)

3. Inside that form that user will open on menu click, I would like to know how to get list of selected contacts (from grid at contact.jpg)

When I (finally) have that list of contacts, I will create SMS entities mentioned above (video link) and everything will fall in place and (hopefully) work.

I am aware that this is probably too much to ask, cause Dynamics 365 is rather complex, and people are spending great amounts of money and their time learning to became Dynamics developers, but without help, Dynamics is making me running in circles chasing my own tail :) and getting nowhere.

Also, I will be using online Dynamics 365 so bare in mind that any solution should work with it.

if any of U think that I missed or got something wrong, please let me know.enter image description here

答:
So basically to get you started, you should:

1) Create a solution in Settings => Customizations => Solutions

2) Add contact entity to that solution (by choosing "Add existing" under Entities pane). Don't click "Add all assets" you will need only contact metadata to get going

3) Create jScript file and add a web resource to CRM (nothing really complicated, just go to web resources in you solution and click "Add new" and specify type of your web resource as jScript and target your file).

4) Now download http://www.xrmtoolbox.com

5) For now you are interested only in plugin "Ribbon Workbench"

6) Now simply choose your solution and contact - you will see command bars for contact homepage, list and form. This is pretty strainghtforward - simply drag and drop a button wherever you like, create a command using workbench and bind the button with the command (simply choose it from a drop-down). The command you are interested in is Custom Javacript. Here you specify your web resource and name of the function that you want to call. You can also specify parameters that should be passed inside your function for example ids of selected items (if you are on the list of records).

There are many approaches to fulfil your specific needs, but being able to call a custom javascript function from a button should be a good starting point, the rest is simply the knowledge of CRM SDK, so how to create an entity using API or open a form or open a web resource - everything is very well documented and you can get it simply by asking google, so I will not post any blog here, not to advertise too much. Also I's suggest downloading latest CRM SDK (https://www.microsoft.com/en-us/download/details.aspx?id=50032) - you have many sample code there, regarding plugins and some form modifications, you should also check this out.

To make it easier for you, you should refer to this "menu" as "Command bar" or "Ribbon", so rather look for "adding custom button to command bar CRM 2016" and you will be all good. Also to make a form for choosing a template, you will probably need some custom web resource, so "creating custom html5 web resource CRM 2016" should give you some good examples.

Title: SMS gateway for Dynamics 365


问:
Is there a "Group Box" equivalent in Java Swing?
Trying to build a GUI application in Java/Swing. I'm mainly used to "painting" GUIs on the Windows side with tools like VB (or to be more precise, Gupta SQLWindows... wonder how many people know what that is ;-)).

I can't find an equivalent of a Group Box in Swing...

With a group box, you have a square box (usually with a title) around a couple of related widgets. One example is a group box around a few radio buttons (with the title explaining what the radio buttons are about, e.g. Group Box entitled "Sex" with "Male" and "Female" radio buttons).

I've searched around a bit... the only way I found was to add a sub-pane, set the border on the sub-pane and then add all the widgets in the "group" to the sub-pane. Is there a more elegant way to do that?

答:
Not AFAIK, at least not with standard swing widgets.

In VB you have a group widget, which is essentially a panel + border.

In Swing you have a JPanel which is the container widget, and you create and set a border object on it only if you need one. One can argue that in a way that is more elegant since you don't pay for something you don't use (e.g., border)

OwnerDisplayName: IronGoofy

LastEditorDisplayName: A. Rex

OwnerDisplayName: Uri


问:
How to intercept an authentication request in ASP.net webform
I have user's who are losing their data because they sit on a page too long, then are asked to log back in.  I want to do the following:

1) Instead of redirecting them to a login page, I want to cancel the current request and give the user a popup dialog box to login with.

2) When the login is successful, I want the user to be sent back to their form, with all data intact.  (Even better if the request could go through without sending them back to that form, but this is optional).

How can I intercept these authentication requests, and present the user with a popup login?

I am using ASP.net forms authentication.

答:
You can intercept this event on Application_AuthenticateRequest in Global.asax

But, you need be more specific, are you using the ASP.NET Forms Authentication?

Added:

Try this and reply me

In Global.asax

```<code>void Application_AuthenticateRequest(object sender, EventArgs e)
{

    if (HttpContext.Current.User == null)
    {
        FormsAuthenticationTicket ticket = new
                        FormsAuthenticationTicket(1, "Anonymous", DateTime.Now, DateTime.Now.AddMinutes(30), false, "Anonymous");

        string encryptedTicket = FormsAuthentication.Encrypt(ticket);

        HttpCookie cookie =
           new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

        Response.Cookies.Add(cookie);

        FormsIdentity id = new FormsIdentity(ticket);

        System.Security.Principal.GenericPrincipal principal = new System.Security.Principal.GenericPrincipal(id, ticket.UserData.Split(new char[] { '|' }));

        Context.User = principal;
    }

}
</code>```

In a web form

```<code>string cookieName = FormsAuthentication.FormsCookieName;

    HttpCookie authCookie = Context.Request.Cookies[cookieName];

    FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

    if (authTicket.UserData == "Anonymous")
    {

        //Throw the login popup

    }
    else
    {

        //Some Code

    }
</code>```

Body:
You can intercept this event on Application_AuthenticateRequest in Global.asax

But, you need be more specific, are you using the ASP.NET Forms Authentication?

Added:

Try this and reply me

In Global.asax

void Application_AuthenticateRequest(object sender, EventArgs e)
{

    if (HttpContext.Current.User == null)
    {
        FormsAuthenticationTicket ticket = new
                        FormsAuthenticationTicket(1, "Anonymous", DateTime.Now, DateTime.Now.AddMinutes(30), false, "Anonymous");

        string encryptedTicket = FormsAuthentication.Encrypt(ticket);

        HttpCookie cookie =
           new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

        Response.Cookies.Add(cookie);

        FormsIdentity id = new FormsIdentity(ticket);

        System.Security.Principal.GenericPrincipal principal = new System.Security.Principal.GenericPrincipal(id, ticket.UserData.Split(new char[] { '|' }));

        Context.User = principal;
    }

}

In a web form

string cookieName = FormsAuthentication.FormsCookieName;

    HttpCookie authCookie = Context.Request.Cookies[cookieName];

    FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

    if (authTicket.UserData == "Anonymous")
    {

        //Throw the login popup

    }
    else
    {

        //Some Code

    }


问:
Why this concurrent execution always give me the same trace?
I'm trying to understand concurrent execution in Java, but given this code :

```<code>class Inter extends Thread {
    public void run() {
        System.out.println("Starting...");
        try {
            sleep(10000);
        } catch (InterruptedException e) {
            System.out.println("Interrupted."); }
        System.out.println("Finished.");
    }

    public static void main(String[] args) {
        Inter hi = new Inter();
        hi.start();
        System.out.println("Sending interruption...");
        hi.interrupt();
        System.out.println("Sent.");
    }
}
</code>```

I don't know why always give me this trace :

```<code>Sending interruption...
Sent.
Starting...
Interrupted.
Finished.
</code>```

No matter how many times I run :

```<code>$ java Inter
</code>```

As fars as I know in Java, when we execute the start() method in a new thread, the execution of this thread starts.

So , since the main thread and the Inter thread are concurrently executed, why can't be this a possible trace, ?

```<code>Starting..
Sending interruption..
Sent
Interrupted
Finished
</code>```

答:
So, since the main thread and the Inter thread are concurrently executed, why can't be this a possible trace?

Yes, it can. If you run your program a thousand times, most probably you will have that output at least once.

It's up to the operating system thread scheduler to arrange the threads execution in order to give that possible output, but we have no control over the scheduler. Hence, the importance of properly designing your code to prevent race conditions.

Body:
I'm trying to understand concurrent execution in Java, but given this code :

class Inter extends Thread {
    public void run() {
        System.out.println("Starting...");
        try {
            sleep(10000);
        } catch (InterruptedException e) {
            System.out.println("Interrupted."); }
        System.out.println("Finished.");
    }

    public static void main(String[] args) {
        Inter hi = new Inter();
        hi.start();
        System.out.println("Sending interruption...");
        hi.interrupt();
        System.out.println("Sent.");
    }
}

I don't know why always give me this trace :

Sending interruption...
Sent.
Starting...
Interrupted.
Finished.

No matter how many times I run :

$ java Inter

As fars as I know in Java, when we execute the start() method in a new thread, the execution of this thread starts.

So , since the main thread and the Inter thread are concurrently executed, why can't be this a possible trace, ?

Starting..
Sending interruption..
Sent
Interrupted
Finished


问:
C# in Windows Forms : "Index was outside the bounds of the array" at a try to auto-add new space
I really can't understand where's from this error and how to fix it.

My idea is to grow the space with 1 every time I read a new object, that's why I use int m = a.GetLength(0)+1;

 a[m, j] = Convert.ToString(m); is j=1 which means the number of account which is in fact m, last position from array.

How can I made this works without writing a lot of lines and copy vector in another with +1 line every time I want to add new element?

// "Index was outside the bounds of the array."

// "An unhandled exception of type 'System.IndexOutOfRangeException' occurred in code.exe"

photo with code&error:

```<code>    private void adauga_Click(object sender, EventArgs e)
    {

        int m = a.GetLength(0)+1;
            for (int j = 0; j < 7; j++)
            {   a[m, j] = Convert.ToString(m);
                a[m, j] = textnume.Text;
                a[m, j] = textprenume.Text;
                a[m, j] = textcnp.Text;
                a[m, j] = textserie.Text;
                a[m, j] = textnumar.Text;
                a[m, j] = textdebcre.Text;
                b[m] = Convert.ToInt32(textsuma.Text); } }
</code>```

Where a and b are :
        static string [,]a = new string[1,1];
        static int[] b=new int1;

答: First, only textdebcre.Text will be in a[m,j] at the end. Second, a is [1,1] and you are trying to access a[1, bigger then 1] so you have an error. Just make a to new string[1,7].

Body:
I really can't understand where's from this error and how to fix it.

My idea is to grow the space with 1 every time I read a new object, that's why I use int m = a.GetLength(0)+1;

 a[m, j] = Convert.ToString(m); is j=1 which means the number of account which is in fact m, last position from array.

How can I made this works without writing a lot of lines and copy vector in another with +1 line every time I want to add new element?

// "Index was outside the bounds of the array."

// "An unhandled exception of type 'System.IndexOutOfRangeException' occurred in code.exe"

photo with code&error:

    private void adauga_Click(object sender, EventArgs e)
    {

        int m = a.GetLength(0)+1;
            for (int j = 0; j < 7; j++)
            {   a[m, j] = Convert.ToString(m);
                a[m, j] = textnume.Text;
                a[m, j] = textprenume.Text;
                a[m, j] = textcnp.Text;
                a[m, j] = textserie.Text;
                a[m, j] = textnumar.Text;
                a[m, j] = textdebcre.Text;
                b[m] = Convert.ToInt32(textsuma.Text); } }

Where a and b are :
        static string [,]a = new string[1,1];
        static int[] b=new int1;


问:
unsigned char value in a function
This is taken from: https://exploreembedded.com/wiki/AVR_C_Library DS1307_GetTime() method, im trying to understand how this function works. So i made a simplified example below.

Can you explain what is happening in the  GetTime() function and what kid of value should  I pass into it?

My goal is to obtain b value inside int main() function.

My understanding so far is:

pointer * a = I2C_Read(); points to unsigned char, but a pointer can not point to a value, why isnt it erroring?

```<code>#include <stdio.h>
#include <stdlib.h>

unsigned char I2C_Read()
{
    unsigned char b = 0b11111111;
    return b;
}

void GetTime(unsigned char *a)
{
    *a = I2C_Read();
}

int main()
{
    unsigned char *a = 0;
    GetTime(a);                        // ?

    printf("Value of b is: %d\n" , b); // ?
}
</code>```

答:
You are setting the pointer a to 0 - not a valid value

You need to read up about pointers - but in the meantime change the code to

```<code> unsigned char a = 0;
 GetTime(&a);
 printf("Value of b is: %d\n" , a);
</code>```

Title: unsigned char value in a function

Body:
This is taken from: https://exploreembedded.com/wiki/AVR_C_Library DS1307_GetTime() method, im trying to understand how this function works. So i made a simplified example below.

Can you explain what is happening in the  GetTime() function and what kid of value should  I pass into it?

My goal is to obtain b value inside int main() function.

My understanding so far is:

pointer * a = I2C_Read(); points to unsigned char, but a pointer can not point to a value, why isnt it erroring?

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

unsigned char I2C_Read()
{
    unsigned char b = 0b11111111;
    return b;
}

void GetTime(unsigned char *a)
{
    *a = I2C_Read();
}

int main()
{
    unsigned char *a = 0;
    GetTime(a);                        // ?

    printf("Value of b is: %d\n" , b); // ?
}

Body:
You are setting the pointer a to 0 - not a valid value

You need to read up about pointers - but in the meantime change the code to

 unsigned char a = 0;
 GetTime(&a);
 printf("Value of b is: %d\n" , a);


问:
PHP: Force download is downloading an empty file
The code below displays this:

```<code>/home/my_site/www/wp-content/uploads/2017/03/2017-03-17-my_file.mp3
</code>```

As far as I can tell, this path is correct. Yet when I comment away the echo and download the file, it's an empty file. Why?

Code:

```<code>if (isset($_GET['file'])) {
    clearstatcache();
    $file_path = str_replace('http://www.example.com/', '', $_GET['file']);
    $file_path = $_SERVER['DOCUMENT_ROOT'] . '/' . $file_path . '.mp3';
    echo $file_path;

    if(file_exists($file_path)) {
        $file_name = basename($file_path);
        $file_size = filesize($file_path);
        header("Cache-Control: private");
        header("Content-Type: application/stream");
        header("Content-Length: ".$file_size);
        header("Content-Disposition: attachment; filename=".$file_name);
        exit();
    }
    else {
        die('The provided file path is not valid.');
    }
}
</code>```

EDIT: this is what I have after KIKO Software's suggestion. Still downloads empty file.

```<code><?php
if (isset($_GET['file'])) {
  $file_path = $_SERVER['DOCUMENT_ROOT'] . '/' . $_GET['file'] . '.mp3';
  //echo $file_path;
  //$file_path = $_SERVER['SCRIPT_FILENAME'];
  if (file_exists($file_path)) {
    $file_name = basename($file_path);
    $file_size = filesize($file_path);
  header('Content-type: application/octet-stream');
  header('Content-Transfer-Encoding: binary');
  header('Content-Length: '.$file_size);
  header('Content-Disposition: attachment; filename='.$file_name);
  //readfile($file_path);
  exit();
  }
  else {
      die('The provided file path is not valid.');
  }
}
?>
</code>```

答:
Simple example to download a file:

```<code>$content = 'This is the content.';
$size    = strlen($content);
$name    = 'test.txt';
header('Content-type: application/octet-stream');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.$size);
header('Content-Disposition: attachment; filename='.$name);
echo $content;
</code>```

Make sure this works first. If it doesn't there could be a problem with the headers. Switch on error reporting and see: How to fix "Headers already sent" error in PHP

Then build up on that. Start by downloading the script itself:

```<code>$file_path = $_SERVER['SCRIPT_FILENAME'];
if (file_exists($file_path)) {
  $file_name = basename($file_path);
  $file_size = filesize($file_path);
  header('Content-type: application/octet-stream');
  header('Content-Transfer-Encoding: binary');
  header('Content-Length: '.$file_size);
  header('Content-Disposition: attachment; filename='.$file_name);
  readfile($file_path);
  exit();
}
else {
  die('The provided file path is not valid.');
}
</code>```

And only after that try to download something else.

By approaching the problem step by step it is easier to see where it goes wrong.

Body:
The code below displays this:

/home/my_site/www/wp-content/uploads/2017/03/2017-03-17-my_file.mp3

As far as I can tell, this path is correct. Yet when I comment away the echo and download the file, it's an empty file. Why?

Code:

if (isset($_GET['file'])) {
    clearstatcache();
    $file_path = str_replace('http://www.example.com/', '', $_GET['file']);
    $file_path = $_SERVER['DOCUMENT_ROOT'] . '/' . $file_path . '.mp3';
    echo $file_path;

    if(file_exists($file_path)) {
        $file_name = basename($file_path);
        $file_size = filesize($file_path);
        header("Cache-Control: private");
        header("Content-Type: application/stream");
        header("Content-Length: ".$file_size);
        header("Content-Disposition: attachment; filename=".$file_name);
        exit();
    }
    else {
        die('The provided file path is not valid.');
    }
}

EDIT: this is what I have after KIKO Software's suggestion. Still downloads empty file.

<?php
if (isset($_GET['file'])) {
  $file_path = $_SERVER['DOCUMENT_ROOT'] . '/' . $_GET['file'] . '.mp3';
  //echo $file_path;
  //$file_path = $_SERVER['SCRIPT_FILENAME'];
  if (file_exists($file_path)) {
    $file_name = basename($file_path);
    $file_size = filesize($file_path);
  header('Content-type: application/octet-stream');
  header('Content-Transfer-Encoding: binary');
  header('Content-Length: '.$file_size);
  header('Content-Disposition: attachment; filename='.$file_name);
  //readfile($file_path);
  exit();
  }
  else {
      die('The provided file path is not valid.');
  }
}
?>

Body:
Simple example to download a file:

$content = 'This is the content.';
$size    = strlen($content);
$name    = 'test.txt';
header('Content-type: application/octet-stream');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.$size);
header('Content-Disposition: attachment; filename='.$name);
echo $content;

Make sure this works first. If it doesn't there could be a problem with the headers. Switch on error reporting and see: How to fix "Headers already sent" error in PHP

Then build up on that. Start by downloading the script itself:

$file_path = $_SERVER['SCRIPT_FILENAME'];
if (file_exists($file_path)) {
  $file_name = basename($file_path);
  $file_size = filesize($file_path);
  header('Content-type: application/octet-stream');
  header('Content-Transfer-Encoding: binary');
  header('Content-Length: '.$file_size);
  header('Content-Disposition: attachment; filename='.$file_name);
  readfile($file_path);
  exit();
}
else {
  die('The provided file path is not valid.');
}

And only after that try to download something else.

By approaching the problem step by step it is easier to see where it goes wrong.


问:
How to pass values from javascript to HTML and vice versa
I am trying to do as follow:

Get a list of paired values - each value includes a name and a number

present the user with a list of buttons , each button shows the name from the name-value pair, so if I get 10 pairs, I will present 10 buttons

when the user clicks the chosen name, the button invokes a JS with the name-value matched.

I am very new to HTML , so this part is the problematic for me.
The page is not required to look nice at this stage, just function correctly.

```<code><html>

<head> </head>

<body>
    <script>
    var pairs = [
        {
            "name_1": 123
        },
        {
            "name_2": 983
        },
        {
            "name_3": 567
        }
    ];

    function present_buttons(pairs) {
        for (var i in pairs) {
            console.log(`index  = ${i}`);
            console.log(`name  = ${pair[i].name}`);
            console.log(`value  = ${pair[i].value}`);
            // send info the the HTML section, so present proper names on buttons
            // make sure to hook matching value for each button so it will be sent correctly to the use_value function later on
        }
    }

    function use_value(value) {
        // do something with the value triggered by the matching name button
    }
    </script>
    <!--
get names to present on buttons from the present_buttons()
when a button is clicked , send the matching value to the use_value() function

-->
</body>

</html>
</code>```

答:
Try this:</p>

```<code><html>
    <head></head>
    <body>
        <script>
            var pairs = [
                { "name_1" : 123 } ,
                { "name_2" : 983 } ,
                { "name_3" : 567 }
            ];

            for (var i = 0; i < pairs.length; i++) {
                var button = document.createElement('button');
                var pair = pairs[i];

                button.innerHTML = Object.keys(pair)[0];
                button.addEventListener('click', function (pair) {
                    use_value(pair);
                }.bind(this, pair));

                document.getElementsByTagName('body')[0].appendChild(button);
            }

            function use_value(value)  {

                // do something with the value triggered by the matching name button
            }
        </script>
    </body>
</html>
</code>```

Body:
Try this:

<html>
    <head></head>
    <body>
        <script>
            var pairs = [
                { "name_1" : 123 } ,
                { "name_2" : 983 } ,
                { "name_3" : 567 }
            ];

            for (var i = 0; i < pairs.length; i++) {
                var button = document.createElement('button');
                var pair = pairs[i];

                button.innerHTML = Object.keys(pair)[0];
                button.addEventListener('click', function (pair) {
                    use_value(pair);
                }.bind(this, pair));

                document.getElementsByTagName('body')[0].appendChild(button);
            }

            function use_value(value)  {

                // do something with the value triggered by the matching name button
            }
        </script>
    </body>
</html>


问:
Authintication upload files using Django
hello I have two difference projects one project have only authentication and other have only fileupload and upload to personal folder per user(work fine from admin mode)and I want to connect with one project.
On the second project I have create a fuction where create new personal folder for any user where want upload files using user_id,user_username (I have to many similars ways to do this function and this is for test).

that I don't know is how to take user_id or user_name of login user and how to use this in views.py to my fuction for generate_path.
I thing so maybe like this user = Photo.objects.get(user__id=user_id)but I am not sure

```<code>def generate_path(user):
    return "/{0}/img".format(user.username)

class Photo(models.Model):
     user = models.ForeignKey(to=settings.AUTH_USER_MODEL)
    file = models.FileField(upload_to=upload_to=generate_path(self.user)))
</code>```

views.py

```<code>@login_required
class BasicUploadView(View):
    def get(self, request):
        photoslist = Photo.objects.all()
        return render(self.request, 'index.html', {'photos': photoslist})

    def post(self, request):
        form = PhotoForm(self.request.POST, self.request.FILES)
        if form.is_valid():
            photo = form.save()
            data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url}
        else:
            data = {'is_valid': False}
        return JsonResponse(data)
</code>```

答:
If I understand well, you would like to get the logon user in your view.
In Django, if the user logon successfully, then the object is available in request.user which you can use to do retrieve the records in Photo as you mentioned. </p>

```<code>def get(self, request):
    # retrieve photos from logon user
    Photo.objects.get(user=request.user)
</code>```

Body:
hello I have two difference projects one project have only authentication and other have only fileupload and upload to personal folder per user(work fine from admin mode)and I want to connect with one project.
On the second project I have create a fuction where create new personal folder for any user where want upload files using user_id,user_username (I have to many similars ways to do this function and this is for test).

that I don't know is how to take user_id or user_name of login user and how to use this in views.py to my fuction for generate_path.
I thing so maybe like this user = Photo.objects.get(user__id=user_id)but I am not sure

def generate_path(user):
    return "/{0}/img".format(user.username)

class Photo(models.Model):
     user = models.ForeignKey(to=settings.AUTH_USER_MODEL)
    file = models.FileField(upload_to=upload_to=generate_path(self.user)))

views.py

@login_required
class BasicUploadView(View):
    def get(self, request):
        photoslist = Photo.objects.all()
        return render(self.request, 'index.html', {'photos': photoslist})

    def post(self, request):
        form = PhotoForm(self.request.POST, self.request.FILES)
        if form.is_valid():
            photo = form.save()
            data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url}
        else:
            data = {'is_valid': False}
        return JsonResponse(data)

Body:
If I understand well, you would like to get the logon user in your view.
In Django, if the user logon successfully, then the object is available in request.user which you can use to do retrieve the records in Photo as you mentioned.

def get(self, request):
    # retrieve photos from logon user
    Photo.objects.get(user=request.user)


问:
C++ - removal of a node in an AVL Tree
I'm currently trying to implement an AVL tree in C++, so far I've done pretty much everything except a node removal.

1) Can someone confirm that my algorithm for removing a node is correct?

Find the node to delete in the tree

if the node has 0 child : delete the node

else, if the node has 1 child: delete the node, and re-link his child

else (2 children): find its successor, and swap the node to delete with its successor. then repeat the steps to delete the node (which is now where its successor was).

Rebalance the tree after the insertion (it'll rebalance the tree recursively...)

I've done this, but the part where I'm not sure, is the step where I delete the node. Do I have to delete the reference to the node also, or it'll be managed? (Because I've passed in parameter a Node*&, but the successor is only a Node* in the function...)

I'm not sure I'm being super clear, let me know if you need more details.

(I would post some code, but unfortunately I speak french, so you won't understand much from it, I guess)

答:
I you are coding in standard C++ then nothing will be "managed" for you. If you use smart pointers then they will take care of the deallocations for you though.

As for your interface, I suggest the remove() function takes a pointer to the node to delete. Then you don't need to bother with finding the node, as it is given. Do write a find() function though, so clients can find the node themselves.

Finally, I am not sure I follow your third case, where a node to delete has two children. In an AVL tree when a node to delete as two children you can swap it with the right-most child of the left subtree of the node to delete. Once swapped, the node to remove has exactly one or zero children, so you essentially reduced the problem to these two cases.

For example:

```<code>            20
     40            15
  60    35     18       10
80    38  30 19  17   13   8
</code>```

In the above tree if you wish to remove node 20 then you swap it with node 30 (the child of node 35):

```<code>            30
     40            15
  60    35     18       10
80    38  20 19  17   13   8
</code>```

And then remove node 20 as a child-less node. If there were no node 30 then the right-most child of the left subtree would be node 35, and you'd swap node 20 with that. Then you'd have to remove a node with a single child, which you know how to do.

Do note that until you're done with the deletion the tree is in an inconsistent state. This is important if you're working concurrently.

Title: C++ - removal of a node in an AVL Tree

Body:
I you are coding in standard C++ then nothing will be "managed" for you. If you use smart pointers then they will take care of the deallocations for you though.

As for your interface, I suggest the remove() function takes a pointer to the node to delete. Then you don't need to bother with finding the node, as it is given. Do write a find() function though, so clients can find the node themselves.

Finally, I am not sure I follow your third case, where a node to delete has two children. In an AVL tree when a node to delete as two children you can swap it with the right-most child of the left subtree of the node to delete. Once swapped, the node to remove has exactly one or zero children, so you essentially reduced the problem to these two cases.

For example:

            20
     40            15
  60    35     18       10
80    38  30 19  17   13   8

In the above tree if you wish to remove node 20 then you swap it with node 30 (the child of node 35):

            30
     40            15
  60    35     18       10
80    38  20 19  17   13   8

And then remove node 20 as a child-less node. If there were no node 30 then the right-most child of the left subtree would be node 35, and you'd swap node 20 with that. Then you'd have to remove a node with a single child, which you know how to do.

Do note that until you're done with the deletion the tree is in an inconsistent state. This is important if you're working concurrently.


问:
Background color on body, with an div on top of it
My body uses a color gradient, but on top of it, I want to have a wrapper around the whole web page (because of vertical/horizontal align). However, because of this div, the background can't be seen anymore. I tried to solve this problem by using RGBA and Opacity, but neither of them worked.

Link to JSFiddle: https://jsfiddle.net/ItsKasper_/cnpczafL/
Code:

```<code><div id='wrapper'>
<div id='list'>
    <p>test</p>
</div>
</div>
</code>```

CSS:
Couldn't get the CSS to correctly show.

Thanks in advance

答:
The body sizes with content and as the wrapper, the only direct child, is positioned absolute, its height becomes 0, but the html is the full viewport

Fiddle

```<code>html {
    background: #457fca; /* For browsers that do not support gradients */
    background: -webkit-linear-gradient(left, #457fca, #5691c8); /* For Safari 5.1 to 6.0 */
    background: -o-linear-gradient(right, #457fca, #5691c8); /* For Opera 11.1 to 12.0 */
    background: -moz-linear-gradient(right, #457fca, #5691c8); /* For Firefox 3.6 to 15 */
    background: linear-gradient(to right, #457fca, #5691c8); /* Standard syntax */
    margin: 0;
}
</code>```

If you give the body a height, height: 100vh;, it would work as well

Fiddle

```<code>body {
    height: 100vh;
    background: #457fca; /* For browsers that do not support gradients */
    background: -webkit-linear-gradient(left, #457fca, #5691c8); /* For Safari 5.1 to 6.0 */
    background: -o-linear-gradient(right, #457fca, #5691c8); /* For Opera 11.1 to 12.0 */
    background: -moz-linear-gradient(right, #457fca, #5691c8); /* For Firefox 3.6 to 15 */
    background: linear-gradient(to right, #457fca, #5691c8); /* Standard syntax */
    margin: 0;
}
</code>```

And since the wrapper has the size of the viewport, you could of course set the background on it

Fiddle

```<code>#wrapper {
    position: absolute;
    width: 100%;
    height: 100%;
    margin: 0px;
    padding: 0px;
    background: #457fca; /* For browsers that do not support gradients */
    background: -webkit-linear-gradient(left, #457fca, #5691c8); /* For Safari 5.1 to 6.0 */
    background: -o-linear-gradient(right, #457fca, #5691c8); /* For Opera 11.1 to 12.0 */
    background: -moz-linear-gradient(right, #457fca, #5691c8); /* For Firefox 3.6 to 15 */
    background: linear-gradient(to right, #457fca, #5691c8); /* Standard syntax */
}
</code>```

Body:
My body uses a color gradient, but on top of it, I want to have a wrapper around the whole web page (because of vertical/horizontal align). However, because of this div, the background can't be seen anymore. I tried to solve this problem by using RGBA and Opacity, but neither of them worked.

Link to JSFiddle: https://jsfiddle.net/ItsKasper_/cnpczafL/
Code:

test

CSS:
Couldn't get the CSS to correctly show.

Thanks in advance

Body:
The body sizes with content and as the wrapper, the only direct child, is positioned absolute, its height becomes 0, but the html is the full viewport

Fiddle

html {
    background: #457fca; /* For browsers that do not support gradients */
    background: -webkit-linear-gradient(left, #457fca, #5691c8); /* For Safari 5.1 to 6.0 */
    background: -o-linear-gradient(right, #457fca, #5691c8); /* For Opera 11.1 to 12.0 */
    background: -moz-linear-gradient(right, #457fca, #5691c8); /* For Firefox 3.6 to 15 */
    background: linear-gradient(to right, #457fca, #5691c8); /* Standard syntax */
    margin: 0;
}

If you give the body a height, height: 100vh;, it would work as well

Fiddle

body {
    height: 100vh;
    background: #457fca; /* For browsers that do not support gradients */
    background: -webkit-linear-gradient(left, #457fca, #5691c8); /* For Safari 5.1 to 6.0 */
    background: -o-linear-gradient(right, #457fca, #5691c8); /* For Opera 11.1 to 12.0 */
    background: -moz-linear-gradient(right, #457fca, #5691c8); /* For Firefox 3.6 to 15 */
    background: linear-gradient(to right, #457fca, #5691c8); /* Standard syntax */
    margin: 0;
}

And since the wrapper has the size of the viewport, you could of course set the background on it

Fiddle

#wrapper {
    position: absolute;
    width: 100%;
    height: 100%;
    margin: 0px;
    padding: 0px;
    background: #457fca; /* For browsers that do not support gradients */
    background: -webkit-linear-gradient(left, #457fca, #5691c8); /* For Safari 5.1 to 6.0 */
    background: -o-linear-gradient(right, #457fca, #5691c8); /* For Opera 11.1 to 12.0 */
    background: -moz-linear-gradient(right, #457fca, #5691c8); /* For Firefox 3.6 to 15 */
    background: linear-gradient(to right, #457fca, #5691c8); /* Standard syntax */
}


问:
How to play video on image?
I have following Image :

Now I want to place a vimeo video on this image with responsive view :

To do that I am using following css and html code :

html code :

```<code><div class="vimeo">
<article>
    <figure>
        <iframe src="https://player.vimeo.com/video/211148482?autoplay=1&title=0&byline=0&portrait=0" width="568" height="453" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
    </figure>
</article>
</div>
</code>```

CSS code :

```<code>.vimeo {
    font: 16px/1.4 Georgia, Serif;
    width: 45%;
    margin: 1px auto;
    background: url(images/bg.jpg);
    background-size: contain;
    background-repeat: no-repeat;
    position: relative;
}

pre, article style, article script {
    white-space: pre;
    display: block;
    overflow-x: auto;

}

img {
    max-width: 100%;
}
figure {
    display: block;
}
figcaption {
    display: block; text-align: center; orphans: 2;
}
</code>```

Now it looks like this image :

I want to set it on the image gray background, How can I do this ?

答:
You can avoid to use javascript but only css.

Instead of the grey color, you can set a transparent color and use the png image format. You need of css declaration background-color: transparent to see the video above a transparent color. Moreover, you need of css declaration position: absolute to overlap both image and video.

Please see also the snippet. (note that you can improve the png image)

I hope I was of any help.

```

Title: How to play video on image?

Body:
I have following Image :

Now I want to place a vimeo video on this image with responsive view :

To do that I am using following css and html code :

html code :

CSS code :

.vimeo {
    font: 16px/1.4 Georgia, Serif;
    width: 45%;
    margin: 1px auto;
    background: url(images/bg.jpg);
    background-size: contain;
    background-repeat: no-repeat;
    position: relative;
}

pre, article style, article script {
    white-space: pre;
    display: block;
    overflow-x: auto;

}

img {
    max-width: 100%;
}
figure {
    display: block;
}
figcaption {
    display: block; text-align: center; orphans: 2;
}

Now it looks like this image :

I want to set it on the image gray background, How can I do this ?

Body:
You can avoid to use javascript but only css.

Instead of the grey color, you can set a transparent color and use the png image format. You need of css declaration background-color: transparent to see the video above a transparent color. Moreover, you need of css declaration position: absolute to overlap both image and video.

Please see also the snippet. (note that you can improve the png image)

I hope I was of any help.

<div style="position: absolute; width: 882px; height: 590px;">
<img style="position: absolute; background-color: transparent; width: 100%; height: 100%;" src="https://i.stack.imgur.com/GsgXg.png">
<iframe src="https://player.vimeo.com/video/211148482?autoplay=1&title=0&byline=0&portrait=0" width="100%" height="100%" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
</div>


问:
Using numpy.unique on multiple columns of a pandas.DataFrame
I am looking to use numpy.unique to obtain the reverse unique indexes of two columns of a pandas.DataFrame.

I know how to use it on one column:

```<code>u, rev = numpy.unique(df[col], return_inverse=True)
</code>```

But I want to use it on multiple columns. For example, if the df looks like:

```<code>    0   1
0   1   1
1   1   2
2   2   1
3   2   1
4   3   1
</code>```

then I would like to get the reverse indexes:

```<code>[0,1,2,2,3]
</code>```

答:
I think you can convert columns to strings and then sum:

```<code>u, rev = np.unique(df.astype(str).values.sum(axis=1), return_inverse=True)
print (rev)
[0 1 2 2 3]
</code>```

As pointed DSM (thank you), it is dangerous.

Another solution is convert rows to tuples:

```<code>u, rev = np.unique(df.apply(tuple, axis=1), return_inverse=True)
print (rev)
[0 1 2 2 3]
</code>```

Body:
I am looking to use numpy.unique to obtain the reverse unique indexes of two columns of a pandas.DataFrame.

I know how to use it on one column:

u, rev = numpy.unique(df[col], return_inverse=True)

But I want to use it on multiple columns. For example, if the df looks like:

    0   1
0   1   1
1   1   2
2   2   1
3   2   1
4   3   1

then I would like to get the reverse indexes:

[0,1,2,2,3]

Body:
I think you can convert columns to strings and then sum:

u, rev = np.unique(df.astype(str).values.sum(axis=1), return_inverse=True)
print (rev)
[0 1 2 2 3]

As pointed DSM (thank you), it is dangerous.

Another solution is convert rows to tuples:

u, rev = np.unique(df.apply(tuple, axis=1), return_inverse=True)
print (rev)
[0 1 2 2 3]


问:
splitting a variable number of tokens with strtok_r
I'm receiving via a named pipe commands with this format:

```<code>GETIP <machine_name> \n
<process_id>

GETNAME<ip_address> \n
<process_id>

UDATA <machine_name> <ip_address>
<process_id>

DDATA <machine_name> \n
<process_id>
</code>```

So, sample strings read from the pipe are:

```<code>GETIP lolcatzmachine
1235

UDATA cheezburger 127.0.0.1
7564
</code>```

Truthfully, I don't know what the hell I'm doing here, I'm not familiar with c tokenizing. How can I alter my code to meet the requirements?

```<code>char *token;

char *commandName [10];
char machineName[200];
char ip[40];
char pid[30];

char * separator = "  ";
char *brkt; // reentrant pointer, as this tokenizing will be multithreaded

for ( ; ; ) {

 token=strtok_r(command_and_pid, separator, &brkt); //strtok_r is needed for multithreading

 commandName = strdup(token);

    //ip=strtok_r(NULL, separator, &brkt);

   //pid=strtok_r(NULL, separator, &brkt);

  if (token == NULL)
        break;
}
</code>```

答:
I ended up using a modified version of this:</p>

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int
main(int argc, char *argv[])
{
    char *str1, *str2, *token, *subtoken;
    char *saveptr1, *saveptr2;
    int j;

    if (argc != 4) {
        fprintf(stderr, "Usage: %s string delim subdelim\n",
                argv[0]);
        exit(EXIT_FAILURE);
    }

    for (j = 1, str1 = argv[1]; ; j++, str1 = NULL) {

       token = strtok_r(str1, argv[2], &saveptr1);

       if (token == NULL)
            break;
        printf("%d: %s\n", j, token);

        for (str2 = token; ; str2 = NULL) {
            subtoken = strtok_r(str2, argv[3], &saveptr2);
            if (subtoken == NULL)
                break;
            printf("     --> %s\n", subtoken);
        }
    }

    exit(EXIT_SUCCESS);
} /* main */
</code>```

Body:
I'm receiving via a named pipe commands with this format:

GETIP <machine_name> \n
<process_id>

GETNAME<ip_address> \n
<process_id>

UDATA <machine_name> <ip_address>
<process_id>

DDATA <machine_name> \n
<process_id>

So, sample strings read from the pipe are:

GETIP lolcatzmachine
1235

UDATA cheezburger 127.0.0.1
7564

Truthfully, I don't know what the hell I'm doing here, I'm not familiar with c tokenizing. How can I alter my code to meet the requirements?

char *token;

char *commandName [10];
char machineName[200];
char ip[40];
char pid[30];

char * separator = "  ";
char *brkt; // reentrant pointer, as this tokenizing will be multithreaded

for ( ; ; ) {

 token=strtok_r(command_and_pid, separator, &brkt); //strtok_r is needed for multithreading

 commandName = strdup(token);

    //ip=strtok_r(NULL, separator, &brkt);

   //pid=strtok_r(NULL, separator, &brkt);

  if (token == NULL)
        break;
}

Body:
I ended up using a modified version of this:

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

int
main(int argc, char *argv[])
{
    char *str1, *str2, *token, *subtoken;
    char *saveptr1, *saveptr2;
    int j;

    if (argc != 4) {
        fprintf(stderr, "Usage: %s string delim subdelim\n",
                argv[0]);
        exit(EXIT_FAILURE);
    }

    for (j = 1, str1 = argv[1]; ; j++, str1 = NULL) {

       token = strtok_r(str1, argv[2], &saveptr1);

       if (token == NULL)
            break;
        printf("%d: %s\n", j, token);

        for (str2 = token; ; str2 = NULL) {
            subtoken = strtok_r(str2, argv[3], &saveptr2);
            if (subtoken == NULL)
                break;
            printf("     --> %s\n", subtoken);
        }
    }

    exit(EXIT_SUCCESS);
} /* main */


问:
CSS3: Nested flexbox form messes up spacing
I am trying to make a flexbox form with label and input on the same line. Using flex-basis and and other flex properties gives the expected and desired result.

However, if one has to nest that flexbox inside another element with a set width, the whole thing falls apart.

E.g. see the attached fiddle and run it with and without the div {width:30%}

How can I get around this?

fiddle

答:
Try this flexible flexbox Form

@import url("https://fonts.googleapis.com/css?family=Open+Sans:300,800");
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html {
  font-family: "Open Sans", helvetica, sans-serif;
  font-size: 24px;
  color: rgba(0, 0, 0, 0.5);
}

body {
  background: #f9f9f9;
}

main {
  position: relative;
  width: 100%;
}

h1 {
  padding: 20px 0 0;
  font-weight: 600;
  font-size: 4rem;
}

h1,
h5 {
  text-align: center;
}

h5 {
  margin: 0 0 20px;
}

.ruler {
  position: relative;
  display: block;
  left: 50%;
  margin: 0 0 30px -320px;
  width: 640px;
  height: 6px;
  line-height: -20px;
  background: rgba(0, 0, 0, 0.1);
}

.ruler span {
  display: block;
  position: absolute;
  padding: 8px;
  width: 80px;
  top: -22px;
  left: 280px;
  text-align: center;
  background: #efefef;
}

textarea,
input {
  display: inline-block;
  font-family: "Open Sans", helvetica, sans-serif;
  margin: 10px;
  padding: 10px;
  background: rgba(255, 255, 255, 0.8);
  border: 2px solid rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  font-size: 1rem;
  font-weight: 300;
  color: #454545;
}

textarea:focus,
input:focus {
  outline: 0;
}

textarea {
  height: 300px;
}

.flexy-parent {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  max-width: 800px;
  margin: 0 auto;
  -ms-flex-flow: row wrap;
  flex-flow: row wrap;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  -ms-flex-line-pack: start;
  align-content: flex-start;
}

.flexy-item {
  -webkit-box-flex: 1;
  -ms-flex: 1 0 300px;
  flex: 1 0 300px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
  <h1>Flex Form</h1>
  <h5>SIZE WINDOW</h5>
  <div class="ruler"><span>640px</span></div>
  <section class="flexy-parent">
    <input class="flexy-item" type="text" placeholder="Responsive input fields...">
    <input class="flexy-item" type="text" placeholder="will break at 640px...">
  </section>
  <section class="flexy-parent">
    <input class="flexy-item" type="text" placeholder="flex-grow: 1">
    <input class="flexy-item" type="text" placeholder="flex-basis: 300px">
  </section>
  <section class="flexy-parent">
    <textarea class="flexy-item" placeholder="And thanks to flexbox, everything stays nice and tidy."></textarea>
  </section>
</main></code>```

Body:
Try this flexible flexbox Form

@import url("https://fonts.googleapis.com/css?family=Open+Sans:300,800");
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html {
  font-family: "Open Sans", helvetica, sans-serif;
  font-size: 24px;
  color: rgba(0, 0, 0, 0.5);
}

body {
  background: #f9f9f9;
}

main {
  position: relative;
  width: 100%;
}

h1 {
  padding: 20px 0 0;
  font-weight: 600;
  font-size: 4rem;
}

h1,
h5 {
  text-align: center;
}

h5 {
  margin: 0 0 20px;
}

.ruler {
  position: relative;
  display: block;
  left: 50%;
  margin: 0 0 30px -320px;
  width: 640px;
  height: 6px;
  line-height: -20px;
  background: rgba(0, 0, 0, 0.1);
}

.ruler span {
  display: block;
  position: absolute;
  padding: 8px;
  width: 80px;
  top: -22px;
  left: 280px;
  text-align: center;
  background: #efefef;
}

textarea,
input {
  display: inline-block;
  font-family: "Open Sans", helvetica, sans-serif;
  margin: 10px;
  padding: 10px;
  background: rgba(255, 255, 255, 0.8);
  border: 2px solid rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  font-size: 1rem;
  font-weight: 300;
  color: #454545;
}

textarea:focus,
input:focus {
  outline: 0;
}

textarea {
  height: 300px;
}

.flexy-parent {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  max-width: 800px;
  margin: 0 auto;
  -ms-flex-flow: row wrap;
  flex-flow: row wrap;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  -ms-flex-line-pack: start;
  align-content: flex-start;
}

.flexy-item {
  -webkit-box-flex: 1;
  -ms-flex: 1 0 300px;
  flex: 1 0 300px;
}

<main>
  <h1>Flex Form</h1>
  <h5>SIZE WINDOW</h5>
  <div class="ruler"><span>640px</span></div>
  <section class="flexy-parent">
    <input class="flexy-item" type="text" placeholder="Responsive input fields...">
    <input class="flexy-item" type="text" placeholder="will break at 640px...">
  </section>
  <section class="flexy-parent">
    <input class="flexy-item" type="text" placeholder="flex-grow: 1">
    <input class="flexy-item" type="text" placeholder="flex-basis: 300px">
  </section>
  <section class="flexy-parent">
    <textarea class="flexy-item" placeholder="And thanks to flexbox, everything stays nice and tidy."></textarea>
  </section>
</main>


问:
Which module called my DLL exported function?

Background

I'm developing a C++ windows DLL module that exports a single function

```<code>__declspec(dllexport) void Run()
</code>```

Motivation

I would like to implement some sort of accessing rights to my function. I wish to prevent unauthorized modules from activating my DLL proc.

I don't need a robust/bullet proof mechanism. I only like to "defend" this proc from other modules running under my own app.

Approach

Get the calling module name and decide based on the name if access is granted.

Question

Would this approach suffice?

if so, how do I get the name of the calling module?

答:
if so, how do I get the name of the calling module?

get return address by call _ReturnAddress

get base address of the image that contains this return address -
RtlPcToFileHeader

finally call GetModuleFileName function

so code can be like this

```<code>HMODULE hmod;
if (RtlPcToFileHeader(_ReturnAddress(), (void**)&hmod))
{
    WCHAR sz[MAX_PATH];
    if (GetModuleFileName(hmod, sz, MAX_PATH))
    {
        DbgPrint("%p %S\n", hmod, sz);
    }
}
</code>```

about - are this work in XP ? yes, but with one note. _ReturnAddress is CL intrinsic - so not depended from os version (for say gcc exist  __builtin_return_address (0) ) GetModuleFileName also very old api function and exist in win2000, xp, everywhere. about RtlPcToFileHeader
- it exported (and implemented) in ntdll.dll in all windows versions from xp to latest. also begin from win2003 it also exported from kernel32.dll but implementation here - simply jump to ntdll.RtlPcToFileHeader - so if want use this on xp also - link with ntdll.lib and place it before kernel32.lib in libs order or can get it it runtime by GetProcAddress(GetModuleHandle(L"ntdll"), "RtlPcToFileHeader");

or even if somebody afraid that RtlPcToFileHeader will be removed from ntdll (this is of course no) can use this
    GetProcAddress(GetModuleHandle(g_xp ? L"ntdll" : L"kernel32"), "RtlPcToFileHeader");

Body:
Background

I'm developing a C++ windows DLL module that exports a single function

__declspec(dllexport) void Run()

Motivation

I would like to implement some sort of accessing rights to my function. I wish to prevent unauthorized modules from activating my DLL proc.

I don't need a robust/bullet proof mechanism. I only like to "defend" this proc from other modules running under my own app.

Approach

Get the calling module name and decide based on the name if access is granted.

Question

Would this approach suffice?

if so, how do I get the name of the calling module?

Body:
if so, how do I get the name of the calling module?

get return address by call _ReturnAddress

get base address of the image that contains this return address -
RtlPcToFileHeader

finally call GetModuleFileName function

so code can be like this

HMODULE hmod;
if (RtlPcToFileHeader(_ReturnAddress(), (void**)&hmod))
{
    WCHAR sz[MAX_PATH];
    if (GetModuleFileName(hmod, sz, MAX_PATH))
    {
        DbgPrint("%p %S\n", hmod, sz);
    }
}

about - are this work in XP ? yes, but with one note. _ReturnAddress is CL intrinsic - so not depended from os version (for say gcc exist  __builtin_return_address (0) ) GetModuleFileName also very old api function and exist in win2000, xp, everywhere. about RtlPcToFileHeader
- it exported (and implemented) in ntdll.dll in all windows versions from xp to latest. also begin from win2003 it also exported from kernel32.dll but implementation here - simply jump to ntdll.RtlPcToFileHeader - so if want use this on xp also - link with ntdll.lib and place it before kernel32.lib in libs order or can get it it runtime by GetProcAddress(GetModuleHandle(L"ntdll"), "RtlPcToFileHeader");

or even if somebody afraid that RtlPcToFileHeader will be removed from ntdll (this is of course no) can use this
    GetProcAddress(GetModuleHandle(g_xp ? L"ntdll" : L"kernel32"), "RtlPcToFileHeader");


问:
How to change the back button color on md and ws in Ionic 2?
I was able to set the back button icon and remove the text using app config but how can I set the color for the icon? Ios picks up the primary/secondary color but it shows up as black in Android and Windows.

```<code>imports: [
IonicModule.forRoot(MyApp,{
  'backButtonText':'',
  'backButtonIcon':'arrow-back',
  'pageTransition':'ios'

},{}
)]
</code>```

答:
You need to give it as shown below on your component's .scss file.

```<code>.ws,
.md {
  .back-button {
            color: red;//what ever the color you like
        }
}
</code>```

If you need to do it globally then You have to do it as shown below.

Note: I don't like to use !important hack.But unfortunately, it's not working without that.

app.scss

```<code>.md,
.wp {
    .back-button {
        color: red !important;//what ever the color you like
    }
}
</code>```

Body:
I was able to set the back button icon and remove the text using app config but how can I set the color for the icon? Ios picks up the primary/secondary color but it shows up as black in Android and Windows.

imports: [
IonicModule.forRoot(MyApp,{
  'backButtonText':'',
  'backButtonIcon':'arrow-back',
  'pageTransition':'ios'

},{}
)]

Body:
You need to give it as shown below on your component's .scss file.

.ws,
.md {
  .back-button {
            color: red;//what ever the color you like
        }
}

If you need to do it globally then You have to do it as shown below.

Note: I don't like to use !important hack.But unfortunately, it's not working without that.

app.scss

.md,
.wp {
    .back-button {
        color: red !important;//what ever the color you like
    }
}


问:
arraylist undefined method for type
i have a method wich takes an ArrayList as argument.
the class song has differents methods like getTitle(),getInterpret(),toString(),toString2()...

```<code>public class Song implements Comparable<Song>{

private String title;
private String interpret;

public Song(String title,String interpret){

    this.title=title;
    this.interpret=interpret;

}

public String getTitle() {
    return title;
}

public String getInterpret() {
    return interpret;
}

public String toString2(){
    return title+" - "+interpret;
}

@Override
public int compareTo(Song otherSong) {

    return title.compareToIgnoreCase(otherSong.getTitle());
}

public String toString() {

    return interpret+" - "+title;
}
</code>```

}

the method printList takes an ArrayList of Song as argument:

```<code>public <Song> void printList(ArrayList<Song> songList,String sortBy){

    JLabel track;

    for(int i=0;i<songList.size();i++){

        if(sortBy=="Artist"){
        track = new JLabel("\n- "+songList.get(i).toString());}

        else if(sortBy=="Song"){
        track = new JLabel("\n- "+songList.get(i).toString2());}

    }
</code>```

i have an error on songList.get(i).toString2(), the method toString2() is undefined for type Song, it seems like i can only access to the method of the class Object.

can somebody help please?

答:
You've made your method generic, and chose to name the generic type Song. It shouldn't be generic:

```<code>public void printList(ArrayList<Song> songList,String sortBy){
</code>```

Also, compare strings with equals(), not ==.

Title: arraylist undefined method for type

Body:
i have a method wich takes an ArrayList as argument.
the class song has differents methods like getTitle(),getInterpret(),toString(),toString2()...

public class Song implements Comparable<Song>{

private String title;
private String interpret;

public Song(String title,String interpret){

    this.title=title;
    this.interpret=interpret;

}

public String getTitle() {
    return title;
}

public String getInterpret() {
    return interpret;
}

public String toString2(){
    return title+" - "+interpret;
}

@Override
public int compareTo(Song otherSong) {

    return title.compareToIgnoreCase(otherSong.getTitle());
}

public String toString() {

    return interpret+" - "+title;
}

}

the method printList takes an ArrayList of Song as argument:

public <Song> void printList(ArrayList<Song> songList,String sortBy){

    JLabel track;

    for(int i=0;i<songList.size();i++){

        if(sortBy=="Artist"){
        track = new JLabel("\n- "+songList.get(i).toString());}

        else if(sortBy=="Song"){
        track = new JLabel("\n- "+songList.get(i).toString2());}

    }

i have an error on songList.get(i).toString2(), the method toString2() is undefined for type Song, it seems like i can only access to the method of the class Object.

can somebody help please?

Body:
You've made your method generic, and chose to name the generic type Song. It shouldn't be generic:

public void printList(ArrayList<Song> songList,String sortBy){

Also, compare strings with equals(), not ==.


问:
How to get the value of a custom attribute in angular js
I have created a custom attribute called test in angular js. When I write the test attribute just beside the ng-controller keyword i.d.

 then I can access that test from the controller by using alert($attrs.test). But if I write the custom attribute test other than beside of the ng-controller keyword, I can't access that. i.e.

In this case I got undefined in alert($attrs.test)

Full code...

```<code><html>
<script src="angular.min.js"></script>
<body ng-app="myApp">

<div ng-controller="kumar" >
 <button ng-click="check()" test="def">Click</button>
</div>

 <script>
 var app = angular.module("myApp", []);
 app.directive("test", function() {
  return {
    //template : "<h1>Hello</h1>"
  };
});

 app.controller("kumar",function($scope,$attrs){
    $scope.check=function(){
      alert(JSON.stringify($attrs.test));   //getting undefined. I
                      //should get def.
  }
});
</script>

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

答:
You can get the element on click if you pass $event in ng-click, i.e. ng-click="check($event)" and can get the attribute from $event.target.

Check fiddle : https://jsfiddle.net/ayusharma/xb63g9ca/

JS

```<code>app.controller('myCtrl', function($scope) {
   $scope.clickMe = function(evt) {
     console.log(evt.target.getAttribute('test'))
   }
});
</code>```

HTML

```<code><div ng-controller="myCtrl">
   <div ng-click="clickMe($event)" test="abc">Click on Me</div>
</div>
</code>```

Body:
I have created a custom attribute called test in angular js. When I write the test attribute just beside the ng-controller keyword i.d.

 then I can access that test from the controller by using alert($attrs.test). But if I write the custom attribute test other than beside of the ng-controller keyword, I can't access that. i.e.

In this case I got undefined in alert($attrs.test)

Full code...

 <button ng-click="check()" test="def">Click</button>

Body:
You can get the element on click if you pass $event in ng-click, i.e. ng-click="check($event)" and can get the attribute from $event.target.

Check fiddle : https://jsfiddle.net/ayusharma/xb63g9ca/

JS

app.controller('myCtrl', function($scope) {
   $scope.clickMe = function(evt) {
     console.log(evt.target.getAttribute('test'))
   }
});

HTML

<div ng-controller="myCtrl">
   <div ng-click="clickMe($event)" test="abc">Click on Me</div>
</div>


问:
Add .well-known to asp.net core
I want to have a .well-known directory in my root for letsencrypt renewals.

I have added a route to .well-known like so:

```<code> app.UseStaticFiles(new StaticFileOptions
        {
            FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @".well-known")),
            RequestPath = new PathString("/.well-known"),
            ServeUnknownFileTypes = true // serve extensionless file
        });
</code>```

I added a direcotry inside my wwwroot called .well-known but it never gets copied to the output when I publish.

I tried adding a file to it and also edit csproj:

```<code>  <ItemGroup>
    <Content Include="wwwroot\.well-known\" />
  </ItemGroup>
</code>```

Every time I publish I have to manually create the directory.  How do I get it automatically added to the wwwroot?

答:
I tried adding a file to it and also edit csproj:

```<code><ItemGroup>
  <Content Include="wwwroot\.well-known\" />
</ItemGroup>
</code>```

You can't copy over folders via Content, only files. You have to change it to

```<code><ItemGroup>
  <Content Include="wwwroot\**">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </Content>
<ItemGroup>
</code>```

and like mentioned in the comments, you need to put an empty dummy file inside.

Title: Add .well-known to asp.net core

Body:
I want to have a .well-known directory in my root for letsencrypt renewals.

I have added a route to .well-known like so:

 app.UseStaticFiles(new StaticFileOptions
        {
            FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @".well-known")),
            RequestPath = new PathString("/.well-known"),
            ServeUnknownFileTypes = true // serve extensionless file
        });

I added a direcotry inside my wwwroot called .well-known but it never gets copied to the output when I publish.

I tried adding a file to it and also edit csproj:

  <ItemGroup>
    <Content Include="wwwroot\.well-known\" />
  </ItemGroup>

Every time I publish I have to manually create the directory.  How do I get it automatically added to the wwwroot?

Body:
I tried adding a file to it and also edit csproj:

<ItemGroup>
  <Content Include="wwwroot\.well-known\" />
</ItemGroup>

You can't copy over folders via Content, only files. You have to change it to

<ItemGroup>
  <Content Include="wwwroot\**">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </Content>
<ItemGroup>

and like mentioned in the comments, you need to put an empty dummy file inside.


问:
How to get pixel/offsite conversion stats from Facebook's ads API?
I'm using the Python SDK for the Facebook ads api to get ad performance reports for Facebook ad campaigns.

The problem is that I can't find a way to get the number of pixel/offsite conversions, and I'm not even sure about where to look for it (campaign, adset, adgroup,ad creative..)
When I get stats on any level it is not included under "actions".

I looked through the documentation and only saw explanations for creating and defining pixels.

I'd appreciate any help you can provide.

答:
You can get these information from actions field of insight of each adset or ads.
For example: here is my command in facebook's developer site:


问:
Apply a method to a list of objects in parallel using multi-processing
I have created a class with a number of methods. One of the methods is very time consuming, my_process, and I'd like to do that method in parallel. I came across Python Multiprocessing - apply class method to a list of objects but I'm not sure how to apply it to my problem, and what effect it will have on the other methods of my class.

```<code>class MyClass():
    def __init__(self, input):
        self.input = input
        self.result = int

    def my_process(self, multiply_by, add_to):
        self.result = self.input * multiply_by
        self._my_sub_process(add_to)
        return self.result

    def _my_sub_process(self, add_to):
        self.result += add_to

list_of_numbers = range(0, 5)
list_of_objects = [MyClass(i) for i in list_of_numbers]
list_of_results = [obj.my_process(100, 1) for obj in list_of_objects] # multi-process this for-loop

print list_of_numbers
print list_of_results

[0, 1, 2, 3, 4]
[1, 101, 201, 301, 401]
</code>```

答:
Generally the easiest way to run the same calculation in parallel is the map method of a multiprocessing.Pool (or the as_completed function from concurrent.futures in Python 3).

However, the map method applies a function that only takes one argument to an iterable of data using multiple processes.

So this function cannot be a normal method, because that requires at least two arguments; it must also include self! It could be a staticmethod, however. See also this answer for a more in-depth explanation.

Body:
I have created a class with a number of methods. One of the methods is very time consuming, my_process, and I'd like to do that method in parallel. I came across Python Multiprocessing - apply class method to a list of objects but I'm not sure how to apply it to my problem, and what effect it will have on the other methods of my class.

class MyClass():
    def __init__(self, input):
        self.input = input
        self.result = int

    def my_process(self, multiply_by, add_to):
        self.result = self.input * multiply_by
        self._my_sub_process(add_to)
        return self.result

    def _my_sub_process(self, add_to):
        self.result += add_to

list_of_numbers = range(0, 5)
list_of_objects = [MyClass(i) for i in list_of_numbers]
list_of_results = [obj.my_process(100, 1) for obj in list_of_objects] # multi-process this for-loop

print list_of_numbers
print list_of_results

[0, 1, 2, 3, 4]
[1, 101, 201, 301, 401]


问:
How can I make Sublime Text 3 use my $PATH?
I have a sublime plugin which executes a script that starts with

```<code>#!/usr/bin/env php
</code>```

Now, when I execute this script from a terminal it will use the php I have in my $PATH (installed by phpbrew) but when the sublime plugin executes the script it will use the php binary installed by macOS (Sierra), which is not the same PHP version. (Note that the plugin does not specify which binary to use, it is resolved by #!/usr/bin/env php when executing the script).

How can I make Sublime respect my $PATH settings?

Edit: I changed #!/usr/bin/env php to #!/path/to/my/php/version in the script that was going to be executed and it works as a work-around for now.

答:
There appear to be some known problems with Sublime's PATH settings on macOS. There is a plugin for it at Git:

https://github.com/int3h/SublimeFixMacPath

Body:
I have a sublime plugin which executes a script that starts with

#!/usr/bin/env php

Now, when I execute this script from a terminal it will use the php I have in my $PATH (installed by phpbrew) but when the sublime plugin executes the script it will use the php binary installed by macOS (Sierra), which is not the same PHP version. (Note that the plugin does not specify which binary to use, it is resolved by #!/usr/bin/env php when executing the script).

How can I make Sublime respect my $PATH settings?

Edit: I changed #!/usr/bin/env php to #!/path/to/my/php/version in the script that was going to be executed and it works as a work-around for now.


问:
C++ 9 :: Casting "System::Object ^ sender" to Control type
This time in C++ 9 (VS2008) I am attempting to cast a "System::Object ^ sender" to the Control type that it represents.

This is specifically in a TextBox_TextChanged event function.

I know this works fine in C# but I'm getting errors when I try it in C++ and I can't seem to find the equivalent for C++.

C++ Code that is giving me errors . . .

```<code>System::Void txtEmplNum_TextChanged(System::Object^  sender, System::EventArgs^  e)
{
    TextBox thisBox = sender as TextBox ;
}
</code>```

And the error that results . . .

```<code>Error   1   error C2582: 'operator =' function is unavailable in 'System::Windows::Forms::TextBox'  c:\projects\nms\badgescan\frmMain.h 673 BadgeScan
</code>```

Any ideas are welcome.

Thanks!

答:
I think you might want to try this:</p>

```<code>System::Void txtEmplNum_TextChanged(System::Object^  sender, System::EventArgs^  e)
{
    TextBox^ thisBox = safe_cast<TextBox^>(sender);
}
</code>```

Body:
This time in C++ 9 (VS2008) I am attempting to cast a "System::Object ^ sender" to the Control type that it represents.

This is specifically in a TextBox_TextChanged event function.

I know this works fine in C# but I'm getting errors when I try it in C++ and I can't seem to find the equivalent for C++.

C++ Code that is giving me errors . . .

System::Void txtEmplNum_TextChanged(System::Object^  sender, System::EventArgs^  e)
{
    TextBox thisBox = sender as TextBox ;
}

And the error that results . . .

Error   1   error C2582: 'operator =' function is unavailable in 'System::Windows::Forms::TextBox'  c:\projects\nms\badgescan\frmMain.h 673 BadgeScan

Any ideas are welcome.

Thanks!

Body:
I think you might want to try this:

System::Void txtEmplNum_TextChanged(System::Object^  sender, System::EventArgs^  e)
{
    TextBox^ thisBox = safe_cast<TextBox^>(sender);
}