问:
Edit __init__ method properties into Metaclasse with exec and setattr
I try to modify the __init__ function of a class in the purpose to set as property, the inherited class property, and be able to init the inherited class from the sub class.
It should working like this :

```<code>class B():
    def __init__(self, b:str):
        self.b = b

class Foo(B,metaclass=Meta):
    def __init__(self,yolo, name ='empty', surname = None):
        self.name = name
        self.surname= surname
x = Foo('yolo',100)
print(x.b)

>>>100
</code>```

How it is work ?:

- first, in the Metaclass I create two dict __CODE__, __ARGS__, where i'm gathering the
code of the function and for the same function, the args and kwargsof the actual class and inherited class in __bases__ .

- second, I parse the code of the __init__ function, I replace the property by those which is the merging of the property of the actual function and those from the __init__in the inherited class. then I add as 2nd row, the superchargeof the inherited class, where I pass through its own property.

- lastly , I compileand execthe definition of the new function, then I use setattr to override the actual __init__function
here come my Metaclasses implementation :

```<code>
import re
from inspect import Parameter
#get all property of function f and return it as list and dict
def get_args(f):
    args = list()
    kwargs = dict()
    for param in inspect.signature(f).parameters.values():
        if (param.kind == param.POSITIONAL_OR_KEYWORD):
            if param.default ==Parameter.empty:
                args.append(param.name)
            else:
                kwargs[param.name]= param.default
    return args, kwargs
# take a dict of kwargs and return kwargs format to pass in function as string
def  compileKwargs(dct):
    string =""
    poke = False
    for k, o  in dct.items():
        if type(o) == str:
            string+= k+"='"+o+"', "
        else:
            string+= k+"="+str(o)+", "

    return string

def stringArgs(liste):
    return " ".join([e+"," for e in liste])

#merge args of the function 1 and the function 2
def compileArgs(liste1,liste2):
    liste1.extend([e for e in liste2 if e not in liste1])
    return liste1
#take a function code as string, and change its name between 'def ' and '('
def editFuncName(actual: str, replace:str):
    print('EDITFUNCNAME')
    print(actual)
    string = re.sub('(?<=def ).*?(?=\()',replace, actual)
    print('string', string)
    return string

import inspect
from textwrap import dedent, indent
#re indent the code  as it's class function it's once to often indented
def processCode(code : list):
    string=""
    #print('processcode')
    for i,e  in enumerate(code):
        #print('row', e)
        #print('dedent', e)
        if i != 0:
            string+=indent(dedent(e),'\t')
        else :
            string+=dedent(e)
    return string

class Meta(type):
    def __init__(cls, name, bases, dct):
        #x = super().__new__(cls, name, bases, dct)
        import inspect
        import re
        #print('name : {} \nbases : {} \ndct : {}'.format(name, bases, dct))
        setattr(cls,'_CODE_', dict())
        func = cls.__init__
        cls._CODE_[func.__name__]= inspect.getsourcelines(func)
        args2 =get_args(cls.__bases__[0].__init__)

        setattr(cls,'_ARGS_', dict())
        cls._ARGS_[func.__name__]=[get_args(func), args2]
        #print("ARGS", cls._ARGS_)

        #print('+++++++',cls._NAMI)
        lines = cls._CODE_['__init__']
        #print(lines)
        string= lines[0][0]
        arg, kwarg = cls._ARGS_['__init__'][0]
        arg2, kwarg2 = cls._ARGS_['__init__'][1]
        #print(kwarg, kwarg2)
        #print(arg, arg2)
        #print(compileArgs(arg, arg2))
        comparg = stringArgs(compileArgs(arg, arg2))

        dct = {**kwarg ,**kwarg2}
        #print(dct)
        newargs = comparg + compileKwargs(dct)
        string = re.sub('(?<=\().*?(?=\))',newargs, string)

        superarg =stringArgs(arg2) + compileKwargs(kwarg2)
        #print(superarg)
        superx = "super({},self).{}({})\n".format(cls.__name__, func.__name__, superarg)

        code = lines[0]
        #print('LINE DEF', code[0])
        code[0]= editFuncName(string, '__init__')
        code.insert(1, superx)

        print('code:',code)
        codestr  = processCode(code)
        print('précompile', codestr)
        comp = compile(codestr, '<string>','exec')
        print(comp)
        exec(comp)
        #exec(codestr)
        setattr(cls, '__init__', eval('__init__'))
</code>```

When it come to test, I got some error even if everything seem to be well set

first test :

```<code>x = Foo('yolo',100)

>>>
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
 in
----> 1 x = Foo('e',b = 1)

 in __init__(self, yolo, b, name, surname)

TypeError: __init__() takes 2 positional arguments but 3 were given
</code>```

second test :

```<code>x = Foo('yolo')

>>>
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
 in
----> 1 x = Foo('yolo')

TypeError: __init__() missing 1 required positional argument: 'b'
</code>```

I noticed too that I'm unable to getsource code from the overrided __init__function now

```<code>print(inspect.getsource(B.__init__))
print(inspect.getsource(Foo.__init__))

>>>def __init__(self, b:str):
...        self.b = b

---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
 in
      1 print(inspect.getsource(B.__init__))
----> 2 print(inspect.getsource(Foo.__init__))

/anaconda3/envs/Demiurge/lib/python3.7/inspect.py in getsource(object)
    971     or code object.  The source code is returned as a single string.  An
    972     OSError is raised if the source code cannot be retrieved."""
--> 973     lines, lnum = getsourcelines(object)
    974     return ''.join(lines)
    975

/anaconda3/envs/Demiurge/lib/python3.7/inspect.py in getsourcelines(object)
    953     raised if the source code cannot be retrieved."""
    954     object = unwrap(object)
--> 955     lines, lnum = findsource(object)
    956
    957     if istraceback(object):

/anaconda3/envs/Demiurge/lib/python3.7/inspect.py in findsource(object)
    784         lines = linecache.getlines(file)
    785     if not lines:
--> 786         raise OSError('could not get source code')
    787
    788     if ismodule(object):

OSError: could not get source code
</code>```

答:
I found the solution, as I try to set method inner the class , I need to bound the method with itself : instead of setattr(cls, '__init__', eval('__init__')) , (which  is working if it's done outside the class ) I set  : cls.__init__ = types.MethodType(eval('tempo'), cls)

It is working perfectly.

My solution is referring to this one : exec to add a function into a class

Body:
I try to modify the __init__ function of a class in the purpose to set as property, the inherited class property, and be able to init the inherited class from the sub class.
It should working like this :

class B():
    def __init__(self, b:str):
        self.b = b

class Foo(B,metaclass=Meta):
    def __init__(self,yolo, name ='empty', surname = None):
        self.name = name
        self.surname= surname
x = Foo('yolo',100)
print(x.b)

>>>100

How it is work ?:

- first, in the Metaclass I create two dict __CODE__, __ARGS__, where i'm gathering the
code of the function and for the same function, the args and kwargsof the actual class and inherited class in __bases__ .

- second, I parse the code of the __init__ function, I replace the property by those which is the merging of the property of the actual function and those from the __init__in the inherited class. then I add as 2nd row, the superchargeof the inherited class, where I pass through its own property.

- lastly , I compileand execthe definition of the new function, then I use setattr to override the actual __init__function
here come my Metaclasses implementation :

import re
from inspect import Parameter
#get all property of function f and return it as list and dict
def get_args(f):
    args = list()
    kwargs = dict()
    for param in inspect.signature(f).parameters.values():
        if (param.kind == param.POSITIONAL_OR_KEYWORD):
            if param.default ==Parameter.empty:
                args.append(param.name)
            else:
                kwargs[param.name]= param.default
    return args, kwargs
# take a dict of kwargs and return kwargs format to pass in function as string
def  compileKwargs(dct):
    string =""
    poke = False
    for k, o  in dct.items():
        if type(o) == str:
            string+= k+"='"+o+"', "
        else:
            string+= k+"="+str(o)+", "

    return string

def stringArgs(liste):
    return " ".join([e+"," for e in liste])

#merge args of the function 1 and the function 2
def compileArgs(liste1,liste2):
    liste1.extend([e for e in liste2 if e not in liste1])
    return liste1
#take a function code as string, and change its name between 'def ' and '('
def editFuncName(actual: str, replace:str):
    print('EDITFUNCNAME')
    print(actual)
    string = re.sub('(?<=def ).*?(?=\()',replace, actual)
    print('string', string)
    return string

import inspect
from textwrap import dedent, indent
#re indent the code  as it's class function it's once to often indented
def processCode(code : list):
    string=""
    #print('processcode')
    for i,e  in enumerate(code):
        #print('row', e)
        #print('dedent', e)
        if i != 0:
            string+=indent(dedent(e),'\t')
        else :
            string+=dedent(e)
    return string

class Meta(type):
    def __init__(cls, name, bases, dct):
        #x = super().__new__(cls, name, bases, dct)
        import inspect
        import re
        #print('name : {} \nbases : {} \ndct : {}'.format(name, bases, dct))
        setattr(cls,'_CODE_', dict())
        func = cls.__init__
        cls._CODE_[func.__name__]= inspect.getsourcelines(func)
        args2 =get_args(cls.__bases__[0].__init__)

        setattr(cls,'_ARGS_', dict())
        cls._ARGS_[func.__name__]=[get_args(func), args2]
        #print("ARGS", cls._ARGS_)

        #print('+++++++',cls._NAMI)
        lines = cls._CODE_['__init__']
        #print(lines)
        string= lines[0][0]
        arg, kwarg = cls._ARGS_['__init__'][0]
        arg2, kwarg2 = cls._ARGS_['__init__'][1]
        #print(kwarg, kwarg2)
        #print(arg, arg2)
        #print(compileArgs(arg, arg2))
        comparg = stringArgs(compileArgs(arg, arg2))

        dct = {**kwarg ,**kwarg2}
        #print(dct)
        newargs = comparg + compileKwargs(dct)
        string = re.sub('(?<=\().*?(?=\))',newargs, string)

        superarg =stringArgs(arg2) + compileKwargs(kwarg2)
        #print(superarg)
        superx = "super({},self).{}({})\n".format(cls.__name__, func.__name__, superarg)

        code = lines[0]
        #print('LINE DEF', code[0])
        code[0]= editFuncName(string, '__init__')
        code.insert(1, superx)

        print('code:',code)
        codestr  = processCode(code)
        print('précompile', codestr)
        comp = compile(codestr, '<string>','exec')
        print(comp)
        exec(comp)
        #exec(codestr)
        setattr(cls, '__init__', eval('__init__'))

When it come to test, I got some error even if everything seem to be well set

first test :

x = Foo('yolo',100)

>>>
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
 in
----> 1 x = Foo('e',b = 1)

 in __init__(self, yolo, b, name, surname)

TypeError: __init__() takes 2 positional arguments but 3 were given

second test :

x = Foo('yolo')

>>>
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
 in
----> 1 x = Foo('yolo')

TypeError: __init__() missing 1 required positional argument: 'b'

I noticed too that I'm unable to getsource code from the overrided __init__function now

print(inspect.getsource(B.__init__))
print(inspect.getsource(Foo.__init__))

>>>def __init__(self, b:str):
...        self.b = b

---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
 in
      1 print(inspect.getsource(B.__init__))
----> 2 print(inspect.getsource(Foo.__init__))

/anaconda3/envs/Demiurge/lib/python3.7/inspect.py in getsource(object)
    971     or code object.  The source code is returned as a single string.  An
    972     OSError is raised if the source code cannot be retrieved."""
--> 973     lines, lnum = getsourcelines(object)
    974     return ''.join(lines)
    975

/anaconda3/envs/Demiurge/lib/python3.7/inspect.py in getsourcelines(object)
    953     raised if the source code cannot be retrieved."""
    954     object = unwrap(object)
--> 955     lines, lnum = findsource(object)
    956
    957     if istraceback(object):

/anaconda3/envs/Demiurge/lib/python3.7/inspect.py in findsource(object)
    784         lines = linecache.getlines(file)
    785     if not lines:
--> 786         raise OSError('could not get source code')
    787
    788     if ismodule(object):

OSError: could not get source code


来源: stackexchange

问:
Load PNG and read pixels in PHP without GD?
I have a need to read in the exact unaltered pixel data (ARGB) from a truecolour PNG file, preferably from PHP.

Unfortunately the GD library in PHP messes with the alpha channel (reducing it from 8-bit to 7-bit), making it unusable.

I'm currently assuming that my options are either:

Implement my own raw PNG reader to extract the necessary data.

Use some less-broken language/library and call it from the PHP as a shell process or CGI.

I'd be interested to hear any other ideas, though, or recommendations for one way over the other...

Edit: I think #1 is out.  I've tried passing the IDAT data stream to gzinflate(), but it just gives me a data error.  (Doing the exact same thing, with the exact same data, outside of PHP produces the expected result.)

答:
How about ImageMagick?</p>

```<code><?php
$im = new Imagick("foo.png");
$it = $im->getPixelIterator();

foreach($it as $row => $pixels) {
    foreach ($pixels as $column => $pixel) {
        // Do something with $pixel
    }

    $it->syncIterator();
}
?>
</code>```

OwnerDisplayName: Miral

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Miral

Body:
How about ImageMagick?

<?php
$im = new Imagick("foo.png");
$it = $im->getPixelIterator();

foreach($it as $row => $pixels) {
    foreach ($pixels as $column => $pixel) {
        // Do something with $pixel
    }

    $it->syncIterator();
}
?>

OwnerDisplayName: Can Berk Güder

LastEditorDisplayName: Can Berk Güder


问:
PHP Cookie management
here is what my client requirements are:

1> There is a common web page that lets each of the customer login. On successful login, a cookie is created and the customer is redirected to a "Waiting area" page. I need to create a cookie that would last for 10 secs and keep refreshing the time until the customer has closed the window.

2> The admin page will list all the customers who have not yet closed the "Waiting area" page and are waiting on the admin to move forward.

Since I am new to session and cookie management, I am not sure exactly what needs to be done here i.e. use session_start or setcookie ? Since the admin needs a list of all customers waiting, I guess all these entries need to go in a database table? And whenever a customer closes the page, the entry should be deleted from the database.

Is my understanding correct? If anyone has better suggestions, please let me know.

答:
I would advise to use the session_start functionality and keep the users associated with their session ID in a database. In the session table you keep track of the created timestamp and can easily check which users are waiting using a single query.

If you implement it only cookie based, you will not know who waits, because this information is only client based.

ContentLicense: CC BY-SA 3.0

Title: PHP Cookie management


问:
Update all slide master's and layout's footers
Trying to create a macro to quickly enter in project names to ppt footers. I can only get the top level slide master to accept the input title. I've tried looping through the other slide master layouts with the new footer info but I keep getting errors at the line to write text to the footer in the For loop</p>

```<code>
    Sub footchange()

    Dim myValue As Variant
    Dim sld As Slide

    myValue = InputBox("Enter Presentation Name")

    Set mySlidesHF = ActivePresentation.SlideMaster.HeadersFooters

    'Add name to slide master footer
    With mySlidesHF
        .Footer.Visible = True
        .Footer.Text = myValue + "    |   Confidential © 2020"
        .SlideNumber.Visible = True
    End With

    'Add name to slide master layouts footers
    For Each sld In ActivePresentation.Slides
       With sld.HeadersFooters
            .Footer.Visible = True
            .Footer.Text = myValue + "    |   Confidential © 2020"
            .SlideNumber.Visible = True
        End With
    Next

</code>```

答:
You can access the other masters through the DESIGN property:
https://learn.microsoft.com/en-us/office/vba/api/powerpoint.design

This code should get you started. Please give feedback if you have troubles.
(indentations kept against reviewers for better understanding):

```<code>Dim myValue As Variant
Dim sld As Slide

'Insert a Design Variable
Dim oMaster As Design

myValue = InputBox("Enter Presentation Name")

'Just to show you how many Masters you have
Debug.Print ActivePresentation.Designs.Count

'Loop through them
For Each oMaster In ActivePresentation.Designs

'Use actual Design
Set mySlidesHF = oMaster.SlideMaster.HeadersFooters

'Add name to slide master footer
With mySlidesHF
    .Footer.Visible = True
    .Footer.Text = myValue + "    |   Confidential © 2020"
    .SlideNumber.Visible = True
End With

'Another approach would be to change the footer on each slide manually
For Each sld In ActivePresentation.Slides
   With sld.HeadersFooters
        .Footer.Visible = True
        .Footer.Text = myValue + "    |   Confidential © 2020"
        .SlideNumber.Visible = True
    End With
Next

Next 'oMaster
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Trying to create a macro to quickly enter in project names to ppt footers. I can only get the top level slide master to accept the input title. I've tried looping through the other slide master layouts with the new footer info but I keep getting errors at the line to write text to the footer in the For loop

    Sub footchange()

    Dim myValue As Variant
    Dim sld As Slide

    myValue = InputBox("Enter Presentation Name")

    Set mySlidesHF = ActivePresentation.SlideMaster.HeadersFooters

    'Add name to slide master footer
    With mySlidesHF
        .Footer.Visible = True
        .Footer.Text = myValue + "    |   Confidential © 2020"
        .SlideNumber.Visible = True
    End With

    'Add name to slide master layouts footers
    For Each sld In ActivePresentation.Slides
       With sld.HeadersFooters
            .Footer.Visible = True
            .Footer.Text = myValue + "    |   Confidential © 2020"
            .SlideNumber.Visible = True
        End With
    Next

Body:
You can access the other masters through the DESIGN property:
https://learn.microsoft.com/en-us/office/vba/api/powerpoint.design

This code should get you started. Please give feedback if you have troubles.
(indentations kept against reviewers for better understanding):

Dim myValue As Variant
Dim sld As Slide

'Insert a Design Variable
Dim oMaster As Design

myValue = InputBox("Enter Presentation Name")

'Just to show you how many Masters you have
Debug.Print ActivePresentation.Designs.Count

'Loop through them
For Each oMaster In ActivePresentation.Designs

'Use actual Design
Set mySlidesHF = oMaster.SlideMaster.HeadersFooters

'Add name to slide master footer
With mySlidesHF
    .Footer.Visible = True
    .Footer.Text = myValue + "    |   Confidential © 2020"
    .SlideNumber.Visible = True
End With

'Another approach would be to change the footer on each slide manually
For Each sld In ActivePresentation.Slides
   With sld.HeadersFooters
        .Footer.Visible = True
        .Footer.Text = myValue + "    |   Confidential © 2020"
        .SlideNumber.Visible = True
    End With
Next

Next 'oMaster


问:
How to get a list of all the legal moves in the python-chess module?
I am using the python chess module. On the website, it shows that you can check if a move is legal by using

```<code>import chess

board = chess.Board()
move = input("Enter a chess move: ")
if move in board.legal_moves:
    # Some code to do if the move is a legal move
</code>```

However, I want to be able to get a move from board.legal_moves. When I try this:

```<code>print(board.legal_moves[0])
</code>```

This returns the following error:

```<code>TypeError: 'LegalMoveGenerator' object is not subscriptable
</code>```

How can I select a move as if I were using a list? Then, how would I use the selection as a move?

答:
The board.legal_moves object is a generator, or more specifically a LegalMoveGenerator. You can iterate over that object and it will yield something with each iteration. You can convert it to a list with list(board.legal_moves) and then index it as normal.

```<code>import chess
board = chess.Board()
legal_moves = list(board.legal_moves)
legal_moves[0]  # Move.from_uci('g1h3')
</code>```

Body:
I am using the python chess module. On the website, it shows that you can check if a move is legal by using

import chess

board = chess.Board()
move = input("Enter a chess move: ")
if move in board.legal_moves:
    # Some code to do if the move is a legal move

However, I want to be able to get a move from board.legal_moves. When I try this:

print(board.legal_moves[0])

This returns the following error:

TypeError: 'LegalMoveGenerator' object is not subscriptable

How can I select a move as if I were using a list? Then, how would I use the selection as a move?

Body:
The board.legal_moves object is a generator, or more specifically a LegalMoveGenerator. You can iterate over that object and it will yield something with each iteration. You can convert it to a list with list(board.legal_moves) and then index it as normal.

import chess
board = chess.Board()
legal_moves = list(board.legal_moves)
legal_moves[0]  # Move.from_uci('g1h3')


问:
How can I stop Wpf BeginAnimation from locking the image source?
I've been trying to get an animation sequence working for a game for Wpf. Being new at WPF, I didn't find a XAML answer that worked. I managed to piece together some C# code, and it worked but then I found I could not change the Image Source afterwards. I did many searches on the internet, tried things like changing the caching, but nothing had any effect.

In the code below, statement marked "This assignment ignored" is just that. No exception or other error, just stepping through it shows the assignment was not honored. I did find an answer while searching on a related topic (which I'll give in an answer post), but I wanted to post this in hopes of saving other developers a lot of frustration with this issue and how to make a WPF image animation of an explosion.
The actual images don't matter, use whatever ones you want.

The XAML

```<code><StackPanel Background="#333333">
    <Button x:Name="boomButton" HorizontalAlignment="Center"
                    FontSize="24" VerticalAlignment="Bottom" Click="boomButton_Click" >BOOM</Button>
    <Button x:Name="resetButton" HorizontalAlignment="Center"
                    FontSize="24" VerticalAlignment="Bottom" Click="resetButton_Click" >Reset</Button>

    <Image x:Name="bmb" Source="Images\bomberbase.png" Stretch="None" />
</StackPanel>
</code>```

C# Backend Code

```<code>public partial class MainWindow : Window
{
    public static BitmapImage mBoom1Img, mBoom2Img, mBoom3Img;
    public static BitmapImage mBomberImg, mBlankImg;
    public static BitmapImage mUnknownEnhancementImg, mAirfieldCraterImg;

    public MainWindow()
    {
        InitializeComponent();

        mBoom1Img = BitmapImageFromSource("Images/boom1.png");
        mBoom2Img = BitmapImageFromSource("Images/boom2.png");
        mBoom3Img = BitmapImageFromSource("Images/boom3.png");
        mBomberImg = BitmapImageFromSource("Images/bomberbase.png");
        mBlankImg = BitmapImageFromSource("Images/blank.png");
        mUnknownEnhancementImg = BitmapImageFromSource("Images/unknownEnhancement.png");
        mAirfieldCraterImg = BitmapImageFromSource("Images/airfieldCrater.png");
    }

    public static BitmapImage BitmapImageFromSource(string aRelPath)
    {
        BitmapImage bi3 = new BitmapImage();

        bi3.BeginInit();
        bi3.UriSource = new Uri(aRelPath, UriKind.Relative);
        bi3.EndInit();
        return bi3;
    }

    private void resetButton_Click(object sender, RoutedEventArgs e)
    {
        bmb.Source = mUnknownEnhancementImg;   // This assignment ignored
    }

    private void boomButton_Click(object sender, RoutedEventArgs e)
    {
        ObjectAnimationUsingKeyFrames animation = new ObjectAnimationUsingKeyFrames();
        animation.BeginTime = TimeSpan.FromSeconds(0);
        animation.Duration = new TimeSpan(0, 0, 0, 3, 0);

        DiscreteObjectKeyFrame fbmb = new DiscreteObjectKeyFrame(mBomberImg, TimeSpan.FromMilliseconds(0));
        animation.KeyFrames.Add(fbmb);

        DiscreteObjectKeyFrame f1 = new DiscreteObjectKeyFrame(mBoom1Img, TimeSpan.FromMilliseconds(200));
        animation.KeyFrames.Add(f1);
        DiscreteObjectKeyFrame f2 = new DiscreteObjectKeyFrame(mBoom2Img, TimeSpan.FromMilliseconds(400));
        animation.KeyFrames.Add(f2);
        DiscreteObjectKeyFrame f3 = new DiscreteObjectKeyFrame(mBoom3Img, TimeSpan.FromMilliseconds(600));
        animation.KeyFrames.Add(f3);
        DiscreteObjectKeyFrame f4 = new DiscreteObjectKeyFrame(mBlankImg, TimeSpan.FromMilliseconds(1000));
        animation.KeyFrames.Add(f4);

        animation.Completed += new EventHandler(animation_Complete);
        bmb.BeginAnimation(Image.SourceProperty, animation);
    }

    private void animation_Complete(object sender, EventArgs e)
    {
        // This unlocks the animation's hold on the property!
        //bmb.BeginAnimation(Image.SourceProperty, null);

        bmb.Source = mAirfieldCraterImg;   //  This assignment ignored
    }
}
</code>```

答:
While all the posts I could find revolved around setting options on the bitmap, I happened upon a surprisingly simple answer that seems to work just fine. It seems the animation maintains a lock on the image source even after the animation has ended.

Starting the same animation up with a null argument gets it to "let go" of the Source so that the problem assignment works fine. I don't know of any side effects of this, but I haven't seen any.

```<code>    private void animation_Complete(object sender, EventArgs e)
    {
        // This unlocks the animation's hold on the property!
        bmb.BeginAnimation(Image.SourceProperty, null);

        bmb.Source = mAirfieldCraterImg;   //  This assignment works
    }
</code>```

Body:
I've been trying to get an animation sequence working for a game for Wpf. Being new at WPF, I didn't find a XAML answer that worked. I managed to piece together some C# code, and it worked but then I found I could not change the Image Source afterwards. I did many searches on the internet, tried things like changing the caching, but nothing had any effect.

In the code below, statement marked "This assignment ignored" is just that. No exception or other error, just stepping through it shows the assignment was not honored. I did find an answer while searching on a related topic (which I'll give in an answer post), but I wanted to post this in hopes of saving other developers a lot of frustration with this issue and how to make a WPF image animation of an explosion.
The actual images don't matter, use whatever ones you want.

The XAML

<StackPanel Background="#333333">
    <Button x:Name="boomButton" HorizontalAlignment="Center"
                    FontSize="24" VerticalAlignment="Bottom" Click="boomButton_Click" >BOOM</Button>
    <Button x:Name="resetButton" HorizontalAlignment="Center"
                    FontSize="24" VerticalAlignment="Bottom" Click="resetButton_Click" >Reset</Button>

    <Image x:Name="bmb" Source="Images\bomberbase.png" Stretch="None" />
</StackPanel>

C# Backend Code

public partial class MainWindow : Window
{
    public static BitmapImage mBoom1Img, mBoom2Img, mBoom3Img;
    public static BitmapImage mBomberImg, mBlankImg;
    public static BitmapImage mUnknownEnhancementImg, mAirfieldCraterImg;

    public MainWindow()
    {
        InitializeComponent();

        mBoom1Img = BitmapImageFromSource("Images/boom1.png");
        mBoom2Img = BitmapImageFromSource("Images/boom2.png");
        mBoom3Img = BitmapImageFromSource("Images/boom3.png");
        mBomberImg = BitmapImageFromSource("Images/bomberbase.png");
        mBlankImg = BitmapImageFromSource("Images/blank.png");
        mUnknownEnhancementImg = BitmapImageFromSource("Images/unknownEnhancement.png");
        mAirfieldCraterImg = BitmapImageFromSource("Images/airfieldCrater.png");
    }

    public static BitmapImage BitmapImageFromSource(string aRelPath)
    {
        BitmapImage bi3 = new BitmapImage();

        bi3.BeginInit();
        bi3.UriSource = new Uri(aRelPath, UriKind.Relative);
        bi3.EndInit();
        return bi3;
    }

    private void resetButton_Click(object sender, RoutedEventArgs e)
    {
        bmb.Source = mUnknownEnhancementImg;   // This assignment ignored
    }

    private void boomButton_Click(object sender, RoutedEventArgs e)
    {
        ObjectAnimationUsingKeyFrames animation = new ObjectAnimationUsingKeyFrames();
        animation.BeginTime = TimeSpan.FromSeconds(0);
        animation.Duration = new TimeSpan(0, 0, 0, 3, 0);

        DiscreteObjectKeyFrame fbmb = new DiscreteObjectKeyFrame(mBomberImg, TimeSpan.FromMilliseconds(0));
        animation.KeyFrames.Add(fbmb);

        DiscreteObjectKeyFrame f1 = new DiscreteObjectKeyFrame(mBoom1Img, TimeSpan.FromMilliseconds(200));
        animation.KeyFrames.Add(f1);
        DiscreteObjectKeyFrame f2 = new DiscreteObjectKeyFrame(mBoom2Img, TimeSpan.FromMilliseconds(400));
        animation.KeyFrames.Add(f2);
        DiscreteObjectKeyFrame f3 = new DiscreteObjectKeyFrame(mBoom3Img, TimeSpan.FromMilliseconds(600));
        animation.KeyFrames.Add(f3);
        DiscreteObjectKeyFrame f4 = new DiscreteObjectKeyFrame(mBlankImg, TimeSpan.FromMilliseconds(1000));
        animation.KeyFrames.Add(f4);

        animation.Completed += new EventHandler(animation_Complete);
        bmb.BeginAnimation(Image.SourceProperty, animation);
    }

    private void animation_Complete(object sender, EventArgs e)
    {
        // This unlocks the animation's hold on the property!
        //bmb.BeginAnimation(Image.SourceProperty, null);

        bmb.Source = mAirfieldCraterImg;   //  This assignment ignored
    }
}

Body:
While all the posts I could find revolved around setting options on the bitmap, I happened upon a surprisingly simple answer that seems to work just fine. It seems the animation maintains a lock on the image source even after the animation has ended.

Starting the same animation up with a null argument gets it to "let go" of the Source so that the problem assignment works fine. I don't know of any side effects of this, but I haven't seen any.

    private void animation_Complete(object sender, EventArgs e)
    {
        // This unlocks the animation's hold on the property!
        bmb.BeginAnimation(Image.SourceProperty, null);

        bmb.Source = mAirfieldCraterImg;   //  This assignment works
    }


问:
How does __proto__ differ from constructor.prototype?
```<code>function Gadget(name, color)
{
   this.name = name;
   this.color = color;
}

Gadget.prototype.rating = 3

var newtoy = new Gadget("webcam", "black")

newtoy.constructor.prototype.constructor.prototype.constructor.prototype
</code>```

It always returns the object with rating = 3.

But if I do the following:

```<code>newtoy.__proto__.__proto__.__proto__
</code>```

The chain ends up returning null.

Also in Internet Explorer how would I check the null if there is not a __proto__ property?

答:
Short answer: __proto__ is a reference to the prototype property of the constructor that created the object.

Objects in JavaScript

A JavaScript object is a built-in type for a collection of zero or more properties. Properties are containers that hold other objects, primitive values, or functions.

Constructors in JavaScript

Functions are regular objects (which implement [[Call]] in ECMA-262 terms) with the additional capability of being callable but play another role in JavaScript: they become constructors (factories for objects) if invoked via the new operator. Constructors are thus a rough analog to classes in other languages.

Every JavaScript function is actually an instance of the Function built-in function object that has a special property named prototype used to implement prototype-based inheritance and shared properties. Every object created by a constructor function has an implicit reference (called the prototype or __proto__) to the value of its constructor prototype.

The constructor prototype is a sort of blueprint for building objects since every object created by the constructor inherits a reference to its prototype.

The prototype chain

An object specifies its prototype via the internal property [[Prototype]] or __proto__. The prototype relationship between two objects is about inheritance: every object can have another object as its prototype. The prototype may be the null value.

The chain of objects connected by the __proto__ property is called the prototype chain. When a reference is made to a property in an object, that reference is to the property encountered in the first object in the prototype chain that contains a property of that name. The prototype chain behaves as if it were a single object.

Whenever you try to access a property in an object, JavaScript starts the search for it in that object and continues with its prototype, the prototype's prototype and so on until the property is encountered or if __proto__ holds the value null.

This type of inheritance using the prototype chain is often called delegation to avoid confusion with other languages using the class chain.

Almost all objects are instances of Object, because Object.prototype is last in their prototype chain. But Object.prototype is not an instance of Object because Object.prototype.__proto__ holds the value null.

You can also create an object with a null prototype like this:

var dict = Object.create(null);
```

Such an object is a better map (dictionary) than a literal object, which is why this pattern is sometimes called the dict pattern (dict for dictionary).

Note: literal objects created using {} are instances of Object since ({}).__proto__ is a reference to Object.prototype.

Body:
function Gadget(name, color)
{
   this.name = name;
   this.color = color;
}

Gadget.prototype.rating = 3

var newtoy = new Gadget("webcam", "black")

newtoy.constructor.prototype.constructor.prototype.constructor.prototype

It always returns the object with rating = 3.

But if I do the following:

newtoy.__proto__.__proto__.__proto__

The chain ends up returning null.

Also in Internet Explorer how would I check the null if there is not a __proto__ property?

Body:
Short answer: __proto__ is a reference to the prototype property of the constructor that created the object.

Objects in JavaScript

A JavaScript object is a built-in type for a collection of zero or more properties. Properties are containers that hold other objects, primitive values, or functions.

Constructors in JavaScript

Functions are regular objects (which implement [[Call]] in ECMA-262 terms) with the additional capability of being callable but play another role in JavaScript: they become constructors (factories for objects) if invoked via the new operator. Constructors are thus a rough analog to classes in other languages.

Every JavaScript function is actually an instance of the Function built-in function object that has a special property named prototype used to implement prototype-based inheritance and shared properties. Every object created by a constructor function has an implicit reference (called the prototype or __proto__) to the value of its constructor prototype.

The constructor prototype is a sort of blueprint for building objects since every object created by the constructor inherits a reference to its prototype.

The prototype chain

An object specifies its prototype via the internal property [[Prototype]] or __proto__. The prototype relationship between two objects is about inheritance: every object can have another object as its prototype. The prototype may be the null value.

The chain of objects connected by the __proto__ property is called the prototype chain. When a reference is made to a property in an object, that reference is to the property encountered in the first object in the prototype chain that contains a property of that name. The prototype chain behaves as if it were a single object.

Whenever you try to access a property in an object, JavaScript starts the search for it in that object and continues with its prototype, the prototype's prototype and so on until the property is encountered or if __proto__ holds the value null.

This type of inheritance using the prototype chain is often called delegation to avoid confusion with other languages using the class chain.

Almost all objects are instances of Object, because Object.prototype is last in their prototype chain. But Object.prototype is not an instance of Object because Object.prototype.__proto__ holds the value null.

You can also create an object with a null prototype like this:

var dict = Object.create(null);

Such an object is a better map (dictionary) than a literal object, which is why this pattern is sometimes called the dict pattern (dict for dictionary).

Note: literal objects created using {} are instances of Object since ({}).__proto__ is a reference to Object.prototype.


问:
What does .! (dot exclamation mark) mean in python?
I wrote the following program:

```<code>from tkinter import *

root = Tk()

temp = None
def changeColor(event, e):
    # print('Positional arumgent passed:', x)
    print('event: ', event.widget)
    e2 = event.widget
    if e2['bg'] == 'white':
        e2['bg'] = 'black'
    elif e2['bg'] == 'black':
        e2['bg'] = 'white'
    global temp
    temp = event

entries = [[None for i in range(3)] for j in range(3)]

for y in range(3):
    for x in range(3):
        e = Entry(root, width=3, bg='white', bd=0, borderwidth=3)
        e.bind('<Double-Button-1>', lambda x: changeColor(x, e))
        e.grid(column=x, row=y)
        entries[y][x] = e

root.mainloop()
</code>```

which, in the terminal, produced the output,

```<code>event:  .!entry5
event:  .!entry6
event:  .!entry8
...
</code>```

When I examined the one of the event.widgets (stored in temp) in the terminal, I got,

```<code>>>> temp.widget
<tkinter.Entry object .!entry8>
>>> print(temp.widget)
.!entry8
</code>```

I've never seen this syntax before and I was unable to find anything in the docs or here on stackoverflow about it.

Does anyone know what it is? Could you kindly explain/describe?

答: .! is not a general Python thing, it's just how the tkinter library names widgets that are not otherwise given a name. entry comes from here, since this widget is an Entry class. The exclamation point & number suffix are assigned here, presumably being given a ! so that auto-generated, class-name-derived widget names don't overlap with those assigned by the user. And the leading period is how widgets are named when they don't have a named parent; if they did, it would be <parentname>.<childname>.

Body:
I wrote the following program:

from tkinter import *

root = Tk()

temp = None
def changeColor(event, e):
    # print('Positional arumgent passed:', x)
    print('event: ', event.widget)
    e2 = event.widget
    if e2['bg'] == 'white':
        e2['bg'] = 'black'
    elif e2['bg'] == 'black':
        e2['bg'] = 'white'
    global temp
    temp = event

entries = [[None for i in range(3)] for j in range(3)]

for y in range(3):
    for x in range(3):
        e = Entry(root, width=3, bg='white', bd=0, borderwidth=3)
        e.bind('<Double-Button-1>', lambda x: changeColor(x, e))
        e.grid(column=x, row=y)
        entries[y][x] = e

root.mainloop()

which, in the terminal, produced the output,

event:  .!entry5
event:  .!entry6
event:  .!entry8
...

When I examined the one of the event.widgets (stored in temp) in the terminal, I got,

>>> temp.widget
<tkinter.Entry object .!entry8>
>>> print(temp.widget)
.!entry8

I've never seen this syntax before and I was unable to find anything in the docs or here on stackoverflow about it.

Does anyone know what it is? Could you kindly explain/describe?


问:
Android drawing app intended for a single View needs to work in multi-view Bottom Navigation Activity app
I'm a completely new Android dev and am rather lost at the moment. I'm following this tutorial as I try to enable drawing to a view in my app which is a "Bottom Navigation Activity" project that features three tabs--or fragments. See screenshot below:

The problem is that the tutorial is intended for an app with a single View and a single standard MainActivity. In this case, the following code is used in the onCreate()method in the project's MainActivity.java class:

```<code>public class MainActivity extends AppCompatActivity {
super.onCreate(savedInstanceState):
PaintView paintView = new PaintView(content: this):
setContentView(paintView);
  }
</code>```

}

When I build a single view app, the code works great. No issues. But things can't work in my "Bottom Navigation Activity" project, because the fragments use a ViewModel type that doesn't offer the much needed methods of the View class. My app features 3 fragments, the first of which is named HomeFragment. It is on this fragment that I want all my drawing to take place. The default onCreateView() method for this fragment looks like so:

```<code>public class HomeFragment extends Fragment {

private HomeView Model homeViewModel;

public View onCreateView(@NonNull LayoutInflator inflater, ViewGroup container, Bundle savedInstanceState) {

homeViewModel = ViewModelProviders.of(fragment: this).get(HomeViewModel.class);
View root = inflater.inflate(R.layout.fragment_home, container, attachToRoot: false);

return root;
 }
}
</code>```

See screenshot below to see what I've tried to do. You will see that I've added a View class to my project called PaintView (just as created in the tutorial), which contains all the drawing code.

Unfortunately it generates the following compilation error:

```<code>Inferred type com.example.mobile_testapp_android_2_ui.home.PaintView for type parameter T is not within its bound; should extend androidx.lifecycle.ViewModel
</code>```

Any tips on how I can implement the tutorial's PaintView class so that I can use its methods to draw on the "HomeFragment" would be deeply appreciated.

Thank you and very cordially,

Wulf

答:
What you are doing is trying to create a HomeViewModel object with the PaintView class which is not possible. If you want to set PaintView as the view of your HomeFragment, you need to return an object of it as :

```<code>    //you can return any kind of view object as you like
    public View onCreateView(@NonNull LayoutInflator inflater, ViewGroup container, Bundle savedInstanceState) {

        PaintView homeFragmentView = new PaintView(requireContext());

        // PaintView class must extends View class
        return homeFragmentView;

    }
</code>```

I hope, this helps.

Learn more about Fragment here

Learn more about ViewModel here

Body:
I'm a completely new Android dev and am rather lost at the moment. I'm following this tutorial as I try to enable drawing to a view in my app which is a "Bottom Navigation Activity" project that features three tabs--or fragments. See screenshot below:

The problem is that the tutorial is intended for an app with a single View and a single standard MainActivity. In this case, the following code is used in the onCreate()method in the project's MainActivity.java class:

public class MainActivity extends AppCompatActivity {
super.onCreate(savedInstanceState):
PaintView paintView = new PaintView(content: this):
setContentView(paintView);
  }

}

When I build a single view app, the code works great. No issues. But things can't work in my "Bottom Navigation Activity" project, because the fragments use a ViewModel type that doesn't offer the much needed methods of the View class. My app features 3 fragments, the first of which is named HomeFragment. It is on this fragment that I want all my drawing to take place. The default onCreateView() method for this fragment looks like so:

public class HomeFragment extends Fragment {

private HomeView Model homeViewModel;

public View onCreateView(@NonNull LayoutInflator inflater, ViewGroup container, Bundle savedInstanceState) {

homeViewModel = ViewModelProviders.of(fragment: this).get(HomeViewModel.class);
View root = inflater.inflate(R.layout.fragment_home, container, attachToRoot: false);

return root;
 }
}

See screenshot below to see what I've tried to do. You will see that I've added a View class to my project called PaintView (just as created in the tutorial), which contains all the drawing code.

Unfortunately it generates the following compilation error:

Inferred type com.example.mobile_testapp_android_2_ui.home.PaintView for type parameter T is not within its bound; should extend androidx.lifecycle.ViewModel

Any tips on how I can implement the tutorial's PaintView class so that I can use its methods to draw on the "HomeFragment" would be deeply appreciated.

Thank you and very cordially,

Wulf

Body:
What you are doing is trying to create a HomeViewModel object with the PaintView class which is not possible. If you want to set PaintView as the view of your HomeFragment, you need to return an object of it as :

    //you can return any kind of view object as you like
    public View onCreateView(@NonNull LayoutInflator inflater, ViewGroup container, Bundle savedInstanceState) {

        PaintView homeFragmentView = new PaintView(requireContext());

        // PaintView class must extends View class
        return homeFragmentView;

    }

I hope, this helps.

Learn more about Fragment here

Learn more about ViewModel here


问:
why android service is stopped by Android OS?
OK, here is my code, I'm trying to create a running service even when the app is closed.

In main activity, I have created a new button and call startMyService() to start the service as following:

```<code>public void startMyService(View view) {
    Intent intent = new Intent(MainActivity.this, MyService.class);
    startService(intent);
}
</code>```

the Service class is simple :

```<code>public class MyService extends Service {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("MyService", "service is running");
        final Uri uri = Settings.System.DEFAULT_RINGTONE_URI;
        final Context x =(Context) MyService.this;

        new Thread(new Runnable() {
            @Override
            public void run() {
                MediaPlayer player = MediaPlayer.create(x,uri);
                player.setLooping(true);
                player.start();
            }
        }).start();
            Toast.makeText(getApplicationContext(), "Service is running", Toast.LENGTH_LONG).show();

        return START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
        Log.e("MyService", "service done");
    }
}
</code>```

Of course, I have added the service to manifest

```<code><service android:name=".MyService" android:exported="false" android:description="@string/service_description" />
</code>```

Now after running, I pressed the button to start the service, and close the activity, I supposed the music will be playing in the background but it stopped just after closing the activity.

How to solve this issue? How to make the service still running, and how to make it running again after an android OS destroying it?

I know there are too many topics about android services and START_STICKY

However, as you see this is not working in code above, why?

Note: This is not about playing music in the background, I used playing music because it is the simplest way to know when service is stopped, this is about how to make service keeps running in the background as supposed to be, for example, to do some task like tracking data changes from the server.

答:
It's normal behavior when your application target from android O, if you want to remain your Service you should use startForgroundService with Notification. Read here

While an app is in the foreground, it can create and run both foreground and background services freely. When an app goes into the background, it has a window of several minutes in which it is still allowed to create and use services. At the end of that window, the app is considered to be idle. At this time, the system stops the app's background services, just as if the app had called the services' Service.stopSelf() methods.

Body:
OK, here is my code, I'm trying to create a running service even when the app is closed.

In main activity, I have created a new button and call startMyService() to start the service as following:

public void startMyService(View view) {
    Intent intent = new Intent(MainActivity.this, MyService.class);
    startService(intent);
}

the Service class is simple :

public class MyService extends Service {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("MyService", "service is running");
        final Uri uri = Settings.System.DEFAULT_RINGTONE_URI;
        final Context x =(Context) MyService.this;

        new Thread(new Runnable() {
            @Override
            public void run() {
                MediaPlayer player = MediaPlayer.create(x,uri);
                player.setLooping(true);
                player.start();
            }
        }).start();
            Toast.makeText(getApplicationContext(), "Service is running", Toast.LENGTH_LONG).show();

        return START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
        Log.e("MyService", "service done");
    }
}

Of course, I have added the service to manifest

<service android:name=".MyService" android:exported="false" android:description="@string/service_description" />

Now after running, I pressed the button to start the service, and close the activity, I supposed the music will be playing in the background but it stopped just after closing the activity.

How to solve this issue? How to make the service still running, and how to make it running again after an android OS destroying it?

I know there are too many topics about android services and START_STICKY

However, as you see this is not working in code above, why?

Note: This is not about playing music in the background, I used playing music because it is the simplest way to know when service is stopped, this is about how to make service keeps running in the background as supposed to be, for example, to do some task like tracking data changes from the server.


问:
How to define the pipe operator?
I like the pipe (in dplyr or magrittr as mentioned in the comments) a lot but sometimes I run into errors which show me that I lack some understanding. In case of other functions or operators I mostly have at least some idea how they may be defined, but in case of the pipe I do not have even a clue where to start if I want to define it.

I am really curious how the pipe is defined. So far I simply tried to assign it to an own operator but even this does not work. See here:

```<code>library(dplyr)

`%pipe%` <- `%>%`

data.frame() %pipe% class(.)
# gives an error: subscript out of bounds
</code>```

What magical ingredients make a pipe work? How could we define it ourselves? Thanks.

答:
magrittr's code itself checks if the pipe you used is named as one of the few allowed names, as seen at the top here: https://github.com/tidyverse/magrittr/blob/master/R/is_something.R .

In fact all pipes have the same code, copied from magrittr:::pipe as seen as the bottom of this script :

https://github.com/tidyverse/magrittr/blob/master/R/pipe.R

The behavior depends on the name of the pipe, it's really odd and I've never seen this anywhere else.

I'll try to make it less confusing by inventing a fake function behaving likewise, forgive the silliness of the example.

concat <- function(x,y) {
  # extract quoted function name from call
  fun <- sys.call()[[1]]

  # check if it's one of our possible names, and act accordingly
  if(identical(fun, quote(`%upconcat>%`))) {
    return(toupper(paste0(x,y)))
  }
  if(identical(fun, quote(`%lowconcat>%`))) {
    return(tolower(paste0(x,y)))
  }
  stop("Unsupported operator!")
}
`%upconcat>%` <- `%lowconcat>%` <- concat

"XoX" %upconcat>% "oXo"
#> [1] "XOXOXO"
"XoX" %lowconcat>% "oXo"
#> [1] "xoxoxo"

`%foo>%` <- `%upconcat>%`
"XoX" %foo>% "oXo"
#> Error in "XoX" %foo>% "oXo": Unsupported operator!
```

<p>You see there's no way to copy the pipe unless you modify the <code>is_pipe</code> function itself, which you can't do...</p>

<p>Just kidding, of course you can, but probably you shouldn't ?</p>

<pre class="lang-r prettyprint-override"><code>
library(magrittr)
is_pipe <- function(pipe) {
  identical(pipe, quote(`%>%`))   ||
    identical(pipe, quote(`%T>%`))  ||
    identical(pipe, quote(`%<>%`))  ||
    identical(pipe, quote(`%$%`)) ||
    identical(pipe, quote(`%pipe%`)) # <- added line
}

assignInNamespace("is_pipe", is_pipe, "magrittr")
`%pipe%` <- `%>%`

data.frame() %pipe% class(.)
#> [1] "data.frame"
</code>```

Created on 2020-05-29 by the reprex package (v0.3.0)

Title: How to define the pipe operator?

Body:
I like the pipe (in dplyr or magrittr as mentioned in the comments) a lot but sometimes I run into errors which show me that I lack some understanding. In case of other functions or operators I mostly have at least some idea how they may be defined, but in case of the pipe I do not have even a clue where to start if I want to define it.

I am really curious how the pipe is defined. So far I simply tried to assign it to an own operator but even this does not work. See here:

library(dplyr)

`%pipe%` <- `%>%`

data.frame() %pipe% class(.)
# gives an error: subscript out of bounds

What magical ingredients make a pipe work? How could we define it ourselves? Thanks.

Body:
magrittr's code itself checks if the pipe you used is named as one of the few allowed names, as seen at the top here: https://github.com/tidyverse/magrittr/blob/master/R/is_something.R .

In fact all pipes have the same code, copied from magrittr:::pipe as seen as the bottom of this script :

https://github.com/tidyverse/magrittr/blob/master/R/pipe.R

The behavior depends on the name of the pipe, it's really odd and I've never seen this anywhere else.

I'll try to make it less confusing by inventing a fake function behaving likewise, forgive the silliness of the example.

concat <- function(x,y) {
  # extract quoted function name from call
  fun <- sys.call()[[1]]

  # check if it's one of our possible names, and act accordingly
  if(identical(fun, quote(`%upconcat>%`))) {
    return(toupper(paste0(x,y)))
  }
  if(identical(fun, quote(`%lowconcat>%`))) {
    return(tolower(paste0(x,y)))
  }
  stop("Unsupported operator!")
}
`%upconcat>%` <- `%lowconcat>%` <- concat

"XoX" %upconcat>% "oXo"
#> [1] "XOXOXO"
"XoX" %lowconcat>% "oXo"
#> [1] "xoxoxo"

`%foo>%` <- `%upconcat>%`
"XoX" %foo>% "oXo"
#> Error in "XoX" %foo>% "oXo": Unsupported operator!

You see there's no way to copy the pipe unless you modify the is_pipe function itself, which you can't do...

Just kidding, of course you can, but probably you shouldn't ?

library(magrittr)
is_pipe <- function(pipe) {
  identical(pipe, quote(`%>%`))   ||
    identical(pipe, quote(`%T>%`))  ||
    identical(pipe, quote(`%<>%`))  ||
    identical(pipe, quote(`%$%`)) ||
    identical(pipe, quote(`%pipe%`)) # <- added line
}

assignInNamespace("is_pipe", is_pipe, "magrittr")
`%pipe%` <- `%>%`

data.frame() %pipe% class(.)
#> [1] "data.frame"

Created on 2020-05-29 by the reprex package (v0.3.0)


问:
SQL standard to escape column names?
Is there a SQL standard to escape a column name? If not what works for MySQL and SQLite? does it also work for SQL Server?</p>

答:
Putting some answers together:

MS SQL (a.k.a. T-SQL), Microsoft Access SQL, DBASE/DBF: SELECT [COLUMN], [COLUMN2] FROM [TABLE]

MySQL:    SELECT `COLUMN`, `COLUMN2` FROM `TABLE`

SQLite, Oracle, Postgresql: SELECT "COLUMN", "COLUMN2" FROM "TABLE"

Please add/edit!

Title: SQL standard to escape column names?


答:
Generate a list from the generator.

```<code>legal_moves = list(board.legal_moves)
</code>```

Legal moves is now a list.

```<code>print(legal_moves)

[Move.from_uci('g1h3'), Move.from_uci('g1f3'), Move.from_uci('b1c3'),
 Move.from_uci('b1a3'), Move.from_uci('h2h3'), Move.from_uci('g2g3'),
 Move.from_uci('f2f3'), Move.from_uci('e2e3'), Move.from_uci('d2d3'),
 Move.from_uci('c2c3'), Move.from_uci('b2b3'), Move.from_uci('a2a3'),
 Move.from_uci('h2h4'), Move.from_uci('g2g4'), Move.from_uci('f2f4'),
 Move.from_uci('e2e4'), Move.from_uci('d2d4'), Move.from_uci('c2c4'),
 Move.from_uci('b2b4'), Move.from_uci('a2a4')]
</code>```

Title: How to get a list of all the legal moves in the python-chess module?

Body:
Generate a list from the generator.

legal_moves = list(board.legal_moves)

Legal moves is now a list.

print(legal_moves)

[Move.from_uci('g1h3'), Move.from_uci('g1f3'), Move.from_uci('b1c3'),
 Move.from_uci('b1a3'), Move.from_uci('h2h3'), Move.from_uci('g2g3'),
 Move.from_uci('f2f3'), Move.from_uci('e2e3'), Move.from_uci('d2d3'),
 Move.from_uci('c2c3'), Move.from_uci('b2b3'), Move.from_uci('a2a3'),
 Move.from_uci('h2h4'), Move.from_uci('g2g4'), Move.from_uci('f2f4'),
 Move.from_uci('e2e4'), Move.from_uci('d2d4'), Move.from_uci('c2c4'),
 Move.from_uci('b2b4'), Move.from_uci('a2a4')]


问:
How can i assign token in async storage to headers in app.js after login. in react-native
I am getting access token after login and I want to assign that token to authorization in headers in my App.js
I am using async storage to store the access token in local storage and I want to assign to headers in my App.js file How can I do it. I want to assign token to authorization in headers so that I can make graphql API calls

MY App.js file

```<code>import React, {Component} from 'react';
import {AppRegistry,SafeAreaView, StyleSheet} from 'react-native';
import Navigator from "@Navigation"
import AsyncStorage from '@react-native-community/async-storage';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { ApolloProvider } from 'react-apollo';
import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-boost';

const httpLink = createHttpLink({
  uri: 'https://graphql.sample.com/graphql',
});

const token = AsyncStorage.getItem('@accessToken')

 const authLink = setContext((_, { headers }) => {
    return {
      headers: {
        ...headers,
        authorization: token ,
      }
    }
});

const link = authLink.concat(httpLink)

const cache = new InMemoryCache();

const defaultOptions = {
  query: {
    fetchPolicy: "network-only",
    errorPolicy: "all"
  }
};

const client = new ApolloClient({
  link,
  cache,
  defaultOptions
});
class App extends Component {
  render() {
    return (
        <ApolloProvider client={client}>
            <Navigator/>
        </ApolloProvider>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1
  },
});
export default App;
</code>```

答:
You should await AsyncStorage.getItem('@accessToken') to get your accessToken before passing it to authorization: token. This is a post relating to Waiting for AsyncStorage.getItem()  in React Native.
Try this:

...
const token = await AsyncStorage.getItem('@accessToken')

 const authLink = setContext((_, { headers }) => {
    return {
      headers: {
        ...headers,
        authorization: token ,
      }
    }
});

...```

Body:
I am getting access token after login and I want to assign that token to authorization in headers in my App.js
I am using async storage to store the access token in local storage and I want to assign to headers in my App.js file How can I do it. I want to assign token to authorization in headers so that I can make graphql API calls

MY App.js file

import React, {Component} from 'react';
import {AppRegistry,SafeAreaView, StyleSheet} from 'react-native';
import Navigator from "@Navigation"
import AsyncStorage from '@react-native-community/async-storage';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { ApolloProvider } from 'react-apollo';
import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-boost';

const httpLink = createHttpLink({
  uri: 'https://graphql.sample.com/graphql',
});

const token = AsyncStorage.getItem('@accessToken')

 const authLink = setContext((_, { headers }) => {
    return {
      headers: {
        ...headers,
        authorization: token ,
      }
    }
});

const link = authLink.concat(httpLink)

const cache = new InMemoryCache();

const defaultOptions = {
  query: {
    fetchPolicy: "network-only",
    errorPolicy: "all"
  }
};

const client = new ApolloClient({
  link,
  cache,
  defaultOptions
});
class App extends Component {
  render() {
    return (
        <ApolloProvider client={client}>
            <Navigator/>
        </ApolloProvider>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1
  },
});
export default App;


问:
Convert timestamp data to date time in Python
I have a DataFrame with a column containing timestamps and I would like to convert the column to date time in Python and save the file with a column containing the date and time. Here is the code:</p>

```<code>
    import pandas as pd
    df = pd.DataFrame({
        "time": [1465585763000, 1465586363000, 1465586963000,
                  1465587563000, 1465588163000]})
    df

</code>```

答:
This could work </p>

```<code>from datetime import datetime as dt
import pandas as pd

times = [
    1465585763000,
    1465586363000,
    1465586963000,
    1465587563000,
    1465588163000]

start_ts = dt.timestamp(dt(1970, 1, 1))
dates = [dt.fromtimestamp(time / 1000 + start_ts) for time in times]
pd.to_datetime(dates)
</code>```

Body:
I have a DataFrame with a column containing timestamps and I would like to convert the column to date time in Python and save the file with a column containing the date and time. Here is the code:

    import pandas as pd
    df = pd.DataFrame({
        "time": [1465585763000, 1465586363000, 1465586963000,
                  1465587563000, 1465588163000]})
    df

Body:
This could work

from datetime import datetime as dt
import pandas as pd

times = [
    1465585763000,
    1465586363000,
    1465586963000,
    1465587563000,
    1465588163000]

start_ts = dt.timestamp(dt(1970, 1, 1))
dates = [dt.fromtimestamp(time / 1000 + start_ts) for time in times]
pd.to_datetime(dates)


问:
working with high precision timestamps in python
Hey I am working in python with datetime and I am wondering what the best way to parse this timestamp is.

The timestamps are ISO standard, here is an example "2010-06-19T08:17:14.078685237Z"

Now so far I have used

```<code>time = datetime.datetime.strptime(timestamp.split(".")[0], "%Y-%m-%dT%H:%M:%S")
precisetime = time + datetime.timedelta(0,float("." + timestamp[:-1].split(".")[0]))
</code>```

This kind of works, but I feel like there should be a more streamlined way (I am very new to python, and I am sure I am doing this like an ass). Also, I have nanoseconds in my timestamp, but only microseconds in my datetime object, is there a better module to work with? I need to be able to do operations on the time such as subtracting times and putting them in the scheduler.

Any better way to go about this?

答:
Here is an alternative approach using a regular expression that you may (or may not) find cleaner:

```<code>import re

timestamp = "2010-06-19T08:17:14.078685237Z"
ts_regex = re.compile(r"(\d{4})-(\d{1,2})-(\d{1,2})T(\d{2}):(\d{2}):(\d{2})\.(\d{6})")
precisetime = datetime.datetime(*map(int, ts_regex.match(timestamp).groups()))
</code>```

Here it is broken into a few more steps to provide some clarity:

```<code>>>> ts_regex.match(timestamp).groups()
('2010', '06', '19', '08', '17', '14', '078685')
>>> map(int, ts_regex.match(timestamp).groups())
[2010, 6, 19, 8, 17, 14, 78685]
</code>```

We can pass this list directly into the initialization of a datetime object using argument expansion with *, since the arguments are in the correct order.

Body:
Hey I am working in python with datetime and I am wondering what the best way to parse this timestamp is.

The timestamps are ISO standard, here is an example "2010-06-19T08:17:14.078685237Z"

Now so far I have used

time = datetime.datetime.strptime(timestamp.split(".")[0], "%Y-%m-%dT%H:%M:%S")
precisetime = time + datetime.timedelta(0,float("." + timestamp[:-1].split(".")[0]))

This kind of works, but I feel like there should be a more streamlined way (I am very new to python, and I am sure I am doing this like an ass). Also, I have nanoseconds in my timestamp, but only microseconds in my datetime object, is there a better module to work with? I need to be able to do operations on the time such as subtracting times and putting them in the scheduler.

Any better way to go about this?

Body:
Here is an alternative approach using a regular expression that you may (or may not) find cleaner:

import re

timestamp = "2010-06-19T08:17:14.078685237Z"
ts_regex = re.compile(r"(\d{4})-(\d{1,2})-(\d{1,2})T(\d{2}):(\d{2}):(\d{2})\.(\d{6})")
precisetime = datetime.datetime(*map(int, ts_regex.match(timestamp).groups()))

Here it is broken into a few more steps to provide some clarity:

>>> ts_regex.match(timestamp).groups()
('2010', '06', '19', '08', '17', '14', '078685')
>>> map(int, ts_regex.match(timestamp).groups())
[2010, 6, 19, 8, 17, 14, 78685]

We can pass this list directly into the initialization of a datetime object using argument expansion with *, since the arguments are in the correct order.


问:
Run Python script on startup/reboot of AWS instance
I'm running Flask on an AWS instance. My goal is to be able to have Flask running on its own, without me having to ssh into it and run

```<code>python app.py
</code>```

Is there a way to have this command run every time the AWS instance itself reboots?

答:
Try this:</p>

```<code>(crontab -l 2>/dev/null; echo '@reboot python /path/to/app.py') | crontab -
</code>```

Body:
I'm running Flask on an AWS instance. My goal is to be able to have Flask running on its own, without me having to ssh into it and run

python app.py

Is there a way to have this command run every time the AWS instance itself reboots?

Body:
Try this:

(crontab -l 2>/dev/null; echo '@reboot python /path/to/app.py') | crontab -


问:
tsc does not recognize '--init' option
For some reason npx tsc --init prints out the following error:

```<code>$ npx tsc --init
npx: installed 1 in 1.467s
error TS5023: Unknown compiler option 'init'.
</code>```

I have installed the typescript package with Yarn 2:

```<code>$ yarn add -D typescript
➤ YN0000: ┌ Resolution step
➤ YN0000: └ Completed in 0.31s
➤ YN0000: ┌ Fetch step
➤ YN0013: │ typescript@npm:3.9.3 can't be found in the cache and will be fetched from the remote registry
➤ YN0013: │ typescript@patch:typescript@npm%3A3.9.3#builtin<compat/typescript>::version=3.9.3&hash=8cac75 can't be found in the cache and will be fetched from the disk
➤ YN0000: └ Completed in 1.46s
➤ YN0000: ┌ Link step
➤ YN0000: └ Completed
➤ YN0000: Done in 1.95s
</code>```

Can someone explain to me why tsc does not recognize --init and what i am doing wrong?

UPDATE:

As Daniel figured out, the problem is that npx does not find or recognize the typescript package installed with Yarn 2. The solution was to use yarn instead: yarn tsc --init

答:
Judging from the output of npx tsc --init you do not seem to have the typescript package installed in the directory where you've run the command. npx tries to be helpful by installing any packages needed in order for the command to run.

Although it was trying to be helpful it ended up not installing the package one would expect in 2020. If you run $ npx tsc -v you will most likely get this output:

```<code>$ npx tsc -v
npx: installed 1 in 1.098s
message TS6029: Version 1.5.3
</code>```

If you had the typescript package installed, however, you would have gotten this, instead:

```<code>$ npx tsc -v
Version 3.9.3
</code>```

As you can see, the version installed by npm is different. That's because npx ended up installing the tsc package and not typescript. The tsc package also provides a tsc command. npx chose it instead of typescript because, while both packages provide a tsc command, it is also called tsc. npx thought it was a better fit.

UPDATE:

Yarn 2 introduces the Plug'n'Play feature. Dependencies are installed very differently from how Yarn 1 and npm used to.

Yarn 1 and npm place the code for your packages in the node_modules directory in every single project. npx goes to look for commands there.

Yarn 2, on the other hand, installs package code in a shared location and places in your project a single .pnp.js file that performs the mapping. If you install a package for one project, you won't have to download it again if you use it in another project.

Any tooling that was dependent on node_modules, however, will be broken. That's why npx was unable to find typescript in your project. npx does not know about Plug'n'Play.

You can read more about this feature here: https://yarnpkg.com/features/pnp

Title: tsc does not recognize '--init' option

Body:
For some reason npx tsc --init prints out the following error:

$ npx tsc --init
npx: installed 1 in 1.467s
error TS5023: Unknown compiler option 'init'.

I have installed the typescript package with Yarn 2:

$ yarn add -D typescript
➤ YN0000: ┌ Resolution step
➤ YN0000: └ Completed in 0.31s
➤ YN0000: ┌ Fetch step
➤ YN0013: │ typescript@npm:3.9.3 can't be found in the cache and will be fetched from the remote registry
➤ YN0013: │ typescript@patch:typescript@npm%3A3.9.3#builtin<compat/typescript>::version=3.9.3&hash=8cac75 can't be found in the cache and will be fetched from the disk
➤ YN0000: └ Completed in 1.46s
➤ YN0000: ┌ Link step
➤ YN0000: └ Completed
➤ YN0000: Done in 1.95s

Can someone explain to me why tsc does not recognize --init and what i am doing wrong?

UPDATE:

As Daniel figured out, the problem is that npx does not find or recognize the typescript package installed with Yarn 2. The solution was to use yarn instead: yarn tsc --init

Body:
Judging from the output of npx tsc --init you do not seem to have the typescript package installed in the directory where you've run the command. npx tries to be helpful by installing any packages needed in order for the command to run.

Although it was trying to be helpful it ended up not installing the package one would expect in 2020. If you run $ npx tsc -v you will most likely get this output:

$ npx tsc -v
npx: installed 1 in 1.098s
message TS6029: Version 1.5.3

If you had the typescript package installed, however, you would have gotten this, instead:

$ npx tsc -v
Version 3.9.3

As you can see, the version installed by npm is different. That's because npx ended up installing the tsc package and not typescript. The tsc package also provides a tsc command. npx chose it instead of typescript because, while both packages provide a tsc command, it is also called tsc. npx thought it was a better fit.

UPDATE:

Yarn 2 introduces the Plug'n'Play feature. Dependencies are installed very differently from how Yarn 1 and npm used to.

Yarn 1 and npm place the code for your packages in the node_modules directory in every single project. npx goes to look for commands there.

Yarn 2, on the other hand, installs package code in a shared location and places in your project a single .pnp.js file that performs the mapping. If you install a package for one project, you won't have to download it again if you use it in another project.

Any tooling that was dependent on node_modules, however, will be broken. That's why npx was unable to find typescript in your project. npx does not know about Plug'n'Play.

You can read more about this feature here: https://yarnpkg.com/features/pnp


问:
Validating forms Ajax PHP
The jQuery/JavaScript/Ajax code is not mine. I'm learning and trying to understand it. The issue that I am having is after the data gets sent to the database the form is suppose to add class="show" to #sendmessage but its adding class="show" to #errormessage even though it was successful and the data was entered into the database. I don't understand why or how to fix it.

contact form index.html

```<code> <div class="form">
                    <div id="sendmessage">Your message has been sent. Thank you!</div>
                    <div id="errormessage"></div>
                    <form action="contactform/contactform.php" method="POST" role="form" class="contactForm">
                        <div class="form-row">
                            <div class="form-group col-md-6">
                                <input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
                                <div class="validation"></div>
                            </div>
                            <div class="form-group col-md-6">
                                <input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
                                <div class="validation"></div>
                            </div>
                        </div>
                        <div class="form-group">
                            <input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:8" data-msg="Please enter at least 8 chars of subject" />
                            <div class="validation"></div>
                        </div>
                        <div class="form-group">
                            <textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
                            <div class="validation"></div>
                        </div>
                        <div class="text-center"><button type="submit">Send Message</button></div>
                    </form>
                </div>
</code>```

contactform.js

```<code>jQuery(document).ready(function($) {
  "use strict";

  //Contact
  $('form.contactForm').submit(function() {
    var f = $(this).find('.form-group'),
      ferror = false,
      emailExp = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i;

    f.children('input').each(function() { // run all inputs

      var i = $(this); // current input
      var rule = i.attr('data-rule');

      if (rule !== undefined) {
        var ierror = false; // error flag for current input
        var pos = rule.indexOf(':', 0);
        if (pos >= 0) {
          var exp = rule.substr(pos + 1, rule.length);
          rule = rule.substr(0, pos);
        } else {
          rule = rule.substr(pos + 1, rule.length);
        }

        switch (rule) {
          case 'required':
            if (i.val() === '') {
              ferror = ierror = true;
            }
            break;

          case 'minlen':
            if (i.val().length < parseInt(exp)) {
              ferror = ierror = true;
            }
            break;

          case 'email':
            if (!emailExp.test(i.val())) {
              ferror = ierror = true;
            }
            break;

          case 'checked':
            if (! i.is(':checked')) {
              ferror = ierror = true;
            }
            break;

          case 'regexp':
            exp = new RegExp(exp);
            if (!exp.test(i.val())) {
              ferror = ierror = true;
            }
            break;
        }
        i.next('.validation').html((ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
      }
    });
    f.children('textarea').each(function() { // run all inputs

      var i = $(this); // current input
      var rule = i.attr('data-rule');

      if (rule !== undefined) {
        var ierror = false; // error flag for current input
        var pos = rule.indexOf(':', 0);
        if (pos >= 0) {
          var exp = rule.substr(pos + 1, rule.length);
          rule = rule.substr(0, pos);
        } else {
          rule = rule.substr(pos + 1, rule.length);
        }

        switch (rule) {
          case 'required':
            if (i.val() === '') {
              ferror = ierror = true;
            }
            break;

          case 'minlen':
            if (i.val().length < parseInt(exp)) {
              ferror = ierror = true;
            }
            break;
        }
        i.next('.validation').html((ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
      }
    });
    if (ferror) return false;
    else var str = $(this).serialize();
    var action = $(this).attr('action');
    if( ! action ) {
      action = 'contactform/contactform.php';
    }
    $.ajax({
      type: "POST",
      url: action,
      data: str,
      success: function(msg) {
         //alert(msg);
        if (msg == 'OK') {
          $("#sendmessage").addClass("show");
          $("#errormessage").removeClass("show");
          $('.contactForm').find("input, textarea").val("");
        } else {
          $("#sendmessage").removeClass("show");
          $("#errormessage").addClass("show");
          $('#errormessage').html(msg);
        }

      }
    });
    return false;
  });

});

</code>```

contactform.php

```<code><?php
//Define access
define('_VALID', 'Yes');
//required files
require_once('../include/config/config.php');

//variables
$contactFormName = '';
$contactFormEmail = '';
$contactFormSubject = '';
$contactFormMessage = '';
$checkStep = 1;

//Add new message
if (isset($_POST['name'])){

        //Get values
        $contactFormName = $_POST['name'];
        $contactFormEmail = $_POST['email'];
        $contactFormSubject = $_POST['subject'];
        $contactFormMessage = $_POST['message'];

        // 1. check name form field
        if($checkStep == 1){
            if($contactFormName === $_POST['name']){
                $contactFormName = filterName($contactFormName);
                $checkStep++;

            }else{
                echo "No its not working";
            }
        }
            // 2. check email field
            if($checkStep == 2){
                if($contactFormEmail === $_POST['email']){
                    $contactFormEmail = filterEmail($contactFormEmail);
                    $checkStep++;
                }else{
                        echo "Uh Oh! Something went wrong with your email please try again!";
                    }
                }

            // 3. check subject
            if($checkStep == 3){
                if($contactFormSubject === $_POST['subject']){
                    $contactFormSubject = filterSubject($contactFormSubject);
                    $checkStep++;
                }else{
                    echo "Uh Oh! Whats up with your subject";
                }
            }
            // 4. check message
            if($checkStep == 4){
                 if($contactFormMessage === $_POST['message']){
                    $contactFormMessage = filterMessage($contactFormMessage);
                     $checkStep++;
                }else{
                    echo "Uh ho!  Please write us a message";
                }
            }
            // 5. insert message
            if($checkStep == 5){
                $sqlAddMessage = "
                    INSERT INTO contact_form(
                        name,
                        email,
                        subject,
                        message
                    ) VALUES(
                        '$contactFormName',
                        '$contactFormEmail',
                        '$contactFormSubject',
                        '$contactFormMessage'
                    )
                ";
                $queryAddMessage = $GLOBALS['mysqli']->query($sqlAddMessage);

                if($queryAddMessage){

                //code goes here
                }

            }else{
                echo "Uh Oh! NO No No. Check step 5";
            }
        }

?>

</code>```

答:
The issue is that you're not setting $msg = "OK" anywhere in your function so the AJAX response is always going to the else statement.

contactform.php (in // 5. section)

```<code>if($queryAddMessage){
    echo "OK";
}
</code>```

Title: Validating forms Ajax PHP

Body:
The jQuery/JavaScript/Ajax code is not mine. I'm learning and trying to understand it. The issue that I am having is after the data gets sent to the database the form is suppose to add class="show" to #sendmessage but its adding class="show" to #errormessage even though it was successful and the data was entered into the database. I don't understand why or how to fix it.

contact form index.html

Your message has been sent. Thank you!

                    <form action="contactform/contactform.php" method="POST" role="form" class="contactForm">

                                <input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />

                                <input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />

                            <input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:8" data-msg="Please enter at least 8 chars of subject" />

                            <textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>

<button type="submit">Send Message</button>

                    </form>

contactform.js

jQuery(document).ready(function($) {
  "use strict";

  //Contact
  $('form.contactForm').submit(function() {
    var f = $(this).find('.form-group'),
      ferror = false,
      emailExp = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i;

    f.children('input').each(function() { // run all inputs

      var i = $(this); // current input
      var rule = i.attr('data-rule');

      if (rule !== undefined) {
        var ierror = false; // error flag for current input
        var pos = rule.indexOf(':', 0);
        if (pos >= 0) {
          var exp = rule.substr(pos + 1, rule.length);
          rule = rule.substr(0, pos);
        } else {
          rule = rule.substr(pos + 1, rule.length);
        }

        switch (rule) {
          case 'required':
            if (i.val() === '') {
              ferror = ierror = true;
            }
            break;

          case 'minlen':
            if (i.val().length < parseInt(exp)) {
              ferror = ierror = true;
            }
            break;

          case 'email':
            if (!emailExp.test(i.val())) {
              ferror = ierror = true;
            }
            break;

          case 'checked':
            if (! i.is(':checked')) {
              ferror = ierror = true;
            }
            break;

          case 'regexp':
            exp = new RegExp(exp);
            if (!exp.test(i.val())) {
              ferror = ierror = true;
            }
            break;
        }
        i.next('.validation').html((ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
      }
    });
    f.children('textarea').each(function() { // run all inputs

      var i = $(this); // current input
      var rule = i.attr('data-rule');

      if (rule !== undefined) {
        var ierror = false; // error flag for current input
        var pos = rule.indexOf(':', 0);
        if (pos >= 0) {
          var exp = rule.substr(pos + 1, rule.length);
          rule = rule.substr(0, pos);
        } else {
          rule = rule.substr(pos + 1, rule.length);
        }

        switch (rule) {
          case 'required':
            if (i.val() === '') {
              ferror = ierror = true;
            }
            break;

          case 'minlen':
            if (i.val().length < parseInt(exp)) {
              ferror = ierror = true;
            }
            break;
        }
        i.next('.validation').html((ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
      }
    });
    if (ferror) return false;
    else var str = $(this).serialize();
    var action = $(this).attr('action');
    if( ! action ) {
      action = 'contactform/contactform.php';
    }
    $.ajax({
      type: "POST",
      url: action,
      data: str,
      success: function(msg) {
         //alert(msg);
        if (msg == 'OK') {
          $("#sendmessage").addClass("show");
          $("#errormessage").removeClass("show");
          $('.contactForm').find("input, textarea").val("");
        } else {
          $("#sendmessage").removeClass("show");
          $("#errormessage").addClass("show");
          $('#errormessage').html(msg);
        }

      }
    });
    return false;
  });

});

contactform.php

<?php
//Define access
define('_VALID', 'Yes');
//required files
require_once('../include/config/config.php');

//variables
$contactFormName = '';
$contactFormEmail = '';
$contactFormSubject = '';
$contactFormMessage = '';
$checkStep = 1;

//Add new message
if (isset($_POST['name'])){

        //Get values
        $contactFormName = $_POST['name'];
        $contactFormEmail = $_POST['email'];
        $contactFormSubject = $_POST['subject'];
        $contactFormMessage = $_POST['message'];

        // 1. check name form field
        if($checkStep == 1){
            if($contactFormName === $_POST['name']){
                $contactFormName = filterName($contactFormName);
                $checkStep++;

            }else{
                echo "No its not working";
            }
        }
            // 2. check email field
            if($checkStep == 2){
                if($contactFormEmail === $_POST['email']){
                    $contactFormEmail = filterEmail($contactFormEmail);
                    $checkStep++;
                }else{
                        echo "Uh Oh! Something went wrong with your email please try again!";
                    }
                }

            // 3. check subject
            if($checkStep == 3){
                if($contactFormSubject === $_POST['subject']){
                    $contactFormSubject = filterSubject($contactFormSubject);
                    $checkStep++;
                }else{
                    echo "Uh Oh! Whats up with your subject";
                }
            }
            // 4. check message
            if($checkStep == 4){
                 if($contactFormMessage === $_POST['message']){
                    $contactFormMessage = filterMessage($contactFormMessage);
                     $checkStep++;
                }else{
                    echo "Uh ho!  Please write us a message";
                }
            }
            // 5. insert message
            if($checkStep == 5){
                $sqlAddMessage = "
                    INSERT INTO contact_form(
                        name,
                        email,
                        subject,
                        message
                    ) VALUES(
                        '$contactFormName',
                        '$contactFormEmail',
                        '$contactFormSubject',
                        '$contactFormMessage'
                    )
                ";
                $queryAddMessage = $GLOBALS['mysqli']->query($sqlAddMessage);

                if($queryAddMessage){

                //code goes here
                }

            }else{
                echo "Uh Oh! NO No No. Check step 5";
            }
        }

?>

Body:
The issue is that you're not setting $msg = "OK" anywhere in your function so the AJAX response is always going to the else statement.

contactform.php (in // 5. section)

if($queryAddMessage){
    echo "OK";
}


问:
How to rotate a two-dimensional array to an arbitrary degree?
Say I have a bool[][], and I want to rotate it by 37 degrees. I am aware that the transformation wouldn't always be perfect, and that's okay. I've ready plenty of answers on here similar to my question, but the only solutions I've found only solve the problem for 90 degree increments. </p>

答:
Assuming you are rotating a bitmap, I'd first look at using an imaging framework (e.g. System.Drawing) to achieve what you want. Say, take your bools, turn it into a 1-bpp bitmap, draw it rotated, and read it back out.

If that's not what you want, you can either use the rotation provided by wberry and apply to each bool, or if performance is at a premium, write your own texturized rectangle rasterizer. To do the latter, look at some old graphics programming textbooks on how to texture map arbitrary 2D polygons.


问:
Warning message while using a window function in SparkSQL dataframe
I am getting the below warning message when I use the window function in SparkSQL. Can anyone please let me know how to fix this issue.

Warning Message:

No Partition Defined for Window operation! Moving all data to a single partition, this can cause serious performance degradation.

My Code:

def calcPrevBrdrx(df: DataFrame): DataFrame = {
    val w = Window.orderBy("existing_col1")
    df.withColumn("new_col", lag("existing_col2", 1).over(w))
}
```

答:
If your logic demands to use order by without partition clause, may be because you don't have anything else to partition on or it doesn't make sense for the window function used, you can add a dummy value like below -

.withColumn("id", explode(typedLit((1 to 100).toList)))

This will create an id field with value from 1 to 100 for each row in original dataframe and use that in partition by clause ( partition by id) , it will launch 100 tasks. Total number of rows it will create will be current rows*100 .Make sure you drop the id field and do distinct on result.


问:
Is there a way to test a css-selector query to an unappended element?
I have this code:

```<code>Element.prototype.queryTest = function(strQuery) {
 var _r;
 if (this.parentElement == null) {
  _r = Array.prototype.slice.call(document.querySelectorAll(strQuery)).indexOf(this);
 } else {
  _r = Array.prototype.slice.call(this.parentElement.querySelectorAll(strQuery)).indexOf(this);
 }
 return !!(_r+1);
}
</code>```

I am searching for some way to test a query to an unappended element.

I want to change the first code to make this work:

```<code>var t = document.createElement("span");
t.classList.add("asdfg");
console.log(t.queryTest("span.adsfg"));
</code>```

If there is a way to detect if the element isn't appended I could create a new temporary unappended one and append the target one to the temporary one to test the css-selector query.
Is there a way to detect if the element hasn't been appended jet? Could the target element be accessible even after freeing the temporary parent one? I have tested it on Chrome and it is accessible but I don't know if that is the case for firefox.

I know I can use document.querySelectorAll("*") to get a list of nodes but... isn't too CPU-demmanding the process to turn this NodeList to an Array? This is why I prefer not to use that way.

Thanks in advance.

答:
I did it.

```<code>Element.prototype.querySelectorTest = function(strQuery) {
 var _r;
 if (this.parentElement != null) {
  _r = Array.prototype.indexOf.call(this.parentElement.querySelectorAll(strQuery),this);
 } else if (this == document.documentElement) {
  _r = ((document.querySelector(strQuery) == this)-1);
 } else {
  _r = ((this == document.createElement("i").appendChild(this).parentElement.querySelector(strQuery))-1);
 }
 return !!(_r+1);
}
</code>```

I changed the way it check the nodeList.
I renamed the function to a more proper name.

If the target element is the root one there's no need to make a querySelectorAll.
If you append the unappended element to a temporary one to test the child you don't loose the reference (variable value in case there is one).

This is not my native language so please consider that.

Body:
I have this code:

Element.prototype.queryTest = function(strQuery) {
 var _r;
 if (this.parentElement == null) {
  _r = Array.prototype.slice.call(document.querySelectorAll(strQuery)).indexOf(this);
 } else {
  _r = Array.prototype.slice.call(this.parentElement.querySelectorAll(strQuery)).indexOf(this);
 }
 return !!(_r+1);
}

I am searching for some way to test a query to an unappended element.

I want to change the first code to make this work:

var t = document.createElement("span");
t.classList.add("asdfg");
console.log(t.queryTest("span.adsfg"));

If there is a way to detect if the element isn't appended I could create a new temporary unappended one and append the target one to the temporary one to test the css-selector query.
Is there a way to detect if the element hasn't been appended jet? Could the target element be accessible even after freeing the temporary parent one? I have tested it on Chrome and it is accessible but I don't know if that is the case for firefox.

I know I can use document.querySelectorAll("*") to get a list of nodes but... isn't too CPU-demmanding the process to turn this NodeList to an Array? This is why I prefer not to use that way.

Thanks in advance.

Body:
I did it.

Element.prototype.querySelectorTest = function(strQuery) {
 var _r;
 if (this.parentElement != null) {
  _r = Array.prototype.indexOf.call(this.parentElement.querySelectorAll(strQuery),this);
 } else if (this == document.documentElement) {
  _r = ((document.querySelector(strQuery) == this)-1);
 } else {
  _r = ((this == document.createElement("i").appendChild(this).parentElement.querySelector(strQuery))-1);
 }
 return !!(_r+1);
}

I changed the way it check the nodeList.
I renamed the function to a more proper name.

If the target element is the root one there's no need to make a querySelectorAll.
If you append the unappended element to a temporary one to test the child you don't loose the reference (variable value in case there is one).

This is not my native language so please consider that.