问:
convert WriteableImage to BufferedImage
I need some help concerning Writable- and BufferedImages in Java (11, Javafx):

How do I convert a WritabeImage to a BufferedImage? - WITHOUT using SwingFXUtils.fromFXImage()

It is important for me to find a solution without SwingFXUtils.fromFXImage(). I have already asked google, but the only results I am getting contain SwingFXUtils.fromFXImage(). So I am asking for your expertise.

Could you please help me?

Thanks!

答:
You can copy the pixels yourself:</p>

```<code>BufferedImage convert(Image fxImage) {
    int width = (int) Math.ceil(fxImage.getWidth());
    int height = (int) Math.ceil(fxImage.getHeight());

    BufferedImage image = new BufferedImage(width, height,
        BufferedImage.TYPE_INT_ARGB);

    int[] buffer = new int[width];

    PixelReader reader = fxImage.getPixelReader();
    WritablePixelFormat<IntBuffer> format =
        PixelFormat.getIntArgbInstance();
    for (int y = 0; y < height; y++) {
        reader.getPixels(0, y, width, 1, format, buffer, 0, width);
        image.getRaster().setDataElements(0, y, width, 1, buffer);
    }

    return image;
}
</code>```

Title: convert WriteableImage to BufferedImage

Body:
You can copy the pixels yourself:

BufferedImage convert(Image fxImage) {
    int width = (int) Math.ceil(fxImage.getWidth());
    int height = (int) Math.ceil(fxImage.getHeight());

    BufferedImage image = new BufferedImage(width, height,
        BufferedImage.TYPE_INT_ARGB);

    int[] buffer = new int[width];

    PixelReader reader = fxImage.getPixelReader();
    WritablePixelFormat<IntBuffer> format =
        PixelFormat.getIntArgbInstance();
    for (int y = 0; y < height; y++) {
        reader.getPixels(0, y, width, 1, format, buffer, 0, width);
        image.getRaster().setDataElements(0, y, width, 1, buffer);
    }

    return image;
}


来源: stackexchange

问:
Get data after second underscore from back in python dataframe?
I'm trying to get data after second underscore from back in python dataframe?

```<code>    number
0   a_bc_def 12_23_this_6729
1   abc_def,122$3_this_6729
2   abc_def_1_2_23_this_6729

    number
0   this_6729
1   this_6729
2   this_6729
</code>```

I tried to get data from second underscore from beginning.

```<code>df['number'] = df['number'].str.split('_',2).apply(lambda x: x[-1])
</code>```

How to do that from second underscore from back ?

答:
No need for apply, this can be done with str method operations

str.split('_') to split on underscores

str[-2:] to select the last 2 elements post-split

str.join('_') to join those elements into a single string

```<code>df['number']=df['number'].str.split('_').str[-2:].str.join('_')

0    this_6729
1    this_6729
2    this_6729
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to get data after second underscore from back in python dataframe?

    number
0   a_bc_def 12_23_this_6729
1   abc_def,122$3_this_6729
2   abc_def_1_2_23_this_6729

    number
0   this_6729
1   this_6729
2   this_6729

I tried to get data from second underscore from beginning.

df['number'] = df['number'].str.split('_',2).apply(lambda x: x[-1])

How to do that from second underscore from back ?

Body:
No need for apply, this can be done with str method operations

str.split('_') to split on underscores

str[-2:] to select the last 2 elements post-split

str.join('_') to join those elements into a single string

df['number']=df['number'].str.split('_').str[-2:].str.join('_')

0    this_6729
1    this_6729
2    this_6729


问:
How can we emulate a reference to an object attribute so that its use is as simple and transparent as possible, in Python 3?
(Note: I don't think this is a duplicate of the many questions about references to references because I already know Python does not support them. I'm asking how we can emulate them to make their use as simple and seamless as possible.)

Use case:

Let's say we have an object M that contains two matrices U1 and U2, and we want to return a view U of their product. This is handy because the user can write M.U @ v directly instead of the more cumbersome M.U1 @ (M.U2 @ v) and M.U1 @ M.U2 @ v, which are not exactly equivalent from the point of view of time complexity. M.U @ v will pick the best one automatically.

Since we need to support the @ operator, M.U must be a property which returns (with caching) an object which refers to M.U1 and M.U2.

The object M modifies not only the objects referenced by U1 and U2, but also the references themselves. This means that the view needs to reference the references themselves and not just the referenced objects.

Now suppose we want to create an analogous view of two other matrices V1 and V2 contained in the same object.

Thoughts:

If the two views are cached, there's only a single instance of each view so we could update them every time M.U1 and M.U2 are modified.

We could implement 1. by defining setters for U1, U2, V1, and V2.

If the views can create modified views (e.g. U.T returns the transposed of U) then we can break the updating mechanism if we're not careful.

Real references to U1, U2, V1, and V2 would be simpler, faster, and safer, so I think they're the way to go.

答:
My solution works seamlessly enough when one wants to access attributes, methods, or dunder methods (e.g. __rmul__) through a reference:

r = Ref(some_obj, 'some_attr')
M = r @ some_other_operand
```

<p>It may not work at all when the reference is passed to a function:</p>

<pre class="lang-py prettyprint-override"><code>M2 = compute_something(r)
</code>```

That's because I have no way to intercept the access to r. For instance np.linalg.svd(r) doesn't work, but np.linalg.svd(r[...]) does because [...] lets us do the dereferencing. Luckily for me, pytorch supports r.svd(), which is very convenient and doesn't suffer from the same problem.

Let me know if you have a way to solve that problem.

EDIT: The problem above can be solved by modifying __bases__ of Ref so that issubclass believes our ref is a subclass of the correct type. Unfortunately, in Python 3, __bases__ can be written only during class creation. That's good enough if a ref keeps pointing to objects of the same type, but if that's not the case, we need to create another class each time the type changes, and we need to catch the modification right when it happens! That's impossible AFAICT.

EDIT2: One solution is to add or replace __getattribute__ on the object containing the reference we're referencing.

Anyway, I'll never use the code presented in this answer of mine. It was just an interesting exercise. Functions are first-class in Python, as we always say, but, unfortunately, references are not. One might misuse them, but don't we also say We're all adults here?.

Since it's difficult to know what dunder methods to support beforehand, I provide the function add_types which lets one add support for new types. For instance:

import torch as T             # I use `T` in honor of theano ;)
import numpy as np

add_types(T.Tensor, np.ndarray)
```

<p>Here's my first attempt:</p>

<pre class="lang-py prettyprint-override"><code># TODO: Can we make this more robust and general?

_to_ignore = "new getattr getattribute setattr init class".split()
_default_types = [list, int, float]

_to_ignore = ['__' + n + '__' for n in _to_ignore]
_supported_types = set()
_dunder_ops = set()
_dunder_rops = set()

def _deref_refs(*objs):
    # TODO: inline this for efficiency?
    return [getattr(o._h6odj9348dh098d__obj, o._h6odj9348dh098d__attr)
                if isinstance(o, Ref) else o
            for o in objs]

def _create_op(name):
    def op(self, *args):
        obj, *args = _deref_refs(self, *args)
        return getattr(obj, name)(*args)

    def rop(self, *args):
        obj, *args = _deref_refs(self, *args)
        # Little hack: we can't remove an (r-)op (e.g. __radd__) so, when the
        #   referenced obj doesn't have it, we emulate its absence by falling
        #   back on the non-r version (e.g. __radd__ -> __add__) instead.
        rop = getattr(obj, name, None)
        if rop is not None:
            return rop(*args)
        # Switch to the non-r version of the op (and swap the operands).
        op_name = name[:2] + name[3:]           # __rXXX__ -> __XXX__
        return getattr(args[0], op_name)(obj, *args[1:])

    return rop if name in _dunder_rops else op

class Ref:
    def __init__(self, obj, attr):
        # 1. use mangling to avoid name conflicts
        # 2. use super().__setattr__ to avoid an infinite recursion
        super().__setattr__('_h6odj9348dh098d__obj', obj)
        super().__setattr__('_h6odj9348dh098d__attr', attr)

    @property
    def __class__(self):
        """This is necessary for faking our type."""
        return _deref_refs(self)[0].__class__

    def __getattr__(self, item):
        return getattr(*_deref_refs(self), item)

    def __setattr__(self, key, value):
        return setattr(*_deref_refs(self), key, value)

def add_types(*dir_ables):
    """Extends Ref support to other types. It can be called at any time."""
    global _dunder_ops, _dunder_rops, _supported_types

    new_dir_ables = set(dir_ables) - _supported_types
    if not new_dir_ables:
        return
    _dops = [d for t in new_dir_ables for d in dir(t)
             if (d[:2] == '__' == d[-2:]) and callable(getattr(t, d))]
    _dops = set(_dops).difference(_to_ignore)
    _new_dops = _dops - _dunder_ops
    _dunder_ops.update(_new_dops)
    _new_drops = set(d for d in _new_dops
                     if d.startswith('__r') and d[:2] + d[3:] in _dunder_ops)
    _dunder_rops.update(_new_drops)
    for dop in _new_dops:
        setattr(Ref, dop, _create_op(dop))
    _supported_types.update(new_dir_ables)

# Let's start with some default types...
add_types(*_default_types)

def test():
    test_torch = True
    # test_torch = False

    # General --------------------------------------------------------->

    class A:
        pass

    class B:
        def __init__(self, s):
            self.s = s
            self.a = A()

    b = B('word1 word2')
    s_ref = Ref(b, 's')
    assert 's_ref' + s_ref == 's_ref' + b.s
    assert s_ref + 's_ref' == b.s + 's_ref'
    assert s_ref + s_ref == b.s + b.s
    assert len(s_ref*3 + 'sdf') == len(b.s*3 + 'sdf')

    assert s_ref.split() == b.s.split()
    assert s_ref + 'ok' == b.s + 'ok'
    assert len(s_ref) == len(b.s)
    a_ref = Ref(b, 'a')
    a_ref.g = 23                # uses our __setattr__
    assert a_ref.g is b.a.g

    # Torch specific -------------------------------------------------->

    if test_torch:
        import torch as T           # I know, I know...

        class C:
            def __init__(self):
                self.M = T.randn(100, 100, dtype=T.float64)

        c = C()
        M_ref = Ref(c, 'M')
        try:
            M_ref @ M_ref           # must fail because '@' is missing
            assert False
        except TypeError:
            pass

        add_types(T.Tensor)         # adds '@' (and other stuff)
        MM = M_ref @ M_ref
        assert MM.allclose(c.M @ c.M)
        M3 = c.M * M_ref.svd(compute_uv=False)[1]
        # Note that [...] works even for scalars, while [:] doesn't.
        # M_ref *= T.svd(M_ref[...], compute_uv=False)[1]     # [...] hack!
        M_ref *= M_ref.svd(compute_uv=False)[1]           # no hack needed
        assert M_ref.allclose(M3)

    # Numpy specific -------------------------------------------------->

    import numpy as np          # I know, I know...

    class C:
        def __init__(self):
            self.M = np.random.randn(100, 100)

    c = C()
    M_ref = Ref(c, 'M')
    try:
        M_ref @ M_ref                   # must fail because '@' is missing
        assert False or test_torch      # ...unless we already tested torch
    except TypeError:
        pass

    add_types(np.ndarray)           # adds '@' (and other stuff)
    MM = M_ref @ M_ref
    assert np.allclose(MM, c.M @ c.M)
    M3 = c.M * np.linalg.svd(c.M, compute_uv=False)[1]
    # Note that [...] works even for scalars, while [:] doesn't.
    M_ref *= np.linalg.svd(M_ref[...], compute_uv=False)[1]     # [...] hack!
    assert np.allclose(M_ref, M3)
</code>```

Body:
My solution works seamlessly enough when one wants to access attributes, methods, or dunder methods (e.g. __rmul__) through a reference:

r = Ref(some_obj, 'some_attr')
M = r @ some_other_operand

It may not work at all when the reference is passed to a function:

M2 = compute_something(r)

That's because I have no way to intercept the access to r. For instance np.linalg.svd(r) doesn't work, but np.linalg.svd(r[...]) does because [...] lets us do the dereferencing. Luckily for me, pytorch supports r.svd(), which is very convenient and doesn't suffer from the same problem.

Let me know if you have a way to solve that problem.

EDIT: The problem above can be solved by modifying __bases__ of Ref so that issubclass believes our ref is a subclass of the correct type. Unfortunately, in Python 3, __bases__ can be written only during class creation. That's good enough if a ref keeps pointing to objects of the same type, but if that's not the case, we need to create another class each time the type changes, and we need to catch the modification right when it happens! That's impossible AFAICT.

EDIT2: One solution is to add or replace __getattribute__ on the object containing the reference we're referencing.

Anyway, I'll never use the code presented in this answer of mine. It was just an interesting exercise. Functions are first-class in Python, as we always say, but, unfortunately, references are not. One might misuse them, but don't we also say We're all adults here?.

Since it's difficult to know what dunder methods to support beforehand, I provide the function add_types which lets one add support for new types. For instance:

import torch as T             # I use `T` in honor of theano ;)
import numpy as np

add_types(T.Tensor, np.ndarray)

Here's my first attempt:

# TODO: Can we make this more robust and general?

_to_ignore = "new getattr getattribute setattr init class".split()
_default_types = [list, int, float]

_to_ignore = ['__' + n + '__' for n in _to_ignore]
_supported_types = set()
_dunder_ops = set()
_dunder_rops = set()

def _deref_refs(*objs):
    # TODO: inline this for efficiency?
    return [getattr(o._h6odj9348dh098d__obj, o._h6odj9348dh098d__attr)
                if isinstance(o, Ref) else o
            for o in objs]

def _create_op(name):
    def op(self, *args):
        obj, *args = _deref_refs(self, *args)
        return getattr(obj, name)(*args)

    def rop(self, *args):
        obj, *args = _deref_refs(self, *args)
        # Little hack: we can't remove an (r-)op (e.g. __radd__) so, when the
        #   referenced obj doesn't have it, we emulate its absence by falling
        #   back on the non-r version (e.g. __radd__ -> __add__) instead.
        rop = getattr(obj, name, None)
        if rop is not None:
            return rop(*args)
        # Switch to the non-r version of the op (and swap the operands).
        op_name = name[:2] + name[3:]           # __rXXX__ -> __XXX__
        return getattr(args[0], op_name)(obj, *args[1:])

    return rop if name in _dunder_rops else op

class Ref:
    def __init__(self, obj, attr):
        # 1. use mangling to avoid name conflicts
        # 2. use super().__setattr__ to avoid an infinite recursion
        super().__setattr__('_h6odj9348dh098d__obj', obj)
        super().__setattr__('_h6odj9348dh098d__attr', attr)

    @property
    def __class__(self):
        """This is necessary for faking our type."""
        return _deref_refs(self)[0].__class__

    def __getattr__(self, item):
        return getattr(*_deref_refs(self), item)

    def __setattr__(self, key, value):
        return setattr(*_deref_refs(self), key, value)

def add_types(*dir_ables):
    """Extends Ref support to other types. It can be called at any time."""
    global _dunder_ops, _dunder_rops, _supported_types

    new_dir_ables = set(dir_ables) - _supported_types
    if not new_dir_ables:
        return
    _dops = [d for t in new_dir_ables for d in dir(t)
             if (d[:2] == '__' == d[-2:]) and callable(getattr(t, d))]
    _dops = set(_dops).difference(_to_ignore)
    _new_dops = _dops - _dunder_ops
    _dunder_ops.update(_new_dops)
    _new_drops = set(d for d in _new_dops
                     if d.startswith('__r') and d[:2] + d[3:] in _dunder_ops)
    _dunder_rops.update(_new_drops)
    for dop in _new_dops:
        setattr(Ref, dop, _create_op(dop))
    _supported_types.update(new_dir_ables)

# Let's start with some default types...
add_types(*_default_types)

def test():
    test_torch = True
    # test_torch = False

    # General --------------------------------------------------------->

    class A:
        pass

    class B:
        def __init__(self, s):
            self.s = s
            self.a = A()

    b = B('word1 word2')
    s_ref = Ref(b, 's')
    assert 's_ref' + s_ref == 's_ref' + b.s
    assert s_ref + 's_ref' == b.s + 's_ref'
    assert s_ref + s_ref == b.s + b.s
    assert len(s_ref*3 + 'sdf') == len(b.s*3 + 'sdf')

    assert s_ref.split() == b.s.split()
    assert s_ref + 'ok' == b.s + 'ok'
    assert len(s_ref) == len(b.s)
    a_ref = Ref(b, 'a')
    a_ref.g = 23                # uses our __setattr__
    assert a_ref.g is b.a.g

    # Torch specific -------------------------------------------------->

    if test_torch:
        import torch as T           # I know, I know...

        class C:
            def __init__(self):
                self.M = T.randn(100, 100, dtype=T.float64)

        c = C()
        M_ref = Ref(c, 'M')
        try:
            M_ref @ M_ref           # must fail because '@' is missing
            assert False
        except TypeError:
            pass

        add_types(T.Tensor)         # adds '@' (and other stuff)
        MM = M_ref @ M_ref
        assert MM.allclose(c.M @ c.M)
        M3 = c.M * M_ref.svd(compute_uv=False)[1]
        # Note that [...] works even for scalars, while [:] doesn't.
        # M_ref *= T.svd(M_ref[...], compute_uv=False)[1]     # [...] hack!
        M_ref *= M_ref.svd(compute_uv=False)[1]           # no hack needed
        assert M_ref.allclose(M3)

    # Numpy specific -------------------------------------------------->

    import numpy as np          # I know, I know...

    class C:
        def __init__(self):
            self.M = np.random.randn(100, 100)

    c = C()
    M_ref = Ref(c, 'M')
    try:
        M_ref @ M_ref                   # must fail because '@' is missing
        assert False or test_torch      # ...unless we already tested torch
    except TypeError:
        pass

    add_types(np.ndarray)           # adds '@' (and other stuff)
    MM = M_ref @ M_ref
    assert np.allclose(MM, c.M @ c.M)
    M3 = c.M * np.linalg.svd(c.M, compute_uv=False)[1]
    # Note that [...] works even for scalars, while [:] doesn't.
    M_ref *= np.linalg.svd(M_ref[...], compute_uv=False)[1]     # [...] hack!
    assert np.allclose(M_ref, M3)


问:
Creating shared methods in Angular
I want to crate some methods and call them from html of different components. On the other hand, there is some approach as on How to call static method of other class in .html (not in .ts)?, but it is old and I am wondering if there is a better way in Angular 9 to call the method directly. Also it is possible to use a shared service and define shared method in this service, but I am looking another approach to call static methods directly from html. How can I do that?

demoBase.ts:

```<code>export class DemoBase {
    static demoMethod(id) {
        //
    }
}
</code>```

Then I want to call this method from html of another component:

list.component.ts:

```<code>import { DemoBase } from '@pages/demoBase';

//other stuff (I do not want to create a method here to access base method)
</code>```

list.component.html:

```<code><div><span [ngClass]="DemoBase.demoMethod(record.Id)">{{record.Name}}</span></div>
</code>```

答:
I believe services in Angular is what you are looking for?

They are shared with their data and methods as well. They can be shared at module level.

Look at this article for details.

Title: Creating shared methods in Angular

Body:
I want to crate some methods and call them from html of different components. On the other hand, there is some approach as on How to call static method of other class in .html (not in .ts)?, but it is old and I am wondering if there is a better way in Angular 9 to call the method directly. Also it is possible to use a shared service and define shared method in this service, but I am looking another approach to call static methods directly from html. How can I do that?

demoBase.ts:

export class DemoBase {
    static demoMethod(id) {
        //
    }
}

Then I want to call this method from html of another component:

list.component.ts:

import { DemoBase } from '@pages/demoBase';

//other stuff (I do not want to create a method here to access base method)

list.component.html:

{{record.Name}}


问:
Show notification then after 5 seconds navigation to other page
I want to create a notification. After 5 seconds the notification should vanish then it goes to another page.

```<code>export class AppComponent  {
name = 'Angular 5';
constructor(private router: Router) {
  var notify = new Notification('', {body: 'test'});
  setTimeout(notify.close.bind(notify), 5000);
  this.router.navigate(['/page1']);
  }
}
</code>```

However it navigates to the other page immediately; I can't see the notification.

Stackblize demo

答:
```<code>export class AppComponent  {
name = 'Angular 5';

    constructor(private router: Router) {
      var notify = new Notification('', {body: 'test'});
      setTimeout(()=> {
         notify.close.bind(notify);
         this.router.navigate(['/page1']);
      }, 5000);
      }

}
</code>```

Body:
I want to create a notification. After 5 seconds the notification should vanish then it goes to another page.

export class AppComponent  {
name = 'Angular 5';
constructor(private router: Router) {
  var notify = new Notification('', {body: 'test'});
  setTimeout(notify.close.bind(notify), 5000);
  this.router.navigate(['/page1']);
  }
}

However it navigates to the other page immediately; I can't see the notification.

Stackblize demo


问:
Nav bar background color not showing in Xcode
I have the following code:

```<code>      override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
    navigationController?.navigationBar.shadowImage = UIImage()
}
</code>```

and what this does is just remove the background color from the nav bar although it doesn't work right away.

https://drive.google.com/file/d/1MJLyTMEwr6CIeIl_ljAGR-uNBdUo-iBk/view?usp=sharing

Above is a google drive video of what is happening, its really hard to explain but I'll do my best. I have 3 steps in my app to set up and account, when I run the simulator for first step, the nav bar is white. I press the next button Then the second step the nav bar is white. When I go to the 3rd step though the nav bar is transparent which is what I want. Furthermore, when I then go back to steps 1 and 2 the nav bar is transparent.
I have tried reseting my simulator but I really have no idea what I am doing wrong. Someone please help

答:
You need to create a new UIViewController for each view in your Storyboard and wire it by Choosing the class in the Inspector on the right hand side of the storyboard... Your current code is only applied to the UIViewControllers that you told the Storyboard Editor to be of type ViewController. Split up your content to multiple classes and you can specify for each VC how the nav bar should look like.

Hope that helps, feel free to ask further questions.

Body:
I have the following code:

      override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
    navigationController?.navigationBar.shadowImage = UIImage()
}

and what this does is just remove the background color from the nav bar although it doesn't work right away.

https://drive.google.com/file/d/1MJLyTMEwr6CIeIl_ljAGR-uNBdUo-iBk/view?usp=sharing

Above is a google drive video of what is happening, its really hard to explain but I'll do my best. I have 3 steps in my app to set up and account, when I run the simulator for first step, the nav bar is white. I press the next button Then the second step the nav bar is white. When I go to the 3rd step though the nav bar is transparent which is what I want. Furthermore, when I then go back to steps 1 and 2 the nav bar is transparent.
I have tried reseting my simulator but I really have no idea what I am doing wrong. Someone please help


问:
Simple fetch and display using IPFS - CORS issue
I'm attempting to fetch the following image hosted on IPFS, and present it dynamically in a webpage:

https://ipfs.io/ipfs/QmcRD4wkPPi6dig81r5sLj9Zm1gDCL4zgpEj9CfuRrGbzF

I've got the following:

  <meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline' 'unsafe-eval' https: ;script-src 'unsafe-inline' 'unsafe-eval';">

```
</div>
</div>
</p>

<p>Firefox/chrome give the following error:</p>

<p>Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://ipfs.io/ipfs/QmcRD4wkPPi6dig81r5sLj9Zm1gDCL4zgpEj9CfuRrGbzF. (Reason: CORS request did not succeed)</p>

<p><strong>Does the "Same Origin Policy" in this error refer to the settings on the server or in the browser?</strong></p>

<p><em>N.b. this resource (https://ipfs.github.io/public-gateway-checker/) seems to imply that CORS requests should work on the ipfs.io server.</em></p>

<p><strong>What is the most simple way to fetch and display an image from a remote IPFS node, solely in the browser?</strong></p>

<p>Edit: I've managed to get something partially working, based on the examples at js.ipfs.io.</p>

<p>I still get CORS errors, but it does pull one chunk of text and display it (the image doesn't work still.</p>

<p>Why does this partially work?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>
<script src="https://unpkg.com/ipfs@0.41.0-rc.2/dist/index.min.js"></script>
<script>

async function main() {
  const container = document.getElementById('container')
  let node;
    node = await Ipfs.create({ repo: 'ipfs-' + Math.random()})
  const stream = node.cat('QmPChd2hVbrJ6bfo3WBcTW4iZnpHm8TEzWkLHmLpXhF68A')
  let data = ''

  for await (const chunk of stream) {
    console.log('chunk',chunk)
    data += chunk.toString()
  }
  document.getElementById('container').innerHTML = data

}
main()
</script>

<style>
  #container {
    background-color: green;
    width:100%;
    width:150px;
  }
</style>
</head>
<body>
<div id='container'>
</div>
</body>
</html></code>```

答:
The problem is with the browser, to protect from cross site request forgery attacks browsers don't allow requests from one origin(here being your localhost at which your code is running) to another origin(here being the site you are fetching your image from).
To overcome this you have actually 3 ways and a good explanation of all of them can be seen here :https://medium.com/@dtkatz/3-ways-to-fix-the-cors-error-and-how-access-control-allow-origin-works-d97d55946d9</p>

Body:
I'm attempting to fetch the following image hosted on IPFS, and present it dynamically in a webpage:

https://ipfs.io/ipfs/QmcRD4wkPPi6dig81r5sLj9Zm1gDCL4zgpEj9CfuRrGbzF

I've got the following:

  <meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline' 'unsafe-eval' https: ;script-src 'unsafe-inline' 'unsafe-eval';">

Firefox/chrome give the following error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://ipfs.io/ipfs/QmcRD4wkPPi6dig81r5sLj9Zm1gDCL4zgpEj9CfuRrGbzF. (Reason: CORS request did not succeed)

Does the "Same Origin Policy" in this error refer to the settings on the server or in the browser?

N.b. this resource (https://ipfs.github.io/public-gateway-checker/) seems to imply that CORS requests should work on the ipfs.io server.

What is the most simple way to fetch and display an image from a remote IPFS node, solely in the browser?

Edit: I've managed to get something partially working, based on the examples at js.ipfs.io.

I still get CORS errors, but it does pull one chunk of text and display it (the image doesn't work still.

Why does this partially work?


问:
Resource and ControllerLinkBuilder not found and deprecated
I am using Spring Boot 2.2.0.M1 with HATEOAS and Gradle.

```<code>implementation 'org.springframework.boot:spring-boot-starter-hateoas'
</code>```

Right now, Resource is not found by the IDE (IntelliJ IDEA 2018.3) and ControllerLinkBuilder is marked as deprecated.

```<code>package com.example.restfulwebservicegradle.user;

import static org.springframework.hateoas.server.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;

import com.example.restfulwebservicegradle.User;
import com.example.restfulwebservicegradle.UserDaoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.server.mvc.ControllerLinkBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.validation.Valid;
import java.net.URI;
import java.util.List;

@RestController
public class UserResource {

    @Autowired
    private UserDaoService service;

    @GetMapping("users/{id}")
    public Resource<User> retrieveUser(@PathVariable int id) {
        User user = service.findOne(id);

        if (user == null)
            throw new UserNotFoundException("id-" + id);

        // Resource not found
        Resource<User> resource = new Resource<User>(user);

        // Deprecated
        ControllerLinkBuilder linkTo = linkTo(methodOn(this.getClass()).retrieveAllUsers());

        resource.add(linkTo.withRel("all-users"));

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

The imports available according to the IDE are:

How can I solve this?

My goal is to found Resource from HATEOAS and to use the substitute of ControllerLinkBuilder.

答:
As mentioned by other fellow coders, many changes (deprecations) have happened in HATEOAS, so please use the following  code:

```<code>@RestController
public class UserResource {

    @Autowired
    private UserDaoService service;

    @GetMapping("users/{id}")
    public Resource<User> retrieveUser(@PathVariable int id) {
        User user = service.findOne(id);

        if (user == null)
            throw new UserNotFoundException("id-" + id);

        //Resource has been replaced by EntityModel
        EntityModel<User> resource = EntityModel.of(user);

        //ControllerLinkBuilder has been replace by WebMvcLinkBuilder
        Link link= WebMvcLinkBuilder.linkTo(methodOn(this.getClass()).retrieveAllUsers()).withRel("all-users");

        resource.add(link);
        return resource;
    }
}
</code>```

And this is spring-hateoas dependency, you should add this to pom.xml:

```<code><dependency>
    <groupId>org.springframework.hateoas</groupId>
    <artifactId>spring-hateoas</artifactId>
    <version>1.1.0.RELEASE</version>
</dependency>
</code>```

Body:
I am using Spring Boot 2.2.0.M1 with HATEOAS and Gradle.

implementation 'org.springframework.boot:spring-boot-starter-hateoas'

Right now, Resource is not found by the IDE (IntelliJ IDEA 2018.3) and ControllerLinkBuilder is marked as deprecated.

package com.example.restfulwebservicegradle.user;

import static org.springframework.hateoas.server.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;

import com.example.restfulwebservicegradle.User;
import com.example.restfulwebservicegradle.UserDaoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.server.mvc.ControllerLinkBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.validation.Valid;
import java.net.URI;
import java.util.List;

@RestController
public class UserResource {

    @Autowired
    private UserDaoService service;

    @GetMapping("users/{id}")
    public Resource<User> retrieveUser(@PathVariable int id) {
        User user = service.findOne(id);

        if (user == null)
            throw new UserNotFoundException("id-" + id);

        // Resource not found
        Resource<User> resource = new Resource<User>(user);

        // Deprecated
        ControllerLinkBuilder linkTo = linkTo(methodOn(this.getClass()).retrieveAllUsers());

        resource.add(linkTo.withRel("all-users"));

        return resource;
    }
}

The imports available according to the IDE are:

How can I solve this?

My goal is to found Resource from HATEOAS and to use the substitute of ControllerLinkBuilder.

Body:
As mentioned by other fellow coders, many changes (deprecations) have happened in HATEOAS, so please use the following  code:

@RestController
public class UserResource {

    @Autowired
    private UserDaoService service;

    @GetMapping("users/{id}")
    public Resource<User> retrieveUser(@PathVariable int id) {
        User user = service.findOne(id);

        if (user == null)
            throw new UserNotFoundException("id-" + id);

        //Resource has been replaced by EntityModel
        EntityModel<User> resource = EntityModel.of(user);

        //ControllerLinkBuilder has been replace by WebMvcLinkBuilder
        Link link= WebMvcLinkBuilder.linkTo(methodOn(this.getClass()).retrieveAllUsers()).withRel("all-users");

        resource.add(link);
        return resource;
    }
}

And this is spring-hateoas dependency, you should add this to pom.xml:

<dependency>
    <groupId>org.springframework.hateoas</groupId>
    <artifactId>spring-hateoas</artifactId>
    <version>1.1.0.RELEASE</version>
</dependency>


问:
Increase the Terminal width in Visual Studio Code
My R Interactive Terminal in Visual Studio Code is too short, cutting-off or wrapping the returned values too early, leading to confusion during data analysis or feature engineering.  Is there any way for me to increase the width of the R Interactive Terminal?

Specifically, I am referring to the Terminal Window that is used to display processed code results from R, Python or any other interpreter:
https://webzest.com/vsc_terminal.png

答:
you can collapse the sidebar to gain some more space. the toggle sidebar command is under View/Appearance/Show Side Bar and the keyboard shortcut is ⌘+B on macos or ⌃+B on windows. see attached screen image.

edit: thanks for sharing a screen-print, that helps to explain what you are seeing. sorry i misunderstood... i am wondering if the issue is related to the R shell you are running.
you can see in the attached screen images that the zsh shell uses all of the space available to the terminal panel.
...also, this is on macos, i have not tried windows but that could be part of it.

can you try some other shells and see if they are affected in the same way?


问:
javascript array and jsf/richfaces
I have the following code in javascript:

```<code>        <script type="text/javascript"
            src="#{facesContext.externalContext.requestContextPath}/js/sample-points.js"></script>

        <script type="text/javascript">//<![CDATA[
            var cloudmade = new CM.Tiles.CloudMade.Web({key: 'bbb'});
            var map = new CM.Map('cm-example', cloudmade);
            map.setCenter(new CM.LatLng(51.50874, 22.76367), 4);

            var markers = [];
            for (var i = 0; i < samplePoints.length; i++) {
                markers.push(new CM.Marker(new CM.LatLng(samplePoints[i][0], samplePoints[i][1])));
            }

            var clusterer = new CM.MarkerClusterer(map, {clusterRadius: 70});
            clusterer.addMarkers(markers);
        //]]></script>
</code>```

"samplePoints" is an array of coordinates which I can use to show markers on the map.

Map is showing here:

```<code><div id="cm-example" style="width: 99.5%; height: 600px"></div>
</code>```

How can I provide this array from jsf/richfaces without using file (e.g. I want to fetch those data from db, create array and send to this script)?

Thanks

答:
Just let JSF print it as if it is JavaScript code.

Replace

```<code>var markers = [];
for (var i = 0; i < samplePoints.length; i++) {
    markers.push(new CM.Marker(new CM.LatLng(samplePoints[i][0], samplePoints[i][1])));
}
</code>```

by (assuming Facelets)

var markers = [];
<ui:repeat value="#{bean.samplePoints}" var="samplePoint">
    markers.push(new CM.Marker(new CM.LatLng(#{samplePoint[0]}, #{samplePoint[1]})));
</ui:repeat>
```

where #{bean.samplePoints} returns a List<BigDecimal[]> or something.

ContentLicense: CC BY-SA 3.0

Title: javascript array and jsf/richfaces

Body:
I have the following code in javascript:

"samplePoints" is an array of coordinates which I can use to show markers on the map.

Map is showing here:

How can I provide this array from jsf/richfaces without using file (e.g. I want to fetch those data from db, create array and send to this script)?

Thanks

Body:
Just let JSF print it as if it is JavaScript code.

Replace

var markers = [];
for (var i = 0; i < samplePoints.length; i++) {
    markers.push(new CM.Marker(new CM.LatLng(samplePoints[i][0], samplePoints[i][1])));
}

by (assuming Facelets)

var markers = [];
<ui:repeat value="#{bean.samplePoints}" var="samplePoint">
    markers.push(new CM.Marker(new CM.LatLng(#{samplePoint[0]}, #{samplePoint[1]})));
</ui:repeat>

where #{bean.samplePoints} returns a List<BigDecimal[]> or something.


问:
Pandas: how to treat strange time format
I have the following Pandas dataframe, where the time (duration) is given in a very strange format:

```<code>Person   Activity   Duration
1        A          1 00:00
2        A          1 00:00
3        B          0 21:17
4        C          0 17:11
</code>```

Where 1 00:00 means 24 hours, and 0 21:17 means 0 days and 21:17 hours, which is to say just 21:17 hours. A quick look at the dtypes returns:

```<code>In[1]: df.dtypes
Out[1]:
Person         object
Activity       object
Duration       object
dtype: object
</code>```

How can I consistently treat the Duration column to return 24 if the value is 1 00:00, and the decimal value of the duration if I have 0 21:17? The decimal value of 0 21:17 would be 21.283.

The outcome should be:

```<code>Person   Activity   Duration
1        A          24
2        A          24
3        B          21.283
4        C          17.183
</code>```

答:
As you mentioned that it wont go beyond 1 00:00 that is 24:00, there is a simpler way:

```<code>'''
Person  Activity    Duration
1   A   1 00:00
2   A   1 00:00
3   B   0 21:17
4   C   0 17:11
'''

import pandas as pd

df = pd.read_clipboard("\t")
</code>```

.

```<code>   Person Activity Duration
0       1        A  1 00:00
1       2        A  1 00:00
2       3        B  0 21:17
3       4        C  0 17:11
</code>```

.

```<code>df['Duration'] = df['Duration'].str.split(' ')

df['Duration'] = ['24:00' if int(val[0]) == 1 else val[1] for val in df['Duration']]

print(df)
</code>```

.

```<code>   Person Activity Duration
0       1        A    24:00
1       2        A    24:00
2       3        B    21:17
3       4        C    17:11
</code>```

Body:
I have the following Pandas dataframe, where the time (duration) is given in a very strange format:

Person   Activity   Duration
1        A          1 00:00
2        A          1 00:00
3        B          0 21:17
4        C          0 17:11

Where 1 00:00 means 24 hours, and 0 21:17 means 0 days and 21:17 hours, which is to say just 21:17 hours. A quick look at the dtypes returns:

In[1]: df.dtypes
Out[1]:
Person         object
Activity       object
Duration       object
dtype: object

How can I consistently treat the Duration column to return 24 if the value is 1 00:00, and the decimal value of the duration if I have 0 21:17? The decimal value of 0 21:17 would be 21.283.

The outcome should be:

Person   Activity   Duration
1        A          24
2        A          24
3        B          21.283
4        C          17.183

Body:
As you mentioned that it wont go beyond 1 00:00 that is 24:00, there is a simpler way:

'''
Person  Activity    Duration
1   A   1 00:00
2   A   1 00:00
3   B   0 21:17
4   C   0 17:11
'''

import pandas as pd

df = pd.read_clipboard("\t")

.

   Person Activity Duration
0       1        A  1 00:00
1       2        A  1 00:00
2       3        B  0 21:17
3       4        C  0 17:11

.

df['Duration'] = df['Duration'].str.split(' ')

df['Duration'] = ['24:00' if int(val[0]) == 1 else val[1] for val in df['Duration']]

print(df)

.

   Person Activity Duration
0       1        A    24:00
1       2        A    24:00
2       3        B    21:17
3       4        C    17:11


问:
How to get next (or previous) enum value in C#
I have an enum which is defined like this:

```<code>public enum eRat { A = 0, B=3, C=5, D=8 };
</code>```

So given value eRat.B, I want to get the next one which is eRat.C

The solution I see is (without range checking)

```<code>Array a = Enum.GetValues(typeof(eRat));
int i=0 ;
for (i = 0; i < a.GetLength(); i++)
{
       if (a.GetValue(i) == eRat.B)
            break;
}
return (eRat)a.GetValue(i+1):
</code>```

Now that is too much complexity, for something that simple. Do you know any better solution?? Something like eRat.B+1 or Enum.Next(Erat.B)?

Thanks

答:
You can add and remove integers to an enum to obtain the next value. The only problem is that integer operations on the enum will not check the validity of the enum itself, thus could set "invalid" values.

But you can combine the ++enum and the Enum.IsDefined() to obtain a simple way to get next and previous values of your enum. This would be inefficient in your case since the integer values are not continuous, but if you have continuous integers then it works nicely, and one can check when the ++enum is out of range. Check the next example.

```<code> public enum level
    {
        a = 0,
        b = 1,
        c = 2,
        d = 3,
        e = 4
    }

private static void Main(string[] args)
    {
        var levelValue = level.a;
        Console.WriteLine(levelValue);
        ++levelValue;
        Console.WriteLine(levelValue);
        ++levelValue;
        Console.WriteLine(levelValue);
        ++levelValue;
        Console.WriteLine(levelValue);
        ++levelValue;
        Console.WriteLine(levelValue);
        ++levelValue;
        Console.WriteLine(Enum.IsDefined(typeof(Program.level), levelValue));
        Console.WriteLine(levelValue);
        --levelValue;
        Console.WriteLine(levelValue);
        --levelValue;
        Console.WriteLine(levelValue);
        --levelValue;
        Console.WriteLine(levelValue);
        --levelValue;
        Console.WriteLine(levelValue);
        --levelValue;
        Console.WriteLine(Enum.IsDefined(typeof(Program.level), levelValue));
        Console.WriteLine(levelValue);
        --levelValue;
        Console.WriteLine(Enum.IsDefined(typeof(Program.level), levelValue));
        Console.WriteLine(levelValue);
    }
</code>```

The output for this would be:

```<code>a
b
c
d
e
False
5
e
d
c
b
True
a
False
-1
</code>```

OwnerDisplayName: husayt

Body:
I have an enum which is defined like this:

public enum eRat { A = 0, B=3, C=5, D=8 };

So given value eRat.B, I want to get the next one which is eRat.C

The solution I see is (without range checking)

Array a = Enum.GetValues(typeof(eRat));
int i=0 ;
for (i = 0; i < a.GetLength(); i++)
{
       if (a.GetValue(i) == eRat.B)
            break;
}
return (eRat)a.GetValue(i+1):

Now that is too much complexity, for something that simple. Do you know any better solution?? Something like eRat.B+1 or Enum.Next(Erat.B)?

Thanks

Body:
You can add and remove integers to an enum to obtain the next value. The only problem is that integer operations on the enum will not check the validity of the enum itself, thus could set "invalid" values.

But you can combine the ++enum and the Enum.IsDefined() to obtain a simple way to get next and previous values of your enum. This would be inefficient in your case since the integer values are not continuous, but if you have continuous integers then it works nicely, and one can check when the ++enum is out of range. Check the next example.

 public enum level
    {
        a = 0,
        b = 1,
        c = 2,
        d = 3,
        e = 4
    }

private static void Main(string[] args)
    {
        var levelValue = level.a;
        Console.WriteLine(levelValue);
        ++levelValue;
        Console.WriteLine(levelValue);
        ++levelValue;
        Console.WriteLine(levelValue);
        ++levelValue;
        Console.WriteLine(levelValue);
        ++levelValue;
        Console.WriteLine(levelValue);
        ++levelValue;
        Console.WriteLine(Enum.IsDefined(typeof(Program.level), levelValue));
        Console.WriteLine(levelValue);
        --levelValue;
        Console.WriteLine(levelValue);
        --levelValue;
        Console.WriteLine(levelValue);
        --levelValue;
        Console.WriteLine(levelValue);
        --levelValue;
        Console.WriteLine(levelValue);
        --levelValue;
        Console.WriteLine(Enum.IsDefined(typeof(Program.level), levelValue));
        Console.WriteLine(levelValue);
        --levelValue;
        Console.WriteLine(Enum.IsDefined(typeof(Program.level), levelValue));
        Console.WriteLine(levelValue);
    }

The output for this would be:

a
b
c
d
e
False
5
e
d
c
b
True
a
False
-1


问:
Use aggreagted row values in multiple columns to form new column in Python
I have the following dataframe in which each record has either D or E filled. Never both.
The following is the dataframe df, with dummy records for 2 months April(Current) & March. (Originally the data will have 12 months, with values for column B reoccurring )

I am looking to:
1. groupby column A for April month sum(column D) / sum(column E)

```<code>df.groupby(['A', 'C']).df.D/df.E.sum().rolling(1, min_periods=1).mean()
</code>```

Alternatively tried,

```<code>def divide_two_cols(df):
    return df['D'].sum() / df['E'].sum()

df.groupby(['A', 'C']).divide_two_cols(df).sum().rolling(1, min_periods=1).sum()
</code>```

Apply same to last two months (March & April)

```<code>df.groupby(['A', 'C']).df.D/df.E.sum().rolling(2, min_periods=1).mean()
</code>```

Any advise on why the either approach is not working to form a new column using sum of two other columns.

答:
Since you are trying to group by at month level, you should ideally try to extract the month from column C which will make things easier for you.

```<code>df['F'] = df.C.apply(lambda x: x.split("-")[1])

print(df)
   A      C     D    E    F
0  W  6-Mar   NaN  1.0  Mar
1  W  6-Mar   4.0  NaN  Mar
2  W  6-Mar   NaN  1.0  Mar
3  W  6-Apr   2.0  NaN  Apr
4  W  6-Apr   NaN  2.0  Apr
5  Y  6-Mar  10.0  NaN  Mar
6  Y  6-Mar   NaN  2.0  Mar
7  Y  6-Apr   6.0  NaN  Apr
8  Y  6-Apr   NaN  2.0  Apr
</code>```

For Part 1 (Column G is the column you are looking for):

```<code>df_grouped1 = df.groupby(['A', 'F'])['D', 'E'].sum().reset_index()
df_grouped1['G'] = df_grouped1['D']/df_grouped1['E']

print(df_grouped1)
    A   F    D     E     G
0   W   Apr  2.0  2.0   1.0
1   W   Mar  4.0  2.0   2.0
2   Y   Apr  6.0  2.0   3.0
3   Y   Mar 10.0  2.0   5.0
</code>```

For Part 2 (Not sure if I understood this part of the question correctly. Correct me if I am wrong) :

```<code>print(df_grouped1.groupby('A')['G'].mean().reset_index())

   A    G
0  W  1.5
1  Y  4.0
</code>```

Body:
I have the following dataframe in which each record has either D or E filled. Never both.
The following is the dataframe df, with dummy records for 2 months April(Current) & March. (Originally the data will have 12 months, with values for column B reoccurring )

I am looking to:
1. groupby column A for April month sum(column D) / sum(column E)

df.groupby(['A', 'C']).df.D/df.E.sum().rolling(1, min_periods=1).mean()

Alternatively tried,

def divide_two_cols(df):
    return df['D'].sum() / df['E'].sum()

df.groupby(['A', 'C']).divide_two_cols(df).sum().rolling(1, min_periods=1).sum()

Apply same to last two months (March & April)

df.groupby(['A', 'C']).df.D/df.E.sum().rolling(2, min_periods=1).mean()

Any advise on why the either approach is not working to form a new column using sum of two other columns.

Body:
Since you are trying to group by at month level, you should ideally try to extract the month from column C which will make things easier for you.

df['F'] = df.C.apply(lambda x: x.split("-")[1])

print(df)
   A      C     D    E    F
0  W  6-Mar   NaN  1.0  Mar
1  W  6-Mar   4.0  NaN  Mar
2  W  6-Mar   NaN  1.0  Mar
3  W  6-Apr   2.0  NaN  Apr
4  W  6-Apr   NaN  2.0  Apr
5  Y  6-Mar  10.0  NaN  Mar
6  Y  6-Mar   NaN  2.0  Mar
7  Y  6-Apr   6.0  NaN  Apr
8  Y  6-Apr   NaN  2.0  Apr

For Part 1 (Column G is the column you are looking for):

df_grouped1 = df.groupby(['A', 'F'])['D', 'E'].sum().reset_index()
df_grouped1['G'] = df_grouped1['D']/df_grouped1['E']

print(df_grouped1)
    A   F    D     E     G
0   W   Apr  2.0  2.0   1.0
1   W   Mar  4.0  2.0   2.0
2   Y   Apr  6.0  2.0   3.0
3   Y   Mar 10.0  2.0   5.0

For Part 2 (Not sure if I understood this part of the question correctly. Correct me if I am wrong) :

print(df_grouped1.groupby('A')['G'].mean().reset_index())

   A    G
0  W  1.5
1  Y  4.0


问:
Selection and extraction of points (shapefile) within a polygon in R
I have two shape-files; one is a point file (some information for world) and the other is a 21-countries shape-file.

I need to extract the points which falls with in a country.
I have to repeat this step in 21 times in QGIS or ArcGIS.

Is there any way to do this in R and if is in batch processing, that would be really great as I have to repeat this for other 4 data sets as well.
Thanks in advance

答:
Here is an example polygons shapefile and how you can read it into R.

```<code>library(raster)
# example polygons filename
f <- system.file("external/lux.shp", package="raster")
pol <- shapefile(f)
</code>```

I do not have a matching points file, so I generate some points for this example

```<code>pts <- spsample(pol, 5, type="regular")
crs(pts) <- crs(pol)
</code>```

To see what area the points fall in you can use over or extract. They both return the values in the order of the points, but extract also adds the (sequential) "point id" --- this is primarily for when you have overlapping polygons, such that a point might fall in two polygons.

```<code>over(pts, pol)
#  ID_1       NAME_1 ID_2           NAME_2 AREA
#1    3   Luxembourg    9 Esch-sur-Alzette  251
#2    2 Grevenmacher    7           Remich  129
#3    3   Luxembourg   11           Mersch  233
#4    2 Grevenmacher    6       Echternach  188
#5    1     Diekirch    1         Clervaux  312

extract(pol, pts)
#  point.ID poly.ID ID_1       NAME_1 ID_2           NAME_2 AREA
#1        1      10    3   Luxembourg    9 Esch-sur-Alzette  251
#2        2       7    2 Grevenmacher    7           Remich  129
#3        3      12    3   Luxembourg   11           Mersch  233
#4        4       6    2 Grevenmacher    6       Echternach  188
#5        5       1    1     Diekirch    1         Clervaux  312
</code>```

If you just want the intersection, say of the points that fall in "Grenmacher", like you may want to do with your countries, you can

```<code>g <- pol[pol$NAME_1 == "Grevenmacher", ]
i <- intersect(pts, g)
i
#class       : SpatialPointsDataFrame
#features    : 2
#extent      : 6.27111, 6.27111, 49.53585, 49.7887  (xmin, xmax, ymin, ymax)
#crs         : +proj=longlat +datum=WGS84 +no_defs
#variables   : 5
#names       : ID_1,       NAME_1, ID_2,     NAME_2, AREA
#min values  :    2, Grevenmacher,    6, Echternach,  129
#max values  :    2, Grevenmacher,    7,     Remich,  188
</code>```

And perhaps write that back to disk like this

```<code>shapefile(i, "test.shp")
</code>```

Body:
Here is an example polygons shapefile and how you can read it into R.

library(raster)
# example polygons filename
f <- system.file("external/lux.shp", package="raster")
pol <- shapefile(f)

I do not have a matching points file, so I generate some points for this example

pts <- spsample(pol, 5, type="regular")
crs(pts) <- crs(pol)

To see what area the points fall in you can use over or extract. They both return the values in the order of the points, but extract also adds the (sequential) "point id" --- this is primarily for when you have overlapping polygons, such that a point might fall in two polygons.

over(pts, pol)
#  ID_1       NAME_1 ID_2           NAME_2 AREA
#1    3   Luxembourg    9 Esch-sur-Alzette  251
#2    2 Grevenmacher    7           Remich  129
#3    3   Luxembourg   11           Mersch  233
#4    2 Grevenmacher    6       Echternach  188
#5    1     Diekirch    1         Clervaux  312

extract(pol, pts)
#  point.ID poly.ID ID_1       NAME_1 ID_2           NAME_2 AREA
#1        1      10    3   Luxembourg    9 Esch-sur-Alzette  251
#2        2       7    2 Grevenmacher    7           Remich  129
#3        3      12    3   Luxembourg   11           Mersch  233
#4        4       6    2 Grevenmacher    6       Echternach  188
#5        5       1    1     Diekirch    1         Clervaux  312

If you just want the intersection, say of the points that fall in "Grenmacher", like you may want to do with your countries, you can

g <- pol[pol$NAME_1 == "Grevenmacher", ]
i <- intersect(pts, g)
i
#class       : SpatialPointsDataFrame
#features    : 2
#extent      : 6.27111, 6.27111, 49.53585, 49.7887  (xmin, xmax, ymin, ymax)
#crs         : +proj=longlat +datum=WGS84 +no_defs
#variables   : 5
#names       : ID_1,       NAME_1, ID_2,     NAME_2, AREA
#min values  :    2, Grevenmacher,    6, Echternach,  129
#max values  :    2, Grevenmacher,    7,     Remich,  188

And perhaps write that back to disk like this

shapefile(i, "test.shp")


问:
Terminate process when timeout has been reached and process output in Rust
I'm trying to consume output from a process in Rust. If the process doesn't terminate after a certain time, I want to terminate/kill it. Ideally I'd like to wrap everything in a generator so that I can iterate the output line by line, but I'm not experienced enough for that in Rust yet.

Here's my code (src/main.rs), using the subprocess crate:

use subprocess::{Popen, PopenConfig, Redirection};
use std::io::Read;
use std::time::Duration;

fn main() {
    let mut p = Popen::create(&["bash", "-c", "echo \"Hi There!\"; sleep 1000"], PopenConfig {stdout: Redirection::Pipe, ..Default::default()}, ).unwrap();
    let mut output = p.stdout.take().unwrap();

    let thread = std::thread::spawn(move || {
        let three_secs = Duration::from_secs(3);
        let one_sec = Duration::from_secs(1);
        let r = p.wait_timeout(three_secs).unwrap();
        match r {
            None => {
                println!("Wait timed out, terminating process");
                p.terminate().unwrap();
                let r = p.wait_timeout(one_sec).unwrap();
                match r {
                    None => {
                        println!("Termination didn't seem to work, killing");
                        p.kill().unwrap();
                    },
                    Some(_) => {
                        println!("Terminated process successfully");
                    },
                }
                p.wait().unwrap();},
            Some(_) => { println!("Process returned");},
        }
        println!("Everything fine");
    });

    println!("Starting to read output");
    let mut output_str = String::new();
    output.read_to_string(&mut output_str).unwrap();
    println!("Done reading output");
    thread.join().unwrap();

    println!("Output: {}", output_str);
    println!("Hello, world!");
}
```

<p>I'd expect the following output:</p>

```Starting to read output
Wait timed out, terminating process
Terminated process successfully
Everything fine
Done reading output
Output: Hi There!

Hello, world!
```

<p>and the process finishing after three seconds. But what I get is</p>

```Starting to read output
Wait timed out, terminating process
Terminated process successfully
Everything fine
```

<p>and the process doesn't terminate.</p>

<p>For completeness, here is my <code>Cargo.toml</code> to go along with the <code>src/main.rs</code> from above:</p>

```[package]
name = "subproc"
version = "0.1.0"
authors = ["<snip>"]
edition = "2018"

[dependencies]
subprocess = "0.2.4"
```

答:
With the help of Jack O'Connor, the author of the os_pipe library, I managed to write a solution that will read the process output, and do the timeout waiting and killing in another thread. Be advised that this solution will only kill the launched process, not its children, you'll need more handling if your child process has children itself.

use std::process::{Command, Stdio};
use std::io::{BufRead, BufReader};
use std::thread;
use std::time;

fn main() {
    const TIMEOUT : i32 = 5;
    let mut cmd = Command::new("bash");
    cmd.arg("-c").arg("for ((i=1000; i > 0; i--)); do echo \"$i bottles of beer on the wall\"; sleep 1; done");
    cmd.stdout(Stdio::piped());
    let mut child = cmd.spawn().unwrap();
    let stdout = child.stdout.take().unwrap();

    let thread = thread::spawn(move || {
        for _ in 0..TIMEOUT {
            if let Ok(Some(_)) = child.try_wait() {
                return;
            }
            thread::sleep(time::Duration::from_secs(1));
        }

        child.kill().unwrap();
    });

    let reader = BufReader::new(stdout);
    for line in reader.lines() {
        println!("line: {}", line.unwrap());
    }
    thread.join().unwrap();

    println!("Hello, world!");
}
```

Body:
I'm trying to consume output from a process in Rust. If the process doesn't terminate after a certain time, I want to terminate/kill it. Ideally I'd like to wrap everything in a generator so that I can iterate the output line by line, but I'm not experienced enough for that in Rust yet.

Here's my code (src/main.rs), using the subprocess crate:

use subprocess::{Popen, PopenConfig, Redirection};
use std::io::Read;
use std::time::Duration;

fn main() {
    let mut p = Popen::create(&["bash", "-c", "echo \"Hi There!\"; sleep 1000"], PopenConfig {stdout: Redirection::Pipe, ..Default::default()}, ).unwrap();
    let mut output = p.stdout.take().unwrap();

    let thread = std::thread::spawn(move || {
        let three_secs = Duration::from_secs(3);
        let one_sec = Duration::from_secs(1);
        let r = p.wait_timeout(three_secs).unwrap();
        match r {
            None => {
                println!("Wait timed out, terminating process");
                p.terminate().unwrap();
                let r = p.wait_timeout(one_sec).unwrap();
                match r {
                    None => {
                        println!("Termination didn't seem to work, killing");
                        p.kill().unwrap();
                    },
                    Some(_) => {
                        println!("Terminated process successfully");
                    },
                }
                p.wait().unwrap();},
            Some(_) => { println!("Process returned");},
        }
        println!("Everything fine");
    });

    println!("Starting to read output");
    let mut output_str = String::new();
    output.read_to_string(&mut output_str).unwrap();
    println!("Done reading output");
    thread.join().unwrap();

    println!("Output: {}", output_str);
    println!("Hello, world!");
}

I'd expect the following output:

Starting to read output
Wait timed out, terminating process
Terminated process successfully
Everything fine
Done reading output
Output: Hi There!

Hello, world!

and the process finishing after three seconds. But what I get is

Starting to read output
Wait timed out, terminating process
Terminated process successfully
Everything fine

and the process doesn't terminate.

For completeness, here is my Cargo.toml to go along with the src/main.rs from above:

[package]
name = "subproc"
version = "0.1.0"
authors = ["<snip>"]
edition = "2018"

[dependencies]
subprocess = "0.2.4"


问:
How to skip corrupt (non-serializable) messages in Spring Kafka Consumer?
This question is for Spring Kafka, related to Apache Kafka with High Level Consumer: Skip corrupted messages

Is there a way to configure Spring Kafka consumer to skip a record that cannot be read/processed (is corrupt)?

I am seeing a situation where the consumer gets stuck on the same record if it cannot be deserialized. This is the error the consumer throws.

```<code>Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of java.time.LocalDate: no long/Long-argument constructor/factory method to deserialize from Number value
</code>```

The consumer polls the topic and just keeps printing the same error in a loop till program is killed.

In a @KafkaListener that has the following Consumer factory configurations,

```<code>Map<String, Object> props = new HashMap<>();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class);
</code>```

答:
In case you are using older version of kafka, in a @KafkaListener set the following Consumer factory configurations.

```<code> Map<String, Object> props = new HashMap<>();
    props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
    props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
    props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, CustomDeserializer.class);
</code>```

Here is the code for CustomDeserializer:

```<code> import java.util.Map;
    import org.apache.kafka.common.serialization.Deserializer;
    import com.fasterxml.jackson.databind.ObjectMapper;
    public class CustomDeserializer implements Deserializer<Object>
    {
        @Override
        public void configure( Map<String, ?> configs, boolean isKey )
        {
        }

        @Override
        public Object deserialize( String topic, byte[] data )
        {
            ObjectMapper mapper = new ObjectMapper();
            Object object = null;
            try
            {
                object = mapper.readValue(data, Object.class);
            }
            catch ( Exception exception )
            {
                System.out.println("Error in deserializing bytes " + exception);
            }
            return object;
        }

        @Override
        public void close()
        {
        }
    }

</code>```

Since I want my code to be generic enough to read any kind of json,
object = mapper.readValue(data, Object.class); I am converting it to Object.class. And as we are catching exception here, it won't be retried once read.

Body:
This question is for Spring Kafka, related to Apache Kafka with High Level Consumer: Skip corrupted messages

Is there a way to configure Spring Kafka consumer to skip a record that cannot be read/processed (is corrupt)?

I am seeing a situation where the consumer gets stuck on the same record if it cannot be deserialized. This is the error the consumer throws.

Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of java.time.LocalDate: no long/Long-argument constructor/factory method to deserialize from Number value

The consumer polls the topic and just keeps printing the same error in a loop till program is killed.

In a @KafkaListener that has the following Consumer factory configurations,

Map<String, Object> props = new HashMap<>();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class);

Body:
In case you are using older version of kafka, in a @KafkaListener set the following Consumer factory configurations.

 Map<String, Object> props = new HashMap<>();
    props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
    props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
    props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, CustomDeserializer.class);

Here is the code for CustomDeserializer:

 import java.util.Map;
    import org.apache.kafka.common.serialization.Deserializer;
    import com.fasterxml.jackson.databind.ObjectMapper;
    public class CustomDeserializer implements Deserializer<Object>
    {
        @Override
        public void configure( Map<String, ?> configs, boolean isKey )
        {
        }

        @Override
        public Object deserialize( String topic, byte[] data )
        {
            ObjectMapper mapper = new ObjectMapper();
            Object object = null;
            try
            {
                object = mapper.readValue(data, Object.class);
            }
            catch ( Exception exception )
            {
                System.out.println("Error in deserializing bytes " + exception);
            }
            return object;
        }

        @Override
        public void close()
        {
        }
    }

Since I want my code to be generic enough to read any kind of json,
object = mapper.readValue(data, Object.class); I am converting it to Object.class. And as we are catching exception here, it won't be retried once read.


问:
Display current user data from firebase database (web)
Hello!

I've been working on a web project where a user is able to sign up and log in. I wanted to add a profile too, where some info they've provided could be diplayed on the page 'Profile'.

I've already used firebase auth (with email & password) and rt database to store extra info like 'Name', 'Bio', etc.

What I seem to not understand is how to retrieve the info that's
  stored on the database and display it on a
 tag on the
  profile page.

I've already tried solutions from other questions asked in here but none seemed to work for me.

This is how my database is looking:

```<code>users:
|
+-uid1
 |
 +-Name
 |
 +-Gender..
|
+-uid2
 |
 +-Name
 |
 +-Gender..
</code>```

Here is some code for the profile page:

What i was trying to do here is get the current user that's logged
  in and display the name on the profile - on a
 tag that has an id=username.

```<code>    //getting reference to the apps
   const auth = firebase.auth();
   const database = firebase.database();
   //also creating table 'users' on database
   const rootRef = database.ref('users');

// ------------------------------------//

   //Check if signed in
    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        // User is signed in.

    database.ref('/users/'+ userId).on('value')
    .then(function(snapshot) {
      var snapVal = snapshot.val();
      displayName.innerHTML = snapVal.Name
      var name = diplayName
      document.getElementById("username").innerHTML = "Welcome: " + name + "!";
    })
  } else {
    // No user is signed in.
    window.location = "login.html"
  }
});
</code>```

When I tested the code I got this error on the console:

```<code>Error: Query.on failed: Was called with 1 argument. Expects at least 2.
</code>```

Also, I don't really know if I am using this function correctly.

 Should I replace 'userId' with something else?

database.ref('/users/'+ userId).on('value')

Thank you for reading this and have a nice day!

答:
You're not setting userId to anything yet. When your onAuthStateChanged callback is called, and user has a value, you know that a user is signed in. At that point you can get that user's UID by doing user.uid.

So something like:

```<code>firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    database.ref('/users/'+ user.uid).once('value')
    .then(function(snaphot) {
      document.getElementById("username").innerText = "Welcome: " + snapshot.val().Name;
    })
  } else {
    window.location = "login.html"
  }
});
</code>```

The Name in snapshot.val().Name needs to match whatever property from the user node in the database you want to show

Body:
Hello!

I've been working on a web project where a user is able to sign up and log in. I wanted to add a profile too, where some info they've provided could be diplayed on the page 'Profile'.

I've already used firebase auth (with email & password) and rt database to store extra info like 'Name', 'Bio', etc.

What I seem to not understand is how to retrieve the info that's
  stored on the database and display it on a
 tag on the
  profile page.

I've already tried solutions from other questions asked in here but none seemed to work for me.

This is how my database is looking:

users:
|
+-uid1
 |
 +-Name
 |
 +-Gender..
|
+-uid2
 |
 +-Name
 |
 +-Gender..

Here is some code for the profile page:

What i was trying to do here is get the current user that's logged
  in and display the name on the profile - on a
 tag that has an id=username.

    //getting reference to the apps
   const auth = firebase.auth();
   const database = firebase.database();
   //also creating table 'users' on database
   const rootRef = database.ref('users');

// ------------------------------------//

   //Check if signed in
    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        // User is signed in.

    database.ref('/users/'+ userId).on('value')
    .then(function(snapshot) {
      var snapVal = snapshot.val();
      displayName.innerHTML = snapVal.Name
      var name = diplayName
      document.getElementById("username").innerHTML = "Welcome: " + name + "!";
    })
  } else {
    // No user is signed in.
    window.location = "login.html"
  }
});

When I tested the code I got this error on the console:

Error: Query.on failed: Was called with 1 argument. Expects at least 2.

Also, I don't really know if I am using this function correctly.

 Should I replace 'userId' with something else?

database.ref('/users/'+ userId).on('value')

Thank you for reading this and have a nice day!

Body:
You're not setting userId to anything yet. When your onAuthStateChanged callback is called, and user has a value, you know that a user is signed in. At that point you can get that user's UID by doing user.uid.

So something like:

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    database.ref('/users/'+ user.uid).once('value')
    .then(function(snaphot) {
      document.getElementById("username").innerText = "Welcome: " + snapshot.val().Name;
    })
  } else {
    window.location = "login.html"
  }
});

The Name in snapshot.val().Name needs to match whatever property from the user node in the database you want to show


问:
How can I create an object that contains instances of a class in Python?
I want to create an object that contains some instances of a class. That object should be some kind of list-generalization of the instances. E.g. I have the following class:

```<code>class car:
    def __init__(self, prize, color)
        self.prize = prize
        self.color = color
</code>```

Now I want to have an object cars that contains many instances of the class car but that I can work with like an instance of car, i.e. cars.prize should return a list of the prizes for all the instances I collected in that object cars.

答:
I think you can do something like that:

```<code>class Cars:
    def __init__(self, list_of_cars):
        self.cars_list = list_of_cars
        self.prize = [car.prize for car in self.cars_list]
        self.color = [car.color for car in self.cars_list]
</code>```

Let's see how it can be used:

```<code>list_of_cars = [Car(1000, "red"), Car(2000, "blue"), Car(3000, "Green")]
x = Cars(list_of_cars)

print(x.prize)
# [1000, 2000, 3000]

print(x.color)
#["red", "blue", "Green"]
</code>```

Body:
I want to create an object that contains some instances of a class. That object should be some kind of list-generalization of the instances. E.g. I have the following class:

class car:
    def __init__(self, prize, color)
        self.prize = prize
        self.color = color

Now I want to have an object cars that contains many instances of the class car but that I can work with like an instance of car, i.e. cars.prize should return a list of the prizes for all the instances I collected in that object cars.

Body:
I think you can do something like that:

class Cars:
    def __init__(self, list_of_cars):
        self.cars_list = list_of_cars
        self.prize = [car.prize for car in self.cars_list]
        self.color = [car.color for car in self.cars_list]

Let's see how it can be used:

list_of_cars = [Car(1000, "red"), Car(2000, "blue"), Car(3000, "Green")]
x = Cars(list_of_cars)

print(x.prize)
# [1000, 2000, 3000]

print(x.color)
#["red", "blue", "Green"]


问:
REPO Db type which works with SQL Server as well as SQLite
I have an application that supports two databases. MSSQL and SQLite. I am revamping the underlying data access and models and using RepoDb. I would be using the same model for the SQLite and MSSQL. Depending on the connection string I create my connection object (i.e. SQLiteConnection or SqlConnection). I am facing a problem with one of my entities. The problem is with a column type.

```<code>public class PLANT
{
    public string OP_ID {get;set;}
}
</code>```

The OP_ID in the SQL Server maps to a uniqueidentifier, and in SQLite to nvarchar. Where I try to do it, it works fine with SQLiteConnection. The problem I face is when I use SqlConnection

```<code> var plant = connection.Query<PLANT>(e => e.PL_ID == "3FFA25B5-4DF5-4216-846C-2C9F58B7DD90").FirstOrDefault();
</code>```

I get error

“No coercion operator is defined between types 'System.Guid' and 'System.String “

I have tried using the IPropertyHandler<Guid, string> on the OP_ID; it works for SqlConnection but fails for SQLiteConnection.

Is there a way that I can use the same model for both connections?

答:
I strongly recommend that you share the models between multiple databases if the PK is on the same type, otherwise you will be ending up some coerce problem like this due to the fact that one DB does not support that target type (i.e. UNIQUEIDENTIFIER).

In anyway, a PropertyHandler is a not way for this as the input types is different. You can use separate models for your SQLite and SqlServer, otherwise, you can explicitly set the RepoDb.Converter.ConversionType = Automatic so the coerce will automatically be handled.

I am not recommending the CoversionType to Automatic as it is an additional conversion logic on top of data extraction. But that would fix it.

Body:
I have an application that supports two databases. MSSQL and SQLite. I am revamping the underlying data access and models and using RepoDb. I would be using the same model for the SQLite and MSSQL. Depending on the connection string I create my connection object (i.e. SQLiteConnection or SqlConnection). I am facing a problem with one of my entities. The problem is with a column type.

public class PLANT
{
    public string OP_ID {get;set;}
}

The OP_ID in the SQL Server maps to a uniqueidentifier, and in SQLite to nvarchar. Where I try to do it, it works fine with SQLiteConnection. The problem I face is when I use SqlConnection

 var plant = connection.Query<PLANT>(e => e.PL_ID == "3FFA25B5-4DF5-4216-846C-2C9F58B7DD90").FirstOrDefault();

I get error

“No coercion operator is defined between types 'System.Guid' and 'System.String “

I have tried using the IPropertyHandler<Guid, string> on the OP_ID; it works for SqlConnection but fails for SQLiteConnection.

Is there a way that I can use the same model for both connections?


问:
Adding text over an image in HTML CSS
I am trying to add text over top of an image on a 'product card' listing. The top left and top right div classes aren't appearing over top of the image. Here is my code:

.cardcontainer {
    position: relative;
}
.top-left {
    position: absolute;
    top: 8px;
    left: 16px;
    background-color: black;
    color: white;
    padding-left: 5px;
    padding-right: 5px;
}
.top-right {
    position: absolute;
    top: 8px;
    right: 16px;
    background-color: black;
    color: white;
    padding-left: 5px;
    padding-right: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="4u">
    <div class="cardcontainer">
        <img src={{ jinja image source }} alt="">
        <div class="top-left">top left text</div>
        <div class="top-right">top right text</div>
        <div class="textbox">
            <!--some stuff here that appears below the image-->
        </div>
    </div>
</section></code>```

Any ideas? thanks for your help!

答:
here is the code for adding text on top of the image . In this i have added text in different position so that you will get the idea how it will look at different position and you can set according to your need where you want to place :

HTML:

```<code><div class="container">
  <img src="img_snow_wide.jpg" alt="Snow" style="width:100%;">
  <div class="bottom-left">Bottom Left</div>
  <div class="top-left">Top Left</div>
  <div class="top-right">Top Right</div>
  <div class="bottom-right">Bottom Right</div>
  <div class="centered">Centered</div>
</div>
</code>```

CSS:

```<code>[![.container {
  position: relative;
  text-align: center;
  color: white;
}

/* Bottom left text */
.bottom-left {
  position: absolute;
  bottom: 8px;
  left: 16px;
}

/* Top left text */
.top-left {
  position: absolute;
  top: 8px;
  left: 16px;
}

/* Top right text */
.top-right {
  position: absolute;
  top: 8px;
  right: 16px;
}

/* Bottom right text */
.bottom-right {
  position: absolute;
  bottom: 8px;
  right: 16px;
}

/* Centered text */
.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}][1]][1]
</code>```

In this i have different position so that you will get an idea where you want to place your text.

Still if you get any doubt in code just feel free to ask.

Title: Adding text over an image in HTML CSS

Body:
I am trying to add text over top of an image on a 'product card' listing. The top left and top right div classes aren't appearing over top of the image. Here is my code:

.cardcontainer {
    position: relative;
}
.top-left {
    position: absolute;
    top: 8px;
    left: 16px;
    background-color: black;
    color: white;
    padding-left: 5px;
    padding-right: 5px;
}
.top-right {
    position: absolute;
    top: 8px;
    right: 16px;
    background-color: black;
    color: white;
    padding-left: 5px;
    padding-right: 5px;
}

top left text

top right text

Any ideas? thanks for your help!

Body:
here is the code for adding text on top of the image . In this i have added text in different position so that you will get the idea how it will look at different position and you can set according to your need where you want to place :

HTML:

<div class="container">
  <img src="img_snow_wide.jpg" alt="Snow" style="width:100%;">
  <div class="bottom-left">Bottom Left</div>
  <div class="top-left">Top Left</div>
  <div class="top-right">Top Right</div>
  <div class="bottom-right">Bottom Right</div>
  <div class="centered">Centered</div>
</div>

CSS:

[![.container {
  position: relative;
  text-align: center;
  color: white;
}

/* Bottom left text */
.bottom-left {
  position: absolute;
  bottom: 8px;
  left: 16px;
}

/* Top left text */
.top-left {
  position: absolute;
  top: 8px;
  left: 16px;
}

/* Top right text */
.top-right {
  position: absolute;
  top: 8px;
  right: 16px;
}

/* Bottom right text */
.bottom-right {
  position: absolute;
  bottom: 8px;
  right: 16px;
}

/* Centered text */
.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}][1]][1]

In this i have different position so that you will get an idea where you want to place your text.

Still if you get any doubt in code just feel free to ask.


问:
How can I protect my application's register API from spammers without using CAPTCHA?
My app has a register service that users can register themselves. However, someone with malicious intent can write a script to register thousands of accounts in seconds.

My back-end developer suggests we use captchas in our mobile apps. However I don't see any apps that are using captchas and they are bad UX.

My question is how to prevent this kind of attacks and secure our services in our app?

答: At my current job, we're working on a passive mobile captcha SDK called HumanDetect. It is transparent to your end users. It grabs sensor data to decide if the phone is being held by a human or not.</p>


问:
Javascript onclick form validation
Can someone tell me what I am doing wrong over here.. Its printing out alert when I put character like abc but when I have valid number its not saving...</p>

```<code>function ValidateNumeric() {
    var val = document.getElementById("tbNumber").value;
    var validChars = '0123456789.';

    for(var i = 0; i < val.length; i++) {
      if(validChars.indexOf(val.charAt(i)) == -1)
       alert('Please enter valid number');
       return false;
        }

        return true;
    }

<INPUT TYPE=SUBMIT NAME="action" VALUE="Save Changes" onclick="return ValidateNumeric();" >
</code>```

答:
Pay attention to the statement start and end - the "return false;" will terminate the "for" loop on the first iteration.

Correct code:

```<code>function ValidateNumeric() {
  var val = document.getElementById("tbNumber").value;
  var validChars = '0123456789.';

  for(var i = 0; i < val.length; i++) {
    if(validChars.indexOf(val.charAt(i)) == -1) {
      alert('Please enter valid number');
      return false;
    }
  }

  return true;
}
</code>```

Title: Javascript onclick form validation

Body:
Can someone tell me what I am doing wrong over here.. Its printing out alert when I put character like abc but when I have valid number its not saving...

function ValidateNumeric() {
    var val = document.getElementById("tbNumber").value;
    var validChars = '0123456789.';

    for(var i = 0; i < val.length; i++) {
      if(validChars.indexOf(val.charAt(i)) == -1)
       alert('Please enter valid number');
       return false;
        }

        return true;
    }

<INPUT TYPE=SUBMIT NAME="action" VALUE="Save Changes" onclick="return ValidateNumeric();" >

Body:
Pay attention to the statement start and end - the "return false;" will terminate the "for" loop on the first iteration.

Correct code:

function ValidateNumeric() {
  var val = document.getElementById("tbNumber").value;
  var validChars = '0123456789.';

  for(var i = 0; i < val.length; i++) {
    if(validChars.indexOf(val.charAt(i)) == -1) {
      alert('Please enter valid number');
      return false;
    }
  }

  return true;
}


问:
Recursion in python, without overwriting changed variable
I am trying to write a function that does the following:

If player_hand doesn't have any number that is less than or equal to mana_bank the function should do nothing.

If player_hand has a number that is less than or equal to mana_bank then the function should prompt the user with which number he chooses.

If the number the user chooses is less than mana_bank it should return a list with that number. If the number is more than mana_bank it should call the function again untill he prompts a number that is less than or equal to mana_bank.

Whenever I run the function and the user first prompts a number that is higher than mana_bank the function gets called from within itself, and then even if the user prompts a number lower than or equal to mana_bank, the function returns None instead of the number in a list.

I also tried making the variable player_choice global but it still didn't work.

Would appreciate any guidance.

```<code>def pick_card():
    player_choice_str = 0
    player_choice = []
    for i in player_hand:
        if i <= mana_bank:
            print(player_hand, mana_bank, "Mana available type the name of the card you wish to play ... ")
            player_choice_str = input()
            break
        if not i <= mana_bank:
            return "You don't have enough mana to play a card."
    if int(player_choice_str) > mana_bank:
        print("That card costs " + str(player_choice_str) + " and you only have " + str(mana_bank) + " this round.")
        pick_card()
    if int(player_choice_str) <= mana_bank:
        player_choice.append(player_choice_str)
        return player_choice

player_hand = [4, 8, 8]
mana_bank = 4

print(pick_card())
</code>```

答:
In your for-loop you have both conditions - if i <= mana_bank: and if not i <= mana_bank: and for any given i one of these will be true.

So your loop will stop as soon as it hits a card that is greater than mana_bank and won't check all cards.

What you want to do is:

```<code>for i in player_hand:
    if i <= mana_bank:
        print(player_hand, mana_bank, "Mana available type the name of the card you wish to play ... ")
        player_choice_str = input()
        break
if player_choice_str is 0:             # no card selected at the end of the loop
    return "You don't have enough mana to play a card."
</code>```

Also you will probably want to validate the user input after this line player_choice_str = input() to check they entered a valid card.

Body:
I am trying to write a function that does the following:

If player_hand doesn't have any number that is less than or equal to mana_bank the function should do nothing.

If player_hand has a number that is less than or equal to mana_bank then the function should prompt the user with which number he chooses.

If the number the user chooses is less than mana_bank it should return a list with that number. If the number is more than mana_bank it should call the function again untill he prompts a number that is less than or equal to mana_bank.

Whenever I run the function and the user first prompts a number that is higher than mana_bank the function gets called from within itself, and then even if the user prompts a number lower than or equal to mana_bank, the function returns None instead of the number in a list.

I also tried making the variable player_choice global but it still didn't work.

Would appreciate any guidance.

def pick_card():
    player_choice_str = 0
    player_choice = []
    for i in player_hand:
        if i <= mana_bank:
            print(player_hand, mana_bank, "Mana available type the name of the card you wish to play ... ")
            player_choice_str = input()
            break
        if not i <= mana_bank:
            return "You don't have enough mana to play a card."
    if int(player_choice_str) > mana_bank:
        print("That card costs " + str(player_choice_str) + " and you only have " + str(mana_bank) + " this round.")
        pick_card()
    if int(player_choice_str) <= mana_bank:
        player_choice.append(player_choice_str)
        return player_choice

player_hand = [4, 8, 8]
mana_bank = 4

print(pick_card())

Body:
In your for-loop you have both conditions - if i <= mana_bank: and if not i <= mana_bank: and for any given i one of these will be true.

So your loop will stop as soon as it hits a card that is greater than mana_bank and won't check all cards.

What you want to do is:

for i in player_hand:
    if i <= mana_bank:
        print(player_hand, mana_bank, "Mana available type the name of the card you wish to play ... ")
        player_choice_str = input()
        break
if player_choice_str is 0:             # no card selected at the end of the loop
    return "You don't have enough mana to play a card."

Also you will probably want to validate the user input after this line player_choice_str = input() to check they entered a valid card.


问:
Perform operation in NumPy array except for some values
Is there a simple way to lock/freeze an element within a Numpy Array. I would like to do several operations over a Numpy Array in python while keeping some specific values as they are originally.

for example,

if a have a Numpy Array a ;

```<code>[[ 1  3  4  5],
  [6  7  8  0],
  [9 10  11 2]]
</code>```

and another Numpy Array b ;

```<code>[[2  0  4  10],
 [11 5  12  3],
 [6  8  7   9]]
</code>```

and c = a+b but keeping the original values of 3, 8 and 2 in a.

My arrays are quite big and I would like a solution where I don't have to use a for loop, an if statement or something similar.

答:
You can use np.isin to build a mask, and then np.where to populate from either a or a+b depending on on the result:

```<code>m = np.isin(a, [3,8,2])
c = np.where(m, a, a+b)
</code>```

Or as @hpaulj suggests, you could also use where and out in np.add, which would modify a in-place:

```<code>np.add(a, b, where=~np.isin(a,[3,8,2]), out=a)

array([[ 3,  3,  8, 15],
       [17, 12,  8,  3],
       [15, 18, 18,  2]])
</code>```

Body:
Is there a simple way to lock/freeze an element within a Numpy Array. I would like to do several operations over a Numpy Array in python while keeping some specific values as they are originally.

for example,

if a have a Numpy Array a ;

[[ 1  3  4  5],
  [6  7  8  0],
  [9 10  11 2]]

and another Numpy Array b ;

[[2  0  4  10],
 [11 5  12  3],
 [6  8  7   9]]

and c = a+b but keeping the original values of 3, 8 and 2 in a.

My arrays are quite big and I would like a solution where I don't have to use a for loop, an if statement or something similar.

Body:
You can use np.isin to build a mask, and then np.where to populate from either a or a+b depending on on the result:

m = np.isin(a, [3,8,2])
c = np.where(m, a, a+b)

Or as @hpaulj suggests, you could also use where and out in np.add, which would modify a in-place:

np.add(a, b, where=~np.isin(a,[3,8,2]), out=a)

array([[ 3,  3,  8, 15],
       [17, 12,  8,  3],
       [15, 18, 18,  2]])


问:
How to rerun animation in SCSS?
I would like to create a simple bubble animation. There are two different animations in my code. When my code runs scale animation is working then movebubbles animation continues to work infinitely. When pics reappear on bottom I want to trigger scale animation again an again. Btw, JS is not allowed.

```<code>//set random size and positions for bubbles

@for $i from 1 through 10 {
  $random-size: random(138) + 77;
  $random-position: random(600);
  $random-animation: random(14) + 14;

  .bubble:nth-child(#{$i}) {
    width: $random-size + px;
    height: $random-size + px;
    left: $random-position + px;
    animation: movebubbles #{$random-animation}s linear infinite 0.9s,
      scale 1s alternate ease-out running;

    background: url("https://picsum.photos/id/1/200/300")
      rgba(0, 0, 0, 0)
      no-repeat
      center
      center;
  }
}

.main-container {
  height: 100%;
  width: 100%;
  display: flex;

  .bubbles-container {
    border: 1px solid red;
    display: flex;
    position: relative;
    width: 680px;
    height: 600px;
    overflow: hidden;
    align-items: flex-end;
  }

  .bubble {
    margin-bottom: 0;

    bottom: 0;
    position: absolute;
    background-size: cover;
    background-color: transparent;
  }
}

@keyframes scale {
  from {
    transform: scale(0.1);
  }
  to {
    transform: scale(1);
  }
}

@keyframes movebubbles {
  from {
    margin-bottom: 0%;
    opacity: 1;
  }
  to {
    margin-bottom: 100%;
    opacity: 0.1;
  }
}
</code>```

My fiddle: https://jsfiddle.net/y3aujceg/12/

答:
How about just splitting animation into percentages and between 1-5% the scale would happen and for the rest, it'll move. To find your best way, change the percentage up to when it has to grow.

```<code>@keyframes goBubblesGo {
  0% {
    transform: scale(0.1);
    margin-bottom: 0%;
    opacity: 1;
  }
  5% {
    transform: scale(1);
  }
  100% {
    margin-bottom: 100%;
    opacity: 0.1;
  }
}
</code>```

Check your updated fiddle

Title: How to rerun animation in SCSS?

Body:
I would like to create a simple bubble animation. There are two different animations in my code. When my code runs scale animation is working then movebubbles animation continues to work infinitely. When pics reappear on bottom I want to trigger scale animation again an again. Btw, JS is not allowed.

//set random size and positions for bubbles

@for $i from 1 through 10 {
  $random-size: random(138) + 77;
  $random-position: random(600);
  $random-animation: random(14) + 14;

  .bubble:nth-child(#{$i}) {
    width: $random-size + px;
    height: $random-size + px;
    left: $random-position + px;
    animation: movebubbles #{$random-animation}s linear infinite 0.9s,
      scale 1s alternate ease-out running;

    background: url("https://picsum.photos/id/1/200/300")
      rgba(0, 0, 0, 0)
      no-repeat
      center
      center;
  }
}

.main-container {
  height: 100%;
  width: 100%;
  display: flex;

  .bubbles-container {
    border: 1px solid red;
    display: flex;
    position: relative;
    width: 680px;
    height: 600px;
    overflow: hidden;
    align-items: flex-end;
  }

  .bubble {
    margin-bottom: 0;

    bottom: 0;
    position: absolute;
    background-size: cover;
    background-color: transparent;
  }
}

@keyframes scale {
  from {
    transform: scale(0.1);
  }
  to {
    transform: scale(1);
  }
}

@keyframes movebubbles {
  from {
    margin-bottom: 0%;
    opacity: 1;
  }
  to {
    margin-bottom: 100%;
    opacity: 0.1;
  }
}

My fiddle: https://jsfiddle.net/y3aujceg/12/

Body:
How about just splitting animation into percentages and between 1-5% the scale would happen and for the rest, it'll move. To find your best way, change the percentage up to when it has to grow.

@keyframes goBubblesGo {
  0% {
    transform: scale(0.1);
    margin-bottom: 0%;
    opacity: 1;
  }
  5% {
    transform: scale(1);
  }
  100% {
    margin-bottom: 100%;
    opacity: 0.1;
  }
}

Check your updated fiddle


问:
Unable to find Windows.Devices.Enumeration and Windows.Storage.Streams
I need to use Windows.Storage.Streams and Windows.Devices.Enumeration in my Winforms application on Windows 7 to access and manipulate Barcode reader, but unable to find it to Add Reference. Not sure if can download it somewhere. I was able to find and download Microsoft.PointOfService and added reference to my project, but not the first two libraries.

Please advise.

答:
How to access the Windows 10 APIs from WPF

You can access the Windows 10 APIs from a pre-existing WPF project. To do so, go to your Solution Explorer window and …

Right click on References.

Select “Add Reference…” from the context menu.

On the left of the Reference Manager, choose Browse and find the following file: C:/Program Files (x86)/Windows Kits/10/UnionMetadata/Windows.winmd.

Add it to your project as a reference. Note: You will need to change the filter to “All Files”.

Right click on References. Select “Add Reference…” from the context menu. On the left of the Reference Manager, go to Browse and find the directory “C:/Program Files (x86)/Reference Assemblies/Microsoft/Framework/.NETCore/v4.5”. Add System.Runtime.WindowsRuntime.dll to your project.

Learn More Calling Windows 10 APIs From a Desktop Application


问:
Cloud Firestore + VueJs Auto Generated Numerical Invoice Number
I'm trying to build an invoice system for a client of mine using Vue.js and Cloud Firestore.

Once a new invoice is created, my client wants an auto generated invoice number added to every new invoice starting from 0001, 0002, 0003 etc... I guess it would be a numerical ID for every new invoice.

How would i go about doing this with Cloud Firestore? I was looking into the new firebase function:

```<code>firebase.firestore.FieldValue.increment()
</code>```

but its not exactly what i was looking for. Or maybe i'm not using it correctly?

I've been going crazy trying to find a solution or even an idea that would steer me in the right direction.

Thank You!

答:
I was able to solve this another way. I created a document (--invoices--) and in that document i created a field called count and im using the increment function to add to that count when a new document is created.

```<code>firebase.firestore.FieldValue.increment()
</code>```

So, when that count gets updated i grab the last number and update the invoice number field on the new document that was created.

Body:
I'm trying to build an invoice system for a client of mine using Vue.js and Cloud Firestore.

Once a new invoice is created, my client wants an auto generated invoice number added to every new invoice starting from 0001, 0002, 0003 etc... I guess it would be a numerical ID for every new invoice.

How would i go about doing this with Cloud Firestore? I was looking into the new firebase function:

firebase.firestore.FieldValue.increment()

but its not exactly what i was looking for. Or maybe i'm not using it correctly?

I've been going crazy trying to find a solution or even an idea that would steer me in the right direction.

Thank You!

Body:
I was able to solve this another way. I created a document (--invoices--) and in that document i created a field called count and im using the increment function to add to that count when a new document is created.

firebase.firestore.FieldValue.increment()

So, when that count gets updated i grab the last number and update the invoice number field on the new document that was created.