问:
Create a custom animatable property
On UIView you can change the backgroundColour animated. And on a UISlideView you can change the value animated.

Can you add a custom property to your own UIView subclass so that it can be animated?

If I have a CGPath within my UIView then I can animate the drawing of it by changing the percentage drawn of the path.

Can I encapsulate that animation into the subclass.

i.e. I have a UIView with a CGPath that creates a circle.

If the circle is not there it represents 0%. If the circle is full it represents 100%. I can draw any value by changing the percentage drawn of the path. I can also animate the change (within the UIView subclass) by animating the percentage of the CGPath and redrawing the path.

Can I set some property (i.e. percentage) on the UIView so that I can stick the change into a UIView animateWithDuration block and it animate the change of the percentage of the path?

I hope I have explained what I would like to do well.

Essentially, all I want to do is something like...

```<code>[UIView animateWithDuration:1.0
 animations:^{
     myCircleView.percentage = 0.7;
 }
 completion:nil];
</code>```

and the circle path animate to the given percentage.

答:
@David Rees answer get me on the right track, but there is one issue. In my case
completion of animation always returns false, right after animation has began.

```<code>UIView.animate(withDuration: 2, delay: 0, options: .curveEaseInOut, animations: {
    circularProgress.progress = 0.76
}, completion: { finished in
   // finished - always false
})
</code>```

This is the way it've worked for me - action of animation is handled inside of CALayer.

I have also included small example how to make layer with additional properties like "color".
In this case, without initializer that copies the values, changing the color would take affect only on non-animating view. During animation it would be visble with "default setting".

```<code>public class CircularProgressView: UIView {

    @objc public dynamic var progress: CGFloat {
        get {
            return progressLayer.progress
        }
        set {
            progressLayer.progress = newValue
        }
    }

    fileprivate var progressLayer: CircularProgressLayer {
        return layer as! CircularProgressLayer
    }

    override public class var layerClass: AnyClass {
        return CircularProgressLayer.self
    }
}

/*
* Concepts taken from:
* https://stackoverflow.com/a/37470079
*/
fileprivate class CircularProgressLayer: CALayer {
    @NSManaged var progress: CGFloat
    let startAngle: CGFloat = 1.5 * .pi
    let twoPi: CGFloat = 2 * .pi
    let halfPi: CGFloat = .pi / 2

    var color: UIColor = .red
    // preserve layer properties
    // without this specyfic init, if color was changed to sth else
    // animation would still use .red
    override init(layer: Any) {
        super.init(layer: layer)
        if let layer = layer as? CircularProgressLayer {
            self.color = layer.color
            self.progress = layer.progress
        }
    }

    override init() {
        super.init()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override class func needsDisplay(forKey key: String) -> Bool {
        if key == #keyPath(progress) {
            return true
        }
        return super.needsDisplay(forKey: key)
    }

    override func action(forKey event: String) -> CAAction? {
        if event == #keyPath(CircularProgressLayer.progress) {
            guard let animation = action(forKey: #keyPath(backgroundColor)) as? CABasicAnimation else {
                setNeedsDisplay()
                return nil
            }

            if let presentation = presentation() {
                animation.keyPath = event
                animation.fromValue = presentation.value(forKeyPath: event)
                animation.toValue = nil
            } else {
                return nil
            }

            return animation
        }

        return super.action(forKey: event)
    }

    override func draw(in ctx: CGContext) {
        super.draw(in: ctx)

        UIGraphicsPushContext(ctx)

        //Light Gray
        UIColor.lightGray.setStroke()

        let center = CGPoint(x: bounds.midX, y: bounds.midY)
        let strokeWidth: CGFloat = 4
        let radius = (bounds.size.width / 2) - strokeWidth
        let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0, endAngle: twoPi, clockwise: true)
        path.lineWidth = strokeWidth
        path.stroke()

        // Red - default
        self.color.setStroke()

        let endAngle = (twoPi * progress) - halfPi
        let pathProgress = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle , clockwise: true)
        pathProgress.lineWidth = strokeWidth
        pathProgress.lineCapStyle = .round
        pathProgress.stroke()

        UIGraphicsPopContext()
    }
}
</code>```

The way to handle animations differently and copy layer properties I have found in this article:
https://medium.com/better-programming/make-apis-like-apple-animatable-view-properties-in-swift-4349b2244cea

Title: Create a custom animatable property

Body:
On UIView you can change the backgroundColour animated. And on a UISlideView you can change the value animated.

Can you add a custom property to your own UIView subclass so that it can be animated?

If I have a CGPath within my UIView then I can animate the drawing of it by changing the percentage drawn of the path.

Can I encapsulate that animation into the subclass.

i.e. I have a UIView with a CGPath that creates a circle.

If the circle is not there it represents 0%. If the circle is full it represents 100%. I can draw any value by changing the percentage drawn of the path. I can also animate the change (within the UIView subclass) by animating the percentage of the CGPath and redrawing the path.

Can I set some property (i.e. percentage) on the UIView so that I can stick the change into a UIView animateWithDuration block and it animate the change of the percentage of the path?

I hope I have explained what I would like to do well.

Essentially, all I want to do is something like...

[UIView animateWithDuration:1.0
 animations:^{
     myCircleView.percentage = 0.7;
 }
 completion:nil];

and the circle path animate to the given percentage.

Body:
@David Rees answer get me on the right track, but there is one issue. In my case
completion of animation always returns false, right after animation has began.

UIView.animate(withDuration: 2, delay: 0, options: .curveEaseInOut, animations: {
    circularProgress.progress = 0.76
}, completion: { finished in
   // finished - always false
})

This is the way it've worked for me - action of animation is handled inside of CALayer.

I have also included small example how to make layer with additional properties like "color".
In this case, without initializer that copies the values, changing the color would take affect only on non-animating view. During animation it would be visble with "default setting".

public class CircularProgressView: UIView {

    @objc public dynamic var progress: CGFloat {
        get {
            return progressLayer.progress
        }
        set {
            progressLayer.progress = newValue
        }
    }

    fileprivate var progressLayer: CircularProgressLayer {
        return layer as! CircularProgressLayer
    }

    override public class var layerClass: AnyClass {
        return CircularProgressLayer.self
    }
}

/*
* Concepts taken from:
* https://stackoverflow.com/a/37470079
*/
fileprivate class CircularProgressLayer: CALayer {
    @NSManaged var progress: CGFloat
    let startAngle: CGFloat = 1.5 * .pi
    let twoPi: CGFloat = 2 * .pi
    let halfPi: CGFloat = .pi / 2

    var color: UIColor = .red
    // preserve layer properties
    // without this specyfic init, if color was changed to sth else
    // animation would still use .red
    override init(layer: Any) {
        super.init(layer: layer)
        if let layer = layer as? CircularProgressLayer {
            self.color = layer.color
            self.progress = layer.progress
        }
    }

    override init() {
        super.init()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override class func needsDisplay(forKey key: String) -> Bool {
        if key == #keyPath(progress) {
            return true
        }
        return super.needsDisplay(forKey: key)
    }

    override func action(forKey event: String) -> CAAction? {
        if event == #keyPath(CircularProgressLayer.progress) {
            guard let animation = action(forKey: #keyPath(backgroundColor)) as? CABasicAnimation else {
                setNeedsDisplay()
                return nil
            }

            if let presentation = presentation() {
                animation.keyPath = event
                animation.fromValue = presentation.value(forKeyPath: event)
                animation.toValue = nil
            } else {
                return nil
            }

            return animation
        }

        return super.action(forKey: event)
    }

    override func draw(in ctx: CGContext) {
        super.draw(in: ctx)

        UIGraphicsPushContext(ctx)

        //Light Gray
        UIColor.lightGray.setStroke()

        let center = CGPoint(x: bounds.midX, y: bounds.midY)
        let strokeWidth: CGFloat = 4
        let radius = (bounds.size.width / 2) - strokeWidth
        let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0, endAngle: twoPi, clockwise: true)
        path.lineWidth = strokeWidth
        path.stroke()

        // Red - default
        self.color.setStroke()

        let endAngle = (twoPi * progress) - halfPi
        let pathProgress = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle , clockwise: true)
        pathProgress.lineWidth = strokeWidth
        pathProgress.lineCapStyle = .round
        pathProgress.stroke()

        UIGraphicsPopContext()
    }
}

The way to handle animations differently and copy layer properties I have found in this article:
https://medium.com/better-programming/make-apis-like-apple-animatable-view-properties-in-swift-4349b2244cea


来源: stackexchange

问:
How to generate game pins
I am developing a game that requires a game PIN to join, similar to Kahoot in that regard I suppose. E.g. KA1PN2XR. I was thinking of making it 8 characters and alphanumeric, so I'm not worried about running out of combinations as there are 36^8 or about 2.8 trillion (capital letters) of them, and games will be removed once everyone has left.

However, I am wondering what is an efficient way to generate these pins? Should I use a while loop that generates one until it finds one that isn't in the database? Seems inefficient but I can't think of a much better method.

Thanks.

答:
Rather than a loop that generates one and checks to see if it's in the database, it would probably be more efficient -- and safer -- to include a unique index in the database and catch the exception in the unlikely event of a collision.

For example:

SQL table:

```<code>create table game_pins (
    pin varchar(8) primary key,
    ...
)
</code>```

Python:

```<code>import random, string

for retry in range(10):   # 10 Retries
    pin = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8))
    try:
        (code to insert in database)
        return pin
    except (database exception for duplicate key):
        pass
    raise Exception('Too many retries generating PIN')
</code>```

The reason this is better than a loop that checks first, then inserts, is that you're relying on the database to keep the PINs unique.

ContentLicense: CC BY-SA 4.0

Title: How to generate game pins

Body:
Rather than a loop that generates one and checks to see if it's in the database, it would probably be more efficient -- and safer -- to include a unique index in the database and catch the exception in the unlikely event of a collision.

For example:

SQL table:

create table game_pins (
    pin varchar(8) primary key,
    ...
)

Python:

import random, string

for retry in range(10):   # 10 Retries
    pin = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8))
    try:
        (code to insert in database)
        return pin
    except (database exception for duplicate key):
        pass
    raise Exception('Too many retries generating PIN')

The reason this is better than a loop that checks first, then inserts, is that you're relying on the database to keep the PINs unique.


问:
Share post on LinkedIn with React Native
I have an app built in react-native in which I need to share a post on LinkedIn with predefined content.

I used 'react-native-share' for sharing content on LinkedIn but It's not working. How can I achieve this?

Thanks in advance.

答:
LinkedIn supports only one parameter being passed to it, and that is the url parameter.  It will look like this...

```<code>https://www.linkedin.com/sharing/share-offsite/?url={url}
</code>```

Source: Official LinkedIn Sharing Documentation.

The following parameters will not work: summary, title, source, etc..  Anything besides url.

To share to LinkedIn, just make a  element that points to an above formatted-URL, and make absolutely sure to do URL-encoding on your {url}.

You probably want to share title and summary, though, based on the accepted answer.  You cannot do that using GET-data, BUT you can do that using og: tags.

<meta property='og:title' content='Title of the article"/>

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

<meta property='og:description' content='Description that will show in the preview"/>

<meta property='og:url' content='//www.example.com/URL of the article" />

Source: LinkedIn Developer Docs: Making Your Website Shareable on LinkedIn.

In case you are uncertain that you've followed the LinkedIn documentation correctly to make a share URL, you can test your page's URL to see how it will look when shared here: href="https://www.linkedin.com/post-inspector/" rel="nofollow noreferrer">LinkedIn Post Inspector.

Body:
LinkedIn supports only one parameter being passed to it, and that is the url parameter.  It will look like this...

https://www.linkedin.com/sharing/share-offsite/?url={url}

Source: Official LinkedIn Sharing Documentation.

The following parameters will not work: summary, title, source, etc..  Anything besides url.

To share to LinkedIn, just make a <a href> element that points to an above formatted-URL, and make absolutely sure to do URL-encoding on your {url}.

You probably want to share title and summary, though, based on the accepted answer.  You cannot do that using GET-data, BUT you can do that using og: tags.

<meta property='og:title' content='Title of the article"/>

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

<meta property='og:description' content='Description that will show in the preview"/>

<meta property='og:url' content='//www.example.com/URL of the article" />

Source: LinkedIn Developer Docs: Making Your Website Shareable on LinkedIn.

In case you are uncertain that you've followed the LinkedIn documentation correctly to make a share URL, you can test your page's URL to see how it will look when shared here: LinkedIn Post Inspector.


问:
Is there a program that allows you to write "pretty" library tutorials?
I need to write tutorial for a library I wrote. The tutorial should also include code.
I wonder if there is a platform/application that provides a nice option for writing such tutorials with code?</p>

答: This pretty much depends on where and what format do you plan to publish your tutorial. For online publication (i.e. on a website, as HTML/CSS) you can use a syntax highlighter.</p>

ContentLicense: CC BY-SA 3.0


问:
Django - VueJS - Can't be null
i work on a project with Django and VueJs. I have a problem with a field can't be null but i don't understand why.

models.py

```<code>from django.db import models
from django.conf import settings

class Tache(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    echeance = models.DateTimeField(null=True, blank=True)
    titre = models.CharField(max_length=240)
    sous_titre = models.CharField(max_length=240, null=True, blank=True)
    content = models.CharField(max_length=240)
    fait = models.BooleanField(default=False)
    slug = models.SlugField(max_length=255, unique=True)
    author = models.ForeignKey(settings.AUTH_USER_MODEL,
                                on_delete=models.CASCADE,
                                related_name="taches")

    def __str__(self):
        return self.content
</code>```

serializers.py

```<code>from rest_framework import serializers
from taches.models import Tache

class TacheSerializer(serializers.ModelSerializer):
    author = serializers.StringRelatedField(read_only=True)
    created_at = serializers.SerializerMethodField(read_only=True)
    # echeance = serializers.SerializerMethodField()
    echeance = serializers.DateTimeField(format = "%Y-%m-%dT%H:%M:%S")
    slug = serializers.SlugField(read_only=True)

    class Meta:
        model = Tache
        exclude = ["updated_at"]

    def get_created_at(self, instance):
        return instance.created_at.strftime("%d" + "/" + "%m" + "/" + "%Y")

    # def get_echeance(self, instance):
    #     if instance.echeance != None:
    #         return instance.echeance.strftime("%Y-%m-%dT%H:%M:%S")
</code>```

My problem "field can't be null are on "echeance" field.
You can see i have 4 lines in comments because => don't work so i do that :
echeance = serializers.DateTimeField(format = "%Y-%m-%dT%H:%M:%S")
I think my problem come here...

Do you have any idea why "echeance" can't be null...?

Thank's

EDIT : I'have this error when i try to create a new "tache" by the user interface and the api django rest frameword. But i can create a new "tache" by the django admin... When i see the "tache" in the api, "echeance" = null.
I'm lost...

SOLUTION : I have change the model field of "echeance" to DateField. After i change in the serializer : echeance = models.DateField(format = "%d/%m/%Y", allow_null=True, required=False). I have just the date and not the time but it's work.

答:
You have to mention allow_blank and allow_true

Try this

```<code>echeance = serializers.DateTimeField(format="%Y-%m-%dT%H:%M:%S", required=False, read_only=True)
</code>```

Title: Django - VueJS - Can't be null

Body:
i work on a project with Django and VueJs. I have a problem with a field can't be null but i don't understand why.

models.py

from django.db import models
from django.conf import settings

class Tache(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    echeance = models.DateTimeField(null=True, blank=True)
    titre = models.CharField(max_length=240)
    sous_titre = models.CharField(max_length=240, null=True, blank=True)
    content = models.CharField(max_length=240)
    fait = models.BooleanField(default=False)
    slug = models.SlugField(max_length=255, unique=True)
    author = models.ForeignKey(settings.AUTH_USER_MODEL,
                                on_delete=models.CASCADE,
                                related_name="taches")

    def __str__(self):
        return self.content

serializers.py

from rest_framework import serializers
from taches.models import Tache

class TacheSerializer(serializers.ModelSerializer):
    author = serializers.StringRelatedField(read_only=True)
    created_at = serializers.SerializerMethodField(read_only=True)
    # echeance = serializers.SerializerMethodField()
    echeance = serializers.DateTimeField(format = "%Y-%m-%dT%H:%M:%S")
    slug = serializers.SlugField(read_only=True)

    class Meta:
        model = Tache
        exclude = ["updated_at"]

    def get_created_at(self, instance):
        return instance.created_at.strftime("%d" + "/" + "%m" + "/" + "%Y")

    # def get_echeance(self, instance):
    #     if instance.echeance != None:
    #         return instance.echeance.strftime("%Y-%m-%dT%H:%M:%S")

My problem "field can't be null are on "echeance" field.
You can see i have 4 lines in comments because => don't work so i do that :
echeance = serializers.DateTimeField(format = "%Y-%m-%dT%H:%M:%S")
I think my problem come here...

Do you have any idea why "echeance" can't be null...?

Thank's

EDIT : I'have this error when i try to create a new "tache" by the user interface and the api django rest frameword. But i can create a new "tache" by the django admin... When i see the "tache" in the api, "echeance" = null.
I'm lost...

SOLUTION : I have change the model field of "echeance" to DateField. After i change in the serializer : echeance = models.DateField(format = "%d/%m/%Y", allow_null=True, required=False). I have just the date and not the time but it's work.

Body:
You have to mention allow_blank and allow_true

Try this

echeance = serializers.DateTimeField(format="%Y-%m-%dT%H:%M:%S", required=False, read_only=True)


问:
Discord.py see if user is talking in voice
Is there a way to check whether a user in a voice channel is currently speaking or not?</p>

答:
There isn't a way to directly tell from the docs if a user is speaking, unless you're planning on working with the bytes from the socket, but that's not the easiest thing to do.

If you have a push-to-talk voice channel set up in your guild, you could do something like this using the user's mute states:

@bot.event
async def on_voice_state_update(member, prev, cur):
    if cur.self_mute and not prev.self_mute:
        print(f"{member} stopped talking!")
    elif prev.self_mute and not cur.self_mute:
        print(f"{member} started talking!")
```

References:

on_voice_state_update()

discord.VoiceState

Body:
There isn't a way to directly tell from the docs if a user is speaking, unless you're planning on working with the bytes from the socket, but that's not the easiest thing to do.

If you have a push-to-talk voice channel set up in your guild, you could do something like this using the user's mute states:

@bot.event
async def on_voice_state_update(member, prev, cur):
    if cur.self_mute and not prev.self_mute:
        print(f"{member} stopped talking!")
    elif prev.self_mute and not cur.self_mute:
        print(f"{member} started talking!")

References:

on_voice_state_update()

discord.VoiceState


问:
vue getter return undefined
Can someone tell me why this getter is returning me "Cannot read property 'testVar' of undefined"?</p>

```<code>productPrice: (state) => (id) => {
    const testVar = true
    if (this.testVar) {
        const priceObj = state.precioProducto.find(product => producto.idProducto === parseInt(id))
    } else {
        const priceObj = []
    }
    return (precioObj && state.productoPrecioReady) ? priceObj : null
},
</code>```

答:
You are using this.testVar, but testVar is declared as a constant in the getter block, so you must just declare your if condition as:

```<code>productPrice: (state) => (id) => {
  const testVar = true
  if (testVar) {
    const priceObj = state.precioProducto.find(product => producto.idProducto === parseInt(id))
  } else {
    const priceObj = []
  }
  return (precioObj && state.productoPrecioReady) ? priceObj : null
}
</code>```

Title: vue getter return undefined

Body:
Can someone tell me why this getter is returning me "Cannot read property 'testVar' of undefined"?

productPrice: (state) => (id) => {
    const testVar = true
    if (this.testVar) {
        const priceObj = state.precioProducto.find(product => producto.idProducto === parseInt(id))
    } else {
        const priceObj = []
    }
    return (precioObj && state.productoPrecioReady) ? priceObj : null
},

Body:
You are using this.testVar, but testVar is declared as a constant in the getter block, so you must just declare your if condition as:

productPrice: (state) => (id) => {
  const testVar = true
  if (testVar) {
    const priceObj = state.precioProducto.find(product => producto.idProducto === parseInt(id))
  } else {
    const priceObj = []
  }
  return (precioObj && state.productoPrecioReady) ? priceObj : null
}


问:
Cant translate a string using Application context
My application uses a Foreground service to make sure the process is still running when app is removed from Recent list. So if the user kills the app by removing from that list, the application is still running in the background. In such state, some times, I need to show a background notification using the NotificationManager. The strings I use when showing the notification is obtained from strings.xml, according to the current selected device locale.
Currently, I use Application context to obtain the string from the strings.xml file and I pass it to the notification manager.
The issue is, when using Application context to call getString, I only get the "default" english translation. Only when I use an Activity context, then I get access to the application resources and the correct translation is obtained.
The problem is when a user kills the app, there is no Activity context to use. Only the Application context is available.

Is there a way to solve this? Thanks!

EDIT 1:
I show the notification in this manner:

```<code>public void showNotification(){

   Context context = Application.getContextFromApplicationClass();
   Intent intent = MainActivity.getLaunchIntent(context);
        intent.putExtra(EVENT_NAME, eventName);
        notificationManager.notify(TRIP_EVENT_NOTIFICATION_ID, obtainNotification(getString(R.string
                .notification_event_title, eventName), getString(R.string.notification_event_message), false, false, getLaunchActivityPendingIntent(intent, TRIP_EVENT_NOTIFICATION_ID)));
        setCancellationAfterTime(TRIP_EVENT_NOTIFICATION_ID, 5000);
}
</code>```

and this is the private getString() method I use:

```<code>private String getString(int resId){

        // First, attempt to use an Activity context to obtain possible language translations...
        Context activityContext = ((Application) Application.getContextFromApplicationClass()).getActivityContext();
        if (activityContext != null){
            return activityContext.getString(resId);
        }

        // If there is no activity, use the Application context that is running in the bg.
        return Application.getContextFromApplicationClass().getString(resId);

    }
</code>```

So as you can see, the method showNotification(), when creating the Notification object, calls getString (which is a private method in the class). In it I obtain the Application context and from that I can get an Activity context if available.
If onDestroy was called on the activity at some point (such as when I remove the app from Recent list), I will no longer have access to that activity context and I will use the Application context instead.
but in such case, I cannot obtain the application resources and there is no translation.

Basically I'm looking for a solution on how to get translated strings for Notifications, when there is no Activity context present...

答:
Can you cast your application context to your activity?</p>

```<code>Context actvitiyContext = this.getApplicationContext();
Activity activity = (Activity) actvitiyContext;
</code>```

Body:
My application uses a Foreground service to make sure the process is still running when app is removed from Recent list. So if the user kills the app by removing from that list, the application is still running in the background. In such state, some times, I need to show a background notification using the NotificationManager. The strings I use when showing the notification is obtained from strings.xml, according to the current selected device locale.
Currently, I use Application context to obtain the string from the strings.xml file and I pass it to the notification manager.
The issue is, when using Application context to call getString, I only get the "default" english translation. Only when I use an Activity context, then I get access to the application resources and the correct translation is obtained.
The problem is when a user kills the app, there is no Activity context to use. Only the Application context is available.

Is there a way to solve this? Thanks!

EDIT 1:
I show the notification in this manner:

public void showNotification(){

   Context context = Application.getContextFromApplicationClass();
   Intent intent = MainActivity.getLaunchIntent(context);
        intent.putExtra(EVENT_NAME, eventName);
        notificationManager.notify(TRIP_EVENT_NOTIFICATION_ID, obtainNotification(getString(R.string
                .notification_event_title, eventName), getString(R.string.notification_event_message), false, false, getLaunchActivityPendingIntent(intent, TRIP_EVENT_NOTIFICATION_ID)));
        setCancellationAfterTime(TRIP_EVENT_NOTIFICATION_ID, 5000);
}

and this is the private getString() method I use:

private String getString(int resId){

        // First, attempt to use an Activity context to obtain possible language translations...
        Context activityContext = ((Application) Application.getContextFromApplicationClass()).getActivityContext();
        if (activityContext != null){
            return activityContext.getString(resId);
        }

        // If there is no activity, use the Application context that is running in the bg.
        return Application.getContextFromApplicationClass().getString(resId);

    }

So as you can see, the method showNotification(), when creating the Notification object, calls getString (which is a private method in the class). In it I obtain the Application context and from that I can get an Activity context if available.
If onDestroy was called on the activity at some point (such as when I remove the app from Recent list), I will no longer have access to that activity context and I will use the Application context instead.
but in such case, I cannot obtain the application resources and there is no translation.

Basically I'm looking for a solution on how to get translated strings for Notifications, when there is no Activity context present...

Body:
Can you cast your application context to your activity?

Context actvitiyContext = this.getApplicationContext();
Activity activity = (Activity) actvitiyContext;


问:
Unhandled exception occurs when Clicking Save Button

private void btnSave_Click(object sender, EventArgs e)
{
    if (!ValidInput())
        return;
    using (var conn = new OleDbConnection(DatabaseObjects.ConnectionString))
    {
        conn.Open();
        command = new OleDbCommand("insert into Students (RollNo, SName, FName, DOB, Class, Section) values (@RollNo, @SName, @FName, @DOB, @Class, @Section)", conn);
        command.Parameters.Add(new OleDbParameter("RollNo", txtRollNo.Text));
        command.Parameters.Add(new OleDbParameter("SName", txtSName.Text));
        command.Parameters.Add(new OleDbParameter("FName", txtFName.Text));
        command.Parameters.Add(new OleDbParameter("DOB", dtpDOB.Text));
        command.Parameters.Add(new OleDbParameter("Class", cmbClass.Text));
        command.Parameters.Add(new OleDbParameter("Section", cmbSection.Text));
        command.ExecuteNonQuery();
        MessageBox.Show("Saved");
    }
}
```

When I Click Save Button this error is rising (Insert Into Syntax Error).

I have troubleshooted the code, I Find that if Field Section and Parameter @Section is removed from insert statement. Then Code works fine. But I want to Get ComboBox(CmbSection) Value of it and also to store on Database. How Can I?

答:
"Section" is a reserved word in MS Access, so its use here is confusing the query parser.

You can explicitly tell the query what identifiers are referring to database objects (columns, tables, etc.) by wrapping them in square brackets:

```<code>INSERT INTO [Students]
    ([RollNo], [SName], [FName], [DOB], [Class], [Section])
    VALUES (@RollNo, @SName, @FName, @DOB, @Class, @Section)
</code>```

Body:
private void btnSave_Click(object sender, EventArgs e)
{
    if (!ValidInput())
        return;
    using (var conn = new OleDbConnection(DatabaseObjects.ConnectionString))
    {
        conn.Open();
        command = new OleDbCommand("insert into Students (RollNo, SName, FName, DOB, Class, Section) values (@RollNo, @SName, @FName, @DOB, @Class, @Section)", conn);
        command.Parameters.Add(new OleDbParameter("RollNo", txtRollNo.Text));
        command.Parameters.Add(new OleDbParameter("SName", txtSName.Text));
        command.Parameters.Add(new OleDbParameter("FName", txtFName.Text));
        command.Parameters.Add(new OleDbParameter("DOB", dtpDOB.Text));
        command.Parameters.Add(new OleDbParameter("Class", cmbClass.Text));
        command.Parameters.Add(new OleDbParameter("Section", cmbSection.Text));
        command.ExecuteNonQuery();
        MessageBox.Show("Saved");
    }
}

When I Click Save Button this error is rising (Insert Into Syntax Error).

I have troubleshooted the code, I Find that if Field Section and Parameter @Section is removed from insert statement. Then Code works fine. But I want to Get ComboBox(CmbSection) Value of it and also to store on Database. How Can I?

Body:
"Section" is a reserved word in MS Access, so its use here is confusing the query parser.

You can explicitly tell the query what identifiers are referring to database objects (columns, tables, etc.) by wrapping them in square brackets:

INSERT INTO [Students]
    ([RollNo], [SName], [FName], [DOB], [Class], [Section])
    VALUES (@RollNo, @SName, @FName, @DOB, @Class, @Section)


问:
Change domain from og:image using CDN
I have my website www.diabeticme.org using a CDN.
The CDN creates an og:image URL that is not readable by Twitter card validator.
Can I overwrite the CDN URL for og:image only?

Example:

```<code><meta property="og:image" content="//293985-1025743-raikfcquaxqncofqfm.stackpathdns.com/wp-content/uploads/2020/05/jennifer-sepulveda-2-a-compressor.jpg" />
</code>```

What is should be:

```<code><meta property="og:image" content="https://www.diabeticme.org/wp-content/uploads/2020/05/jennifer-sepulveda-2-a-compressor.jpg" />
</code>```

I am using Wordpress and Yoast Premium Plugin.

I tried adding the following code to my functions.php but without any succes:

```<code>add_filter( 'wpseo_opengraph_image', 'change_opengraph_image_url' );

    function change_opengraph_image_url( $url ) {
        return str_replace('//293985-1025743-raikfcquaxqncofqfm.stackpathdns.com', 'https://diabeticme.org', $url);
    }
</code>```

Thank you for any input.

Kind regards
Ely

答: The wpseo_opengraph_image filter can only be used to modify the existing og:image. If you wish to change the URL, you will need to hook into the wpseo_opengraph action to add a different image URL.</p>

Title: Change domain from og:image using CDN

Body:
I have my website www.diabeticme.org using a CDN.
The CDN creates an og:image URL that is not readable by Twitter card validator.
Can I overwrite the CDN URL for og:image only?

Example:

<meta property="og:image" content="//293985-1025743-raikfcquaxqncofqfm.stackpathdns.com/wp-content/uploads/2020/05/jennifer-sepulveda-2-a-compressor.jpg" />

What is should be:

<meta property="og:image" content="https://www.diabeticme.org/wp-content/uploads/2020/05/jennifer-sepulveda-2-a-compressor.jpg" />

I am using Wordpress and Yoast Premium Plugin.

I tried adding the following code to my functions.php but without any succes:

add_filter( 'wpseo_opengraph_image', 'change_opengraph_image_url' );

    function change_opengraph_image_url( $url ) {
        return str_replace('//293985-1025743-raikfcquaxqncofqfm.stackpathdns.com', 'https://diabeticme.org', $url);
    }

Thank you for any input.

Kind regards
Ely


问:
Navigate a URL with Query string values on click of hyperlink
I have a control with 'email' and 'password' textboxes and a 'autoLogin' checkbox. All are web form controls (not html controls). And there is a 'Login' hyperlink. When I click on heperlink, I want to move to other page using NavigateUrl property like below:

```<code>NavigateUrl="~/DoLogin.aspx?email={0}&pwd={1}&autoLogin={3}"
</code>```

how to pass and how to get the query string?

Thanks in Advance...

答:
```<code>private void btnSubmit_Click(object sender, System.EventArgs e)
{
Response.Redirect("Webform2.aspx?Email=" +
this.txtemail.Text + "&Pwd=" +
txtPassword.Text);
}
</code>```

now for the next page(Webform2.aspx) go there and in page load event write this code

```<code>private void Page_Load(object sender, System.EventArgs e)
{
string Email = Request.QueryString["Email"];
 string password = Request.QueryString["Pwd"];
}
</code>```

You can use this one also

```<code>private void Page_Load(object sender, System.EventArgs e)
{
 string Email = Request.QueryString[0];
 string password = Request.QueryString[1];
}
</code>```

place this values where You Want

Body:
I have a control with 'email' and 'password' textboxes and a 'autoLogin' checkbox. All are web form controls (not html controls). And there is a 'Login' hyperlink. When I click on heperlink, I want to move to other page using NavigateUrl property like below:

NavigateUrl="~/DoLogin.aspx?email={0}&pwd={1}&autoLogin={3}"

how to pass and how to get the query string?

Thanks in Advance...

Body:
private void btnSubmit_Click(object sender, System.EventArgs e)
{
Response.Redirect("Webform2.aspx?Email=" +
this.txtemail.Text + "&Pwd=" +
txtPassword.Text);
}

now for the next page(Webform2.aspx) go there and in page load event write this code

private void Page_Load(object sender, System.EventArgs e)
{
string Email = Request.QueryString["Email"];
 string password = Request.QueryString["Pwd"];
}

You can use this one also

private void Page_Load(object sender, System.EventArgs e)
{
 string Email = Request.QueryString[0];
 string password = Request.QueryString[1];
}

place this values where You Want


问:
Why can 'CURRENT_DATE' not as a parameter when using NamedParameterJdbcTemplate in JAVA?
In mysql,I use this sql and it runs well.

select * from student where CREATE_TIME>=DATE_SUB(curdate(),INTERVAL 24 HOUR)

Now I want to use the date as a parameter,SO I use NamedParameterJdbcTemplate,If I pass the date like '2020-05-30',it also runs well.But when I pass 'CURRENT_DATE' or 'curdate()',it could not search any result.How to change my code?

```<code> NamedParameterJdbcTemplate nameJdbc = new NamedParameterJdbcTemplate(jdbcTemplate);
    Map<String,Object> paramMap = new HashMap<String, Object>();
    //dateStr when '2020-05-30' is ok,'CURRENT_DATE' is not ok;
   paramMap.put("dateStr",dateStr);
    String sql = "SELECT *"
            + " FROM student where CREATE_TIME>=DATE_SUB(:dateStr,INTERVAL 24 HOUR)" ;
    return   nameJdbc.query(sql,paramMap,
            new BeanPropertyRowMapper<>(Student.class));
</code>```

答:
It doesn't work, because the CURRENT_DATE, or an equivalent function call is being inserted as a string parameter, and not as a keyword.

One thing you could do is to manually replace the :dateStr in the SQL string with CURRENT_DATE if the parameter is empty, otherwise put its value in the parameter map.

A better option would be to just use LocalDate.now().toString() to set the date string, if the parameter is empty, and always set it in the SQL statement.

Body:
In mysql,I use this sql and it runs well.

select * from student where CREATE_TIME>=DATE_SUB(curdate(),INTERVAL 24 HOUR)

Now I want to use the date as a parameter,SO I use NamedParameterJdbcTemplate,If I pass the date like '2020-05-30',it also runs well.But when I pass 'CURRENT_DATE' or 'curdate()',it could not search any result.How to change my code?

 NamedParameterJdbcTemplate nameJdbc = new NamedParameterJdbcTemplate(jdbcTemplate);
    Map<String,Object> paramMap = new HashMap<String, Object>();
    //dateStr when '2020-05-30' is ok,'CURRENT_DATE' is not ok;
   paramMap.put("dateStr",dateStr);
    String sql = "SELECT *"
            + " FROM student where CREATE_TIME>=DATE_SUB(:dateStr,INTERVAL 24 HOUR)" ;
    return   nameJdbc.query(sql,paramMap,
            new BeanPropertyRowMapper<>(Student.class));


问:
Flutter. Path scaling
How can I change the size of path in this section of code? When drawing, the path goes beyond the phone screen.
I should not have access to drawing the paths themselves.

```<code>Path path = getPath();  //the path is given dynamically

canvas.drawPath(
  path,
  Paint()
    ..style = PaintingStyle.stroke
    ..color = Colors.black
    ..strokeWidth = 2.0);
</code>```

I tried to use the method path.transform. But the path is not transformed correctly.

答:
The code for adjustment is as follows.

```<code>main() => runApp(MaterialApp(home: SO()));

class SO extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        child: CustomPaint(
          painter: SOP(),
        ),
      ),
    );
  }
}

class SOP extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    Path p = getPath();

    Rect b = p.getBounds();
    var path_width = b.width;
    var path_height = b.height;
    var screen_width = size.width;
    var screen_height = size.height;
    var x_scale = screen_width / path_width;
    var y_scale = screen_height / path_height;

    //UNCOMMENT the following line to see the scaling effect
//    canvas.scale(x_scale, y_scale);

    canvas.drawPath(p, Paint()..color = Colors.red);
  }

  Path getPath() {
    Path p = Path();
    double w = 100;
    double h = 100;
    p.moveTo(0, 0);
    p.lineTo(0, h);
    p.lineTo(w, h);
    p.lineTo(w, 0);
    p.close();
    return p;
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }
}
</code>```

Uncomment the scaling line to see the effect.

Title: Flutter. Path scaling

Body:
How can I change the size of path in this section of code? When drawing, the path goes beyond the phone screen.
I should not have access to drawing the paths themselves.

Path path = getPath();  //the path is given dynamically

canvas.drawPath(
  path,
  Paint()
    ..style = PaintingStyle.stroke
    ..color = Colors.black
    ..strokeWidth = 2.0);

I tried to use the method path.transform. But the path is not transformed correctly.

Body:
The code for adjustment is as follows.

main() => runApp(MaterialApp(home: SO()));

class SO extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        child: CustomPaint(
          painter: SOP(),
        ),
      ),
    );
  }
}

class SOP extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    Path p = getPath();

    Rect b = p.getBounds();
    var path_width = b.width;
    var path_height = b.height;
    var screen_width = size.width;
    var screen_height = size.height;
    var x_scale = screen_width / path_width;
    var y_scale = screen_height / path_height;

    //UNCOMMENT the following line to see the scaling effect
//    canvas.scale(x_scale, y_scale);

    canvas.drawPath(p, Paint()..color = Colors.red);
  }

  Path getPath() {
    Path p = Path();
    double w = 100;
    double h = 100;
    p.moveTo(0, 0);
    p.lineTo(0, h);
    p.lineTo(w, h);
    p.lineTo(w, 0);
    p.close();
    return p;
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }
}

Uncomment the scaling line to see the effect.


问:
Getting Segmentation Fault on running hyperledger/explorer in docker container
I am getting segmentation fault and docker exited with code 139 on running hyperledger-explorer docker image.

docker-compose file for creating explorer-db

```<code>version: "2.1"

volumes:
  data:
  walletstore:
  pgadmin_4:
    external: true

networks:
  mynetwork.com:
    external:
      name: bikeblockchain_network

services:
  explorerdb.mynetwork.com:
    image: hyperledger/explorer-db:V1.0.0
    container_name: explorerdb.mynetwork.com
    hostname: explorerdb.mynetwork.com
    restart: always
    ports:
      - 54320:5432
    environment:
      - DATABASE_DATABASE=fabricexplorer
      - DATABASE_USERNAME=hppoc
      - DATABASE_PASSWORD=password
    healthcheck:
      test: "pg_isready -h localhost -p 5432 -q -U postgres"
      interval: 30s
      timeout: 10s
      retries: 5
    volumes:
      - data:/var/lib/postgresql/data
    networks:
      mynetwork.com:
        aliases:
          - postgresdb

  pgadmin:
      image: dpage/pgadmin4
      restart: always
      environment:
        PGADMIN_DEFAULT_EMAIL: user@domain.com
        PGADMIN_DEFAULT_PASSWORD: SuperSecret
        PGADMIN_CONFIG_ENHANCED_COOKIE_PROTECTION: "True"
        # PGADMIN_CONFIG_LOGIN_BANNER: "Authorized Users Only!"
        PGADMIN_CONFIG_CONSOLE_LOG_LEVEL: 10
      volumes:
        - "pgadmin_4:/var/lib/pgadmin"
      ports:
        - 8080:80
      networks:
        - mynetwork.com

</code>```

docker-compose-explorer file

```<code>version: "2.1"

volumes:
  data:
  walletstore:
    external: true
  pgadmin_4:
    external: true

networks:
  mynetwork.com:
    external:
      name: bikeblockchain_network

services:
  explorer.mynetwork.com:
    image: hyperledger/explorer:V1.0.0
    container_name: explorer.mynetwork.com
    hostname: explorer.mynetwork.com
    # restart: always
    environment:
      - DATABASE_HOST=xx.xxx.xxx.xxx
      #Host is VM IP address with ports exposed for postgres. No issues here
      - DATABASE_PORT=54320
      - DATABASE_DATABASE=fabricexplorer
      - DATABASE_USERNAME=hppoc
      - DATABASE_PASSWD=password
      - LOG_LEVEL_APP=debug
      - LOG_LEVEL_DB=debug
      - LOG_LEVEL_CONSOLE=info
      # - LOG_CONSOLE_STDOUT=true
      - DISCOVERY_AS_LOCALHOST=false
    volumes:
      - ./config.json:/opt/explorer/app/platform/fabric/config.json
      - ./connection-profile:/opt/explorer/app/platform/fabric/connection-profile
      - ./examples/net1/crypto:/tmp/crypto
      - walletstore:/opt/wallet
      - ./crypto-config/:/etc/data
    command: sh -c "node /opt/explorer/main.js && tail -f /dev/null"
    ports:
      - 6060:6060
    networks:
      - mynetwork.com

</code>```

error

```<code>Attaching to explorer.mynetwork.com
explorer.mynetwork.com    | Segmentation fault
explorer.mynetwork.com exited with code 139

</code>```

Postgres is working fine. Docker is updated to the latest version.
Fabric network being used is generated inside IBM Blockchain VS Code extension.

答: Okay!! So I did some testings and found that if, the Docker is set to Run on Windows Login, Explorer will throw error of segmentation fault, but if, I manually start Docker after windows login, it works well. Strange !!</p>

Body:
I am getting segmentation fault and docker exited with code 139 on running hyperledger-explorer docker image.

docker-compose file for creating explorer-db

version: "2.1"

volumes:
  data:
  walletstore:
  pgadmin_4:
    external: true

networks:
  mynetwork.com:
    external:
      name: bikeblockchain_network

services:
  explorerdb.mynetwork.com:
    image: hyperledger/explorer-db:V1.0.0
    container_name: explorerdb.mynetwork.com
    hostname: explorerdb.mynetwork.com
    restart: always
    ports:
      - 54320:5432
    environment:
      - DATABASE_DATABASE=fabricexplorer
      - DATABASE_USERNAME=hppoc
      - DATABASE_PASSWORD=password
    healthcheck:
      test: "pg_isready -h localhost -p 5432 -q -U postgres"
      interval: 30s
      timeout: 10s
      retries: 5
    volumes:
      - data:/var/lib/postgresql/data
    networks:
      mynetwork.com:
        aliases:
          - postgresdb

  pgadmin:
      image: dpage/pgadmin4
      restart: always
      environment:
        PGADMIN_DEFAULT_EMAIL: user@domain.com
        PGADMIN_DEFAULT_PASSWORD: SuperSecret
        PGADMIN_CONFIG_ENHANCED_COOKIE_PROTECTION: "True"
        # PGADMIN_CONFIG_LOGIN_BANNER: "Authorized Users Only!"
        PGADMIN_CONFIG_CONSOLE_LOG_LEVEL: 10
      volumes:
        - "pgadmin_4:/var/lib/pgadmin"
      ports:
        - 8080:80
      networks:
        - mynetwork.com

docker-compose-explorer file

version: "2.1"

volumes:
  data:
  walletstore:
    external: true
  pgadmin_4:
    external: true

networks:
  mynetwork.com:
    external:
      name: bikeblockchain_network

services:
  explorer.mynetwork.com:
    image: hyperledger/explorer:V1.0.0
    container_name: explorer.mynetwork.com
    hostname: explorer.mynetwork.com
    # restart: always
    environment:
      - DATABASE_HOST=xx.xxx.xxx.xxx
      #Host is VM IP address with ports exposed for postgres. No issues here
      - DATABASE_PORT=54320
      - DATABASE_DATABASE=fabricexplorer
      - DATABASE_USERNAME=hppoc
      - DATABASE_PASSWD=password
      - LOG_LEVEL_APP=debug
      - LOG_LEVEL_DB=debug
      - LOG_LEVEL_CONSOLE=info
      # - LOG_CONSOLE_STDOUT=true
      - DISCOVERY_AS_LOCALHOST=false
    volumes:
      - ./config.json:/opt/explorer/app/platform/fabric/config.json
      - ./connection-profile:/opt/explorer/app/platform/fabric/connection-profile
      - ./examples/net1/crypto:/tmp/crypto
      - walletstore:/opt/wallet
      - ./crypto-config/:/etc/data
    command: sh -c "node /opt/explorer/main.js && tail -f /dev/null"
    ports:
      - 6060:6060
    networks:
      - mynetwork.com

error

Attaching to explorer.mynetwork.com
explorer.mynetwork.com    | Segmentation fault
explorer.mynetwork.com exited with code 139

Postgres is working fine. Docker is updated to the latest version.
Fabric network being used is generated inside IBM Blockchain VS Code extension.


问:
javascript, parse an html string and recognize parts
I have a string like this:

```<code>"this is a string with <em>html</em> values"
</code>```

and I need to recognize the em part and the before and after part of the html tags.

can I use javascript to split the string into an array, as example:

```<code>["this is a string with", "html", "values"]
</code>```

答:
The other answer is useful if you want to navigate between html nodes, but if you are interested in manipulating strings instead, you can look into regular expressions. See for instance https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions for an introduction.

// Input string
let str = 'this is a string with html values';

// The reg exp matching what you asked.
let reg_exp = /(.+)(.+)<\/em>(.+)/;

// Verify that the input string matches the result
if(reg_exp.test(str)) {

  // Extract the value captured by the parenthesis
  let output = [RegExp.$1, RegExp.$2, RegExp.$3];

  // Contains ["this is a string with", "html", "values"]
  console.log(output);
}```

Body:
I have a string like this:

"this is a string with html values"

and I need to recognize the em part and the before and after part of the html tags.

can I use javascript to split the string into an array, as example:

["this is a string with", "html", "values"]

Body:
The other answer is useful if you want to navigate between html nodes, but if you are interested in manipulating strings instead, you can look into regular expressions. See for instance https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions for an introduction.

// Input string
let str = 'this is a string with <em>html</em> values';

// The reg exp matching what you asked.
let reg_exp = /(.+)<em>(.+)<\/em>(.+)/;

// Verify that the input string matches the result
if(reg_exp.test(str)) {

  // Extract the value captured by the parenthesis
  let output = [RegExp.$1, RegExp.$2, RegExp.$3];

  // Contains ["this is a string with", "html", "values"]
  console.log(output);
}


问:
Tab switching in android?
i have Tab host which is shown below,

```<code> private TabHost myTabHost;

......

    setContentView(R.layout.vidtab);

    Intent intent=getIntent();

    intent = new Intent().setClass(this, RecordActivityGroup.class);
    myTabHost = (TabHost)this.findViewById(android.R.id.tabhost);
    myTabHost.setup();
    TabSpec rectab = myTabHost.newTabSpec("Record");
    rectab.setIndicator("Record",getResources().getDrawable(R.drawable.irecord));
    rectab.setContent(intent);

    myTabHost.addTab(rectab);
   intent = new Intent().setClass(this, sharingProject.class);

    TabSpec setting = myTabHost.newTabSpec("Hint");
    setting.setIndicator("Hint",getResources().getDrawable(R.drawable.isettings));
    setting.setContent(intent);

    myTabHost.addTab(setting);
</code>```

in that record Activity group i have following code,

RecordActivityGroup extends TabGroupActivity{

```<code>@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    startChildActivity("RecordingActivity", new Intent(this,Record.class));

}
</code>```

and Record.class is an activity which contain one button, i need to switch to second tab while clicking button in Record class, how to do that? i any one know that please help me out.

答:
You can use an method in your main class like following

```<code>public void switchToTab(int tabid){
            myTabHost.setCurrentTab(tabid);
}
</code>```

And now in Record class on your Button click call this

```<code>        YourStartCalss parentActivity;
        parentActivity= (YourStartCalss) this.getParent();
        parentActivity.switchToTab(yourtabid);
</code>```

Title: Tab switching in android?

Body:
i have Tab host which is shown below,

 private TabHost myTabHost;

......

    setContentView(R.layout.vidtab);

    Intent intent=getIntent();

    intent = new Intent().setClass(this, RecordActivityGroup.class);
    myTabHost = (TabHost)this.findViewById(android.R.id.tabhost);
    myTabHost.setup();
    TabSpec rectab = myTabHost.newTabSpec("Record");
    rectab.setIndicator("Record",getResources().getDrawable(R.drawable.irecord));
    rectab.setContent(intent);

    myTabHost.addTab(rectab);
   intent = new Intent().setClass(this, sharingProject.class);

    TabSpec setting = myTabHost.newTabSpec("Hint");
    setting.setIndicator("Hint",getResources().getDrawable(R.drawable.isettings));
    setting.setContent(intent);

    myTabHost.addTab(setting);

in that record Activity group i have following code,

RecordActivityGroup extends TabGroupActivity{

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    startChildActivity("RecordingActivity", new Intent(this,Record.class));

}

and Record.class is an activity which contain one button, i need to switch to second tab while clicking button in Record class, how to do that? i any one know that please help me out.

Body:
You can use an method in your main class like following

public void switchToTab(int tabid){
            myTabHost.setCurrentTab(tabid);
}

And now in Record class on your Button click call this

        YourStartCalss parentActivity;
        parentActivity= (YourStartCalss) this.getParent();
        parentActivity.switchToTab(yourtabid);


问:
streamreader encoding not working on remote machine
I have an email body that I read from a file. I had encoding issues which I have fixed in the past. I tried and verfied this works properly on my computer. WHen I start the app on the remote server and let it run it runs as if it isn't using UTF8.

```<code>using StreamReader sr = new StreamReader("C:\\EmailTemplates\\Spanish.html", Encoding.UTF8);
body = await sr.ReadToEndAsync();
var encodingused = sr.CurrentEncoding;
</code>```

I have confirmed that the CurrentEncoding remotely and localy are both UTF8 using the remote debugger. I am using .net core 3.1

Email body from remote machine: �Gracias por elegir

Email body from Local Dev: ¡Gracias por elegir

答: I Figured out the issue,the problem was not the code. The problem was I was using PowerShell to edit the file and upload it to the environment as part of automated deployment using Octopus Deploy. Editing the file in PS change the file to a different format (ANSI). to file the problem when I use the PS command Set content I needed to specify UFT8  Set-Content -Path $file -Encoding UTF8

Body:
I have an email body that I read from a file. I had encoding issues which I have fixed in the past. I tried and verfied this works properly on my computer. WHen I start the app on the remote server and let it run it runs as if it isn't using UTF8.

using StreamReader sr = new StreamReader("C:\\EmailTemplates\\Spanish.html", Encoding.UTF8);
body = await sr.ReadToEndAsync();
var encodingused = sr.CurrentEncoding;

I have confirmed that the CurrentEncoding remotely and localy are both UTF8 using the remote debugger. I am using .net core 3.1

Email body from remote machine: �Gracias por elegir

Email body from Local Dev: ¡Gracias por elegir


问:
How can I convert the datetime intervals into a dataframe?
I would like to make a dataframe of dates with an interval of a week. I have used the following codes to generate a list of dates but when I want to make this into a dataframe, I got this error:

ValueError: DataFrame constructor not properly called!

Could you give me a hlep?

```<code>import pandas as pd

from datetime import date, datetime, timedelta

def perdelta(start, end, delta):
    curr = start
    while curr < end:
        yield curr
        curr += delta

for dates in perdelta(date(1997, 7, 19), date(2020, 5, 25), timedelta(days=7)):
    OP_dates = pd.DataFrame(dates)

print(OP_dates.head(3))
</code>```

答:
Are you familiar with pandas.date_range?  I believe this does exactly what you want:

```<code>import pandas as pd

date_range = pd.date_range('7-19-1997','5-25-2020',freq='1W')

#if you want the dates as entries
df = pd.DataFrame(date_range)

#or if you want the dates as the index:
df = pd.DataFrame(index=date_range)
</code>```

Looks like someone just posted a fix using your perdelta function which also works - the issue was that your for loop tried to make a DataFrame for each date yielded from perdelta rather than making a single DataFrame for a collection/array of the dates yielded by perdelta.

JSYK you can also use datetimes with pandas.date_range, instead of the time strings I used.

Body:
I would like to make a dataframe of dates with an interval of a week. I have used the following codes to generate a list of dates but when I want to make this into a dataframe, I got this error:

ValueError: DataFrame constructor not properly called!

Could you give me a hlep?

import pandas as pd

from datetime import date, datetime, timedelta

def perdelta(start, end, delta):
    curr = start
    while curr < end:
        yield curr
        curr += delta

for dates in perdelta(date(1997, 7, 19), date(2020, 5, 25), timedelta(days=7)):
    OP_dates = pd.DataFrame(dates)

print(OP_dates.head(3))

Body:
Are you familiar with pandas.date_range?  I believe this does exactly what you want:

import pandas as pd

date_range = pd.date_range('7-19-1997','5-25-2020',freq='1W')

#if you want the dates as entries
df = pd.DataFrame(date_range)

#or if you want the dates as the index:
df = pd.DataFrame(index=date_range)

Looks like someone just posted a fix using your perdelta function which also works - the issue was that your for loop tried to make a DataFrame for each date yielded from perdelta rather than making a single DataFrame for a collection/array of the dates yielded by perdelta.

JSYK you can also use datetimes with pandas.date_range, instead of the time strings I used.


问:
Mask collision between two sprite groups
My player attacks by throwing their weapon at the enemies. This is currently done by using a singular sword that gets thrown, then teleports back to the player to be thrown again. I want to change this so that I have a class called sword which I can call when the player wants to throw a weapon. However, I have no idea how to do collision between to sprite groups. Heres an example of how my collision currently works (Its easier to just show the whole enemy class)

class Bat(pygame.sprite.Sprite):
    def __init__(self, bat_x, bat_y, bat_image, bat_health, bat_immune, const, dash_counter, dash, dash_time, fly_count, fly_time): #There is an indent in the actual code, but stack overflow removed it in copying and pasting
        pygame.sprite.Sprite.__init__(self)
        self.bat_health = bat_health
        self.bat_immune = bat_immune
        self.const = const
        self.dash_counter = dash_counter
        self.dash = dash
        self.dash_time = dash_time
        self.fly_count = fly_count
        self.fly_time = fly_time
        self.image = bat_image
        self.rect = self.image.get_rect()
        self.mask = pygame.mask.from_surface(self.image)
        self.rect.topleft = (bat_x, bat_y)
        self.bat_x = bat_x
        self.bat_y = bat_y

    def fly(self):
        global dash_time
        global dash
        global const
        x = player_rect.centerx - self.rect.centerx
        y = player_rect.centery - self.rect.centery
        if x == 0:
            x = 0.1
        if y == 0:
            y = 0.1
        self.dash_counter = random.randint(0, 120)
        if self.dash_counter == 30:
            if self.dash == False:
                self.dash_time = pygame.time.get_ticks() ##def self in __init__
                self.dash = True
                self.const = 5.5
        if pygame.time.get_ticks() - self.dash_time > 1500:
            self.dash = False
            self.const = 3
        norm = (x**2 + y**2)**0.5
        self.bat_x += self.const * x / norm
        self.bat_y += self.const * y / norm

        if self.const * y / norm > 0:
            if self.fly_count == 0:
                self.image = bat_front1
                self.fly_time = pygame.time.get_ticks()
                self.fly_count = 1
            if self.fly_count == 1:
                if pygame.time.get_ticks() - self.fly_time > 600:
                    self.image = bat_front2
                    if pygame.time.get_ticks() - self.fly_time > 1200:
                        self.fly_count = 0

        if self.const * y / norm < 0:
            if self.fly_count == 0:
                self.image = bat_back1
                self.fly_time = pygame.time.get_ticks()
                self.fly_count = 1
            if self.fly_count == 1:
                if pygame.time.get_ticks() - self.fly_time > 600:
                    self.image = bat_back2
                    if pygame.time.get_ticks() - self.fly_time > 1200:
                        self.fly_count = 0

    def update(self): ##RELEVANT##
        global player_immune
        global player_health
        global immune_time
        global player_hitsound
        global enemy_hitsound
        global dmg_multiplier
        self.rect.topleft = (self.bat_x, self.bat_y)
        bat_immune = False
        bat_health = 5
        offsetP2B = (int(x - self.bat_x), int(y - self.bat_y)) #Player to Bat
        resultP2B = self.mask.overlap(player_mask, offsetP2B)
        if resultP2B:
            if player_immune == False:
                if invincibility_potion_activ == False:
                    player_health -= 1
                    player_hitsound.play()
                    immune_time = pygame.time.get_ticks()
                    player_immune = True

        offsetS2B = (int(fx - self.bat_x), int(fy - self.bat_y)) #Sword to Bat
        resultS2B = self.mask.overlap(sword_mask, offsetS2B)
        if resultS2B:
            if self.bat_immune == False:
                if fire == True:
                    self.bat_health -= 1 * dmg_multiplier
                    enemy_hitsound.play()
                    self.bat_time = pygame.time.get_ticks()
                    self.bat_immune = True
        if self.bat_health <= 0:
            self.kill()

        if self.bat_immune == True:
            if pygame.time.get_ticks() - self.bat_time > 100:
                self.bat_immune = False
        self.fly()

    all_bats = pygame.sprite.Group()
```

This works perfectly, but I want my weapon to be like the enemies, a sprite group so I can have multiple on the screen at one time, but then how would I do the collision?? I honestly have no clue how to work around this problem!

答:
I believe pygame.sprite.groupcollide() is what you are looking for?  "Find all sprites that collide between two groups."

You could also use pygame.sprite.spritecollideany() if you wanted to go through them one sword at time.

Body:
My player attacks by throwing their weapon at the enemies. This is currently done by using a singular sword that gets thrown, then teleports back to the player to be thrown again. I want to change this so that I have a class called sword which I can call when the player wants to throw a weapon. However, I have no idea how to do collision between to sprite groups. Heres an example of how my collision currently works (Its easier to just show the whole enemy class)

class Bat(pygame.sprite.Sprite):
    def __init__(self, bat_x, bat_y, bat_image, bat_health, bat_immune, const, dash_counter, dash, dash_time, fly_count, fly_time): #There is an indent in the actual code, but stack overflow removed it in copying and pasting
        pygame.sprite.Sprite.__init__(self)
        self.bat_health = bat_health
        self.bat_immune = bat_immune
        self.const = const
        self.dash_counter = dash_counter
        self.dash = dash
        self.dash_time = dash_time
        self.fly_count = fly_count
        self.fly_time = fly_time
        self.image = bat_image
        self.rect = self.image.get_rect()
        self.mask = pygame.mask.from_surface(self.image)
        self.rect.topleft = (bat_x, bat_y)
        self.bat_x = bat_x
        self.bat_y = bat_y

    def fly(self):
        global dash_time
        global dash
        global const
        x = player_rect.centerx - self.rect.centerx
        y = player_rect.centery - self.rect.centery
        if x == 0:
            x = 0.1
        if y == 0:
            y = 0.1
        self.dash_counter = random.randint(0, 120)
        if self.dash_counter == 30:
            if self.dash == False:
                self.dash_time = pygame.time.get_ticks() ##def self in __init__
                self.dash = True
                self.const = 5.5
        if pygame.time.get_ticks() - self.dash_time > 1500:
            self.dash = False
            self.const = 3
        norm = (x**2 + y**2)**0.5
        self.bat_x += self.const * x / norm
        self.bat_y += self.const * y / norm

        if self.const * y / norm > 0:
            if self.fly_count == 0:
                self.image = bat_front1
                self.fly_time = pygame.time.get_ticks()
                self.fly_count = 1
            if self.fly_count == 1:
                if pygame.time.get_ticks() - self.fly_time > 600:
                    self.image = bat_front2
                    if pygame.time.get_ticks() - self.fly_time > 1200:
                        self.fly_count = 0

        if self.const * y / norm < 0:
            if self.fly_count == 0:
                self.image = bat_back1
                self.fly_time = pygame.time.get_ticks()
                self.fly_count = 1
            if self.fly_count == 1:
                if pygame.time.get_ticks() - self.fly_time > 600:
                    self.image = bat_back2
                    if pygame.time.get_ticks() - self.fly_time > 1200:
                        self.fly_count = 0

    def update(self): ##RELEVANT##
        global player_immune
        global player_health
        global immune_time
        global player_hitsound
        global enemy_hitsound
        global dmg_multiplier
        self.rect.topleft = (self.bat_x, self.bat_y)
        bat_immune = False
        bat_health = 5
        offsetP2B = (int(x - self.bat_x), int(y - self.bat_y)) #Player to Bat
        resultP2B = self.mask.overlap(player_mask, offsetP2B)
        if resultP2B:
            if player_immune == False:
                if invincibility_potion_activ == False:
                    player_health -= 1
                    player_hitsound.play()
                    immune_time = pygame.time.get_ticks()
                    player_immune = True

        offsetS2B = (int(fx - self.bat_x), int(fy - self.bat_y)) #Sword to Bat
        resultS2B = self.mask.overlap(sword_mask, offsetS2B)
        if resultS2B:
            if self.bat_immune == False:
                if fire == True:
                    self.bat_health -= 1 * dmg_multiplier
                    enemy_hitsound.play()
                    self.bat_time = pygame.time.get_ticks()
                    self.bat_immune = True
        if self.bat_health <= 0:
            self.kill()

        if self.bat_immune == True:
            if pygame.time.get_ticks() - self.bat_time > 100:
                self.bat_immune = False
        self.fly()

    all_bats = pygame.sprite.Group()

This works perfectly, but I want my weapon to be like the enemies, a sprite group so I can have multiple on the screen at one time, but then how would I do the collision?? I honestly have no clue how to work around this problem!


问:
Table Not Found with Hibernate and HSQLDB
We're using hibernate entitymanager to map our entities through JPA. And we are using HSQLDB in-memory database for unit testing. Everything was fine until a recent refactor to the model started causing the following error:

```<code>17:55:48.516 [main] WARN  o.h.util.JDBCExceptionReporter - SQL Error: -22, SQLState: S0002
17:55:48.517 [main] ERROR o.h.util.JDBCExceptionReporter - Table not found in statement
</code>```

I can't post the SQL in question, but can anyone give me pointers as to the possible causes of the above error? especially since I know the code was working before. It seems like hibernate is generating invalid sqls because of the refactor?

答:
Use dependency

```<code>groupId org.hsqldb
</code>```

instead of

```<code>groupId hsqldb
</code>```

in your pom.xml or gradle. Check out https://mvnrepository.com/search?q=hsqldb

ContentLicense: CC BY-SA 2.5

Body:
We're using hibernate entitymanager to map our entities through JPA. And we are using HSQLDB in-memory database for unit testing. Everything was fine until a recent refactor to the model started causing the following error:

17:55:48.516 [main] WARN  o.h.util.JDBCExceptionReporter - SQL Error: -22, SQLState: S0002
17:55:48.517 [main] ERROR o.h.util.JDBCExceptionReporter - Table not found in statement

I can't post the SQL in question, but can anyone give me pointers as to the possible causes of the above error? especially since I know the code was working before. It seems like hibernate is generating invalid sqls because of the refactor?

Body:
Use dependency

groupId org.hsqldb

instead of

groupId hsqldb

in your pom.xml or gradle. Check out https://mvnrepository.com/search?q=hsqldb


问:
Formatting table in Jupyter
I was trying to make a table in Python, but there are some elements that don't fit... I've tried everything that I know and I'm not getting why this is getting like this

The code is this:

```<code>    print("Year nº \t\t Stdts 1st year \t\t Stdts 2nd year \t\t Stdts 3rd years \t\t Stdts 4th year \t\t Stdts 5th year \n") #1st line of the table
    print(" %d \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t \n" %(actualYear, N1, N2, N3, N4, N5)) #Year 0 of the table

    while actualYear < 19:
          ...
    print(" %d \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t \n" %(actualYear, N1, N2, N3, N4, N5))
</code>```

Thanks in advance.

答:
Two solutions:

Don’t use tabs. They advance to the next tab stop which is usually the column number divisible by 8. Notice how your first values are shorter so it throws off where the tab stop ends up.

Set your field widths correctly. %3.2f means your field has a width of 3, but your largest numbers have a width of 6. Use %6.2f instead.

Title: Formatting table in Jupyter

Body:
I was trying to make a table in Python, but there are some elements that don't fit... I've tried everything that I know and I'm not getting why this is getting like this

The code is this:

    print("Year nº \t\t Stdts 1st year \t\t Stdts 2nd year \t\t Stdts 3rd years \t\t Stdts 4th year \t\t Stdts 5th year \n") #1st line of the table
    print(" %d \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t \n" %(actualYear, N1, N2, N3, N4, N5)) #Year 0 of the table

    while actualYear < 19:
          ...
    print(" %d \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t \n" %(actualYear, N1, N2, N3, N4, N5))

Thanks in advance.


问:
Adding calculated fields to Google-Sheets form results
I'm taking data with a Google Spreadsheet form.
But for grouping puproses I want to add a column in the result-table with the weeknumber.

I also want a calculated field in my result-table.

Is this even possible? And what is the best way to accomplish this?

edit: hope this works.
this is the spreadsheet generated (and filled) by the form. Not the real one, just an example one.
https://docs.google.com/spreadsheets/d/1WXqNiP9EIx3lA0ND1ysFitfN9QVEGVXY2SI5cHF57oA/edit?usp=sharing

As said, I would like to be able to add a weeknumber field, and get a calculated field (total (Amount * Price))

The Calculated field can propabably be achieved with a query on a second Sheet. But I can't use a 'Weeknum()' in a query and group by it.

答:
For the week number, paste in the first cell of the column of your choice (e.g. E2):

=arrayformula(WEEKNUM(A2:A))

For the calculated product field, e.g. in F2:

=ARRAYFORMULA(C2:C*D2:D)

The results of the array formulas will automatically update when new form responses come into the spreadsheet.


问:
Is it better way to avoid „Cannot use mutating member on immutable” in var
I have a struct with var grid

```<code>struct Machina {
    ....
    var grid: [Whatever] = []
    var other: Something
    ... // other stuff
}
</code>```

But grid needs to be counted every time other changes. So, I can call

```<code>var other: Something {
    didSet {
        defineGrid()
    }
...

mutating func defineGrid() {
    var result: [Whatever]
    ... // count result
    grid = result
}
</code>```

but I would love to simply call grid as var and keep counted grid in _grid

```<code>var _grid: [Whatever]? = nil
var other: Something {
    didSet {
        _grid = nil
    }
...

mutating func defineGrid() {
    var result: [Whatever]
    ... // count result
    _grid = result
}
...
var grid: [Whatever] {
    if _grid == nil {
        defineGrid() // error: Cannot use mutating member on immutable value: 'self' is immutable
    }
    return _grid!
}
</code>```

but in this case I got an error. Is a first approach nice? Is it possible to get var grid from second approach? Maybe it's just a cosmetics. I don't know.

答:
If Swift 5 is used you can also use this handy @propertyWrapper:

```<code>@propertyWrapper
struct LazyWithReset<T> {
    private var value: T? = nil // this is hidden storage for the value, like _grid in the question

    var wrappedValue: T { // this is lazy-ish interface to access/generate value, like grid in the question
        mutating get {
            if (value == nil) {
                value = generator()
            }
            return value!
        }
    }
    var generator: () -> T // this is the function that sets value, like defineGrid in the question

    init(_ generator: @escaping () -> T) {
        self.generator = generator
    }

    mutating func reset() { // this is just resetting the storage while keeping internals hidden
        value = nil
    }
}
</code>```

Usage:

```<code>struct Machina {
    @LazyWithReset(defineGrid)
    private(set) var grid: [Whatever] // no initial value required, generator will lazily provide value if needed

    var other: Something {
        didSet {
            _grid.reset() // variable set, we reset our lazy variable
        }
    }

    private static func defineGrid() -> [Whatever] { // now it's pure static function, no mutability required
        return … // whatever you was directly setting to the grid var previously
    }
}
</code>```

This way you can hide all boilerplate code under the rug and keep your business logic clean.

Also LazyWithReset<T> can be reused wherever you want, so you won't have to copy-paste any code.

Body:
I have a struct with var grid

struct Machina {
    ....
    var grid: [Whatever] = []
    var other: Something
    ... // other stuff
}

But grid needs to be counted every time other changes. So, I can call

var other: Something {
    didSet {
        defineGrid()
    }
...

mutating func defineGrid() {
    var result: [Whatever]
    ... // count result
    grid = result
}

but I would love to simply call grid as var and keep counted grid in _grid

var _grid: [Whatever]? = nil
var other: Something {
    didSet {
        _grid = nil
    }
...

mutating func defineGrid() {
    var result: [Whatever]
    ... // count result
    _grid = result
}
...
var grid: [Whatever] {
    if _grid == nil {
        defineGrid() // error: Cannot use mutating member on immutable value: 'self' is immutable
    }
    return _grid!
}

but in this case I got an error. Is a first approach nice? Is it possible to get var grid from second approach? Maybe it's just a cosmetics. I don't know.

Body:
If Swift 5 is used you can also use this handy @propertyWrapper:

@propertyWrapper
struct LazyWithReset<T> {
    private var value: T? = nil // this is hidden storage for the value, like _grid in the question

    var wrappedValue: T { // this is lazy-ish interface to access/generate value, like grid in the question
        mutating get {
            if (value == nil) {
                value = generator()
            }
            return value!
        }
    }
    var generator: () -> T // this is the function that sets value, like defineGrid in the question

    init(_ generator: @escaping () -> T) {
        self.generator = generator
    }

    mutating func reset() { // this is just resetting the storage while keeping internals hidden
        value = nil
    }
}

Usage:

struct Machina {
    @LazyWithReset(defineGrid)
    private(set) var grid: [Whatever] // no initial value required, generator will lazily provide value if needed

    var other: Something {
        didSet {
            _grid.reset() // variable set, we reset our lazy variable
        }
    }

    private static func defineGrid() -> [Whatever] { // now it's pure static function, no mutability required
        return … // whatever you was directly setting to the grid var previously
    }
}

This way you can hide all boilerplate code under the rug and keep your business logic clean.

Also LazyWithReset<T> can be reused wherever you want, so you won't have to copy-paste any code.


问:
Subtraction in SQL
I am trying to create this trigger that allows me to subtract from the quantity present in articles, the quantity of articles that have just been sold. The only thing that doesn't work is subtraction. Can anyone help me? Thanks in advance</p>

```<code>CREATE TRIGGER subtraction
AFTER INSERT ON SoldItems
FOR EACH ROW
BEGIN
DECLARE s INT(11);
DECLARE qta INT(11);
SELECT Quantity INTO s
FROM Articles
WHERE ID=NEW.IDArticle
SET s=s-NEW.Quantity
UPDATE Articles SET Quanty= s WHERE ID=NEW.IDArticle
END
</code>```

答:
No need to select, compute, then update. You could use a simple update statement directly in the trigger, like so:

```<code>delimiter //

create trigger subtraction
after insert on solditems
for each row
begin
    update articles
    set quantity = quantity - new.quantity
    where id = new.id_article;
end
//

delimiter ;
</code>```

Title: Subtraction in SQL

Body:
I am trying to create this trigger that allows me to subtract from the quantity present in articles, the quantity of articles that have just been sold. The only thing that doesn't work is subtraction. Can anyone help me? Thanks in advance

CREATE TRIGGER subtraction
AFTER INSERT ON SoldItems
FOR EACH ROW
BEGIN
DECLARE s INT(11);
DECLARE qta INT(11);
SELECT Quantity INTO s
FROM Articles
WHERE ID=NEW.IDArticle
SET s=s-NEW.Quantity
UPDATE Articles SET Quanty= s WHERE ID=NEW.IDArticle
END

Body:
No need to select, compute, then update. You could use a simple update statement directly in the trigger, like so:

delimiter //

create trigger subtraction
after insert on solditems
for each row
begin
    update articles
    set quantity = quantity - new.quantity
    where id = new.id_article;
end
//

delimiter ;


问:
Spell checking using fastText model?
So I'm using fastText from its GitHub repo and wondering if it has build-in spell checking command.

If yes, how do I use them? and can I get full documentation of fastText because as in here answer from Kalana Geesara, I could use model.get_nearest_neighbor (and it worked) while I can't find it anywhere (even in the repo readme).

If no, is there any way for me to do spell checking with the model provided?

I am using english model provided here and code it without Gensim

答:
I've solved the problem by using Peter Norvig's Spell Correction Algorithm and load it with fastText models.

But I've to install it with Gensim since I only found a tutorial about it.

Title: Spell checking using fastText model?


问:
Multithread performance
I created very simple app to figure out how boost::thread works.
I found result of this test suprising.
4 threads of execution finish computation 2 times faster than 1 thread.
I expected 4x boost.
Another question is why 8 threads did not bring any performance boost?

I'm using boost 1.46.1 and VS2008. Full source code is below.
Program was run on Core i5 750 machine.

```<code>#include <iostream>
#include <vector>
#include <cmath>

#include <boost/thread.hpp>
#include <boost/timer.hpp>

typedef unsigned int uint;

struct Vector {
    float x, y, z;

    Vector() : x(0.f), y(0.f), z(0.f) {}

    float len() {
        return sqrtf(x*x + y*y + z*z);
    }

};

float norm(int a) {
    return float((a % 10) + 1) / 10.f;
}

void genVectors(std::vector<Vector>& examples) {
    srand(GetTickCount());

    for (uint i = 0; i < examples.size(); ++i) {
        examples[i].x = norm(rand());
        examples[i].y = norm(rand());
        examples[i].z = norm(rand());
    }

}

typedef std::vector<Vector> Data;
typedef Data::iterator DataIter;

typedef std::vector<float> Result;
typedef Result::iterator ResultIter;

struct Worker {
    Data   data;
    Result result;

    Worker(DataIter& dataStart,
           const DataIter& dataEnd,
           ResultIter& resultStart,
           const ResultIter& resultEnd) : data(dataStart, dataEnd), result(resultStart, resultEnd) {
        assert(data.size() == result.size());
    }

    void operator()() {
        DataIter di = data.begin();
        ResultIter ri = result.begin();

        const DataIter dend = data.end();

        for (; di != dend; ++di, ++ri) {
            *ri = di->len();
        }
    }
};

int main(int argc, char **argv) {
    const uint numThreads = 4;
    const uint seqLen = 13107200;

    std::vector<Vector> a;
    a.resize(seqLen);

    genVectors(a);

    std::vector<float> singleThreadResult(a.size());
    assert(a.size() == singleThreadResult.size());

    boost::timer singleThreadTimer;
    for (uint i = 0; i < a.size(); ++i) {
        singleThreadResult[i] = a[i].len();
    }
    double singleThreadTime = singleThreadTimer.elapsed();

    std::vector<float> multiThreadResult(a.size());

    Worker* workers[numThreads];
    for (uint i = 0; i < numThreads; ++i) {
        uint chunkSize = seqLen / numThreads;
        assert(numThreads * chunkSize == seqLen);

        workers[i] = new Worker(a.begin() + i*chunkSize,
                                a.begin() + (i+1)*chunkSize,
                                multiThreadResult.begin() + i*chunkSize,
                                multiThreadResult.begin() + (i+1)*chunkSize);
    }

    boost::timer multiThreadTimer;
    boost::thread_group threads;
    for (uint i = 0; i < numThreads; ++i) {
        threads.create_thread(boost::ref(*workers[i]));
    }
    threads.join_all();
    double multiThreadTime = multiThreadTimer.elapsed();

    using namespace std;
    cout << "Single thread time: " << singleThreadTime << endl;
    cout << numThreads << " threads time: " << multiThreadTime << endl;

    return 0;
}
</code>```

答: I've always found that it is impossible to predict the "best" number of threads for a given problem running on a given hardware configuration. My approach has been to parameterise the number of threads from the command line, and try various numbers until I hit the "sweet spot". </p>

Title: Multithread performance

Body:
I created very simple app to figure out how boost::thread works.
I found result of this test suprising.
4 threads of execution finish computation 2 times faster than 1 thread.
I expected 4x boost.
Another question is why 8 threads did not bring any performance boost?

I'm using boost 1.46.1 and VS2008. Full source code is below.
Program was run on Core i5 750 machine.

#include <iostream>
#include <vector>
#include <cmath>

#include <boost/thread.hpp>
#include <boost/timer.hpp>

typedef unsigned int uint;

struct Vector {
    float x, y, z;

    Vector() : x(0.f), y(0.f), z(0.f) {}

    float len() {
        return sqrtf(x*x + y*y + z*z);
    }

};

float norm(int a) {
    return float((a % 10) + 1) / 10.f;
}

void genVectors(std::vector<Vector>& examples) {
    srand(GetTickCount());

    for (uint i = 0; i < examples.size(); ++i) {
        examples[i].x = norm(rand());
        examples[i].y = norm(rand());
        examples[i].z = norm(rand());
    }

}

typedef std::vector<Vector> Data;
typedef Data::iterator DataIter;

typedef std::vector<float> Result;
typedef Result::iterator ResultIter;

struct Worker {
    Data   data;
    Result result;

    Worker(DataIter& dataStart,
           const DataIter& dataEnd,
           ResultIter& resultStart,
           const ResultIter& resultEnd) : data(dataStart, dataEnd), result(resultStart, resultEnd) {
        assert(data.size() == result.size());
    }

    void operator()() {
        DataIter di = data.begin();
        ResultIter ri = result.begin();

        const DataIter dend = data.end();

        for (; di != dend; ++di, ++ri) {
            *ri = di->len();
        }
    }
};

int main(int argc, char **argv) {
    const uint numThreads = 4;
    const uint seqLen = 13107200;

    std::vector<Vector> a;
    a.resize(seqLen);

    genVectors(a);

    std::vector<float> singleThreadResult(a.size());
    assert(a.size() == singleThreadResult.size());

    boost::timer singleThreadTimer;
    for (uint i = 0; i < a.size(); ++i) {
        singleThreadResult[i] = a[i].len();
    }
    double singleThreadTime = singleThreadTimer.elapsed();

    std::vector<float> multiThreadResult(a.size());

    Worker* workers[numThreads];
    for (uint i = 0; i < numThreads; ++i) {
        uint chunkSize = seqLen / numThreads;
        assert(numThreads * chunkSize == seqLen);

        workers[i] = new Worker(a.begin() + i*chunkSize,
                                a.begin() + (i+1)*chunkSize,
                                multiThreadResult.begin() + i*chunkSize,
                                multiThreadResult.begin() + (i+1)*chunkSize);
    }

    boost::timer multiThreadTimer;
    boost::thread_group threads;
    for (uint i = 0; i < numThreads; ++i) {
        threads.create_thread(boost::ref(*workers[i]));
    }
    threads.join_all();
    double multiThreadTime = multiThreadTimer.elapsed();

    using namespace std;
    cout << "Single thread time: " << singleThreadTime << endl;
    cout << numThreads << " threads time: " << multiThreadTime << endl;

    return 0;
}


问:
Conditional sum on multiple pandas groups, each defined by a set of overlapping column values
I'm trying to perform a conditional sum on groups of rows defined by a list of arbitrary column values. By conditional sum, I mean sum values in one column only if the value in a second column is above a threshold. There can be overlap among the groups and the number of elements in each group can be different.

For example, given the following dataframe:

data = {
   'id': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
   'counter': [10, 9, 8, 7, 6, 5, 4, 3, 2, 1],
   'output': [5, 10, 15, 20, 25, 35, 20, 15, 10, 5]
}
df = pd.DataFrame(data)
```
```>>> df
   id  counter  output
0   1       10       5
1   2        9      10
2   3        8      15
3   4        7      20
4   5        6      25
5   6        5      35
6   7        4      20
7   8        3      15
8   9        2      10
9  10        1       5
```
<p>And the following inputs (I'm flexible if we need to change their format):</p>
<pre class="lang-py prettyprint-override"><code>group_ids = {'Group A': [1, 2, 3, 4], 'Group B': [6, 7, 8, 9], 'Group C': [4, 5, 6]}
output_threshold = 12
</code>```

I would like to generate the following new dataframe, which is the sum of counter for each group defined by the list of group_ids only if output exceeds the specified output_threshold. Bonus points if I can add the title to each of these groups:

```<code>title    sum
Group A   15
Group B   12
Group C   18
</code>```

答:
You can use isin to check for values and sum:

```<code>mask = (df['output'] > output_threshold).astype(int)
for k,v in group_ids.items():
    df[k] = df['id'].isin(v) * mask * df['counter']

df[group_ids.keys()].sum()
</code>```

Output (can't quite match your expected):

```<code>Group A    15
Group B    12
Group C    18
dtype: int64
</code>```

Body:
I'm trying to perform a conditional sum on groups of rows defined by a list of arbitrary column values. By conditional sum, I mean sum values in one column only if the value in a second column is above a threshold. There can be overlap among the groups and the number of elements in each group can be different.

For example, given the following dataframe:

data = {
   'id': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
   'counter': [10, 9, 8, 7, 6, 5, 4, 3, 2, 1],
   'output': [5, 10, 15, 20, 25, 35, 20, 15, 10, 5]
}
df = pd.DataFrame(data)

>>> df
   id  counter  output
0   1       10       5
1   2        9      10
2   3        8      15
3   4        7      20
4   5        6      25
5   6        5      35
6   7        4      20
7   8        3      15
8   9        2      10
9  10        1       5

And the following inputs (I'm flexible if we need to change their format):

group_ids = {'Group A': [1, 2, 3, 4], 'Group B': [6, 7, 8, 9], 'Group C': [4, 5, 6]}
output_threshold = 12

I would like to generate the following new dataframe, which is the sum of counter for each group defined by the list of group_ids only if output exceeds the specified output_threshold. Bonus points if I can add the title to each of these groups:

title    sum
Group A   15
Group B   12
Group C   18

Body:
You can use isin to check for values and sum:

mask = (df['output'] > output_threshold).astype(int)
for k,v in group_ids.items():
    df[k] = df['id'].isin(v) * mask * df['counter']

df[group_ids.keys()].sum()

Output (can't quite match your expected):

Group A    15
Group B    12
Group C    18
dtype: int64


问:
Error while using sqlalchemy for mysql : Segmentation fault (core dumped)
I am trying to use sqlalchemy to connect to mysql server configured locally on my laptop.
However I am getting the error :

```<code>(database) ✔ ~/dev/database [master L|…9]
13:07 $ python database.py
Segmentation fault (core dumped)
(database) ✘-SEGV ~/dev/database [master L|…9]

(database) ✘-SEGV ~/dev/database [master L|…9]
13:07 $ python --version
Python 3.6.9
(database) ✔ ~/dev/database [master L|…9]
13:22 $ pip freeze
mysql-connector-python==8.0.20
mysqlclient==1.4.6
pkg-resources==0.0.0
protobuf==3.12.2
six==1.15.0
SQLAlchemy==1.3.17
(database) ✔ ~/dev/database [master L|…9]
</code>```

Code :

```<code>#!/bin/python3

"""
    Python module to interact with database.
"""
import sqlalchemy as db

class DataBase:

    def __init__(self, db_url):
        self.engine = db.create_engine(db_url)
        self.metadata = db.MetaData(self.engine)

        self.inventory = db.Table(
            'inventory',
            self.metadata,
            db.Column('address', db.String, primary_key=True),
            db.Column('name', db.String),
            db.Column('device_type', db.String, default='cisco_ios'),
            db.Column('group', db.String, nullable=False),
        )

        self.connect()
        self.metadata.create_all()
        self.disconnect()

    def connect(self):
        self.conn = self.engine.connect()
        if self.conn.closed:
            raise OSError("Tried to connect to DB server but connection still closed.")

    def disconnect(self):
        self.conn.close()

    def insert(self):
        pass

    def select(self):
        pass

    def update(self):
        pass

    def delete(self):
        pass

if __name__ == "__main__":
    test = DataBase("mysql+mysqlconnector://root:mysql@localhost:3306/inventory_db")
</code>```

Initial troubleshooting shows that whenever I am using "metadata" it is causing this error.
I if comment out "self.metadata.create_all()" and "self.metadata = db.MetaData(self.engine)" I do not get this error.

答: Found what the problem was, There is something wrong with mysql-python-connector, things do not work as expected if you use that. I used mysqlclient and it worked.</p>

Body:
I am trying to use sqlalchemy to connect to mysql server configured locally on my laptop.
However I am getting the error :

(database) ✔ ~/dev/database [master L|…9]
13:07 $ python database.py
Segmentation fault (core dumped)
(database) ✘-SEGV ~/dev/database [master L|…9]

(database) ✘-SEGV ~/dev/database [master L|…9]
13:07 $ python --version
Python 3.6.9
(database) ✔ ~/dev/database [master L|…9]
13:22 $ pip freeze
mysql-connector-python==8.0.20
mysqlclient==1.4.6
pkg-resources==0.0.0
protobuf==3.12.2
six==1.15.0
SQLAlchemy==1.3.17
(database) ✔ ~/dev/database [master L|…9]

Code :

#!/bin/python3

"""
    Python module to interact with database.
"""
import sqlalchemy as db

class DataBase:

    def __init__(self, db_url):
        self.engine = db.create_engine(db_url)
        self.metadata = db.MetaData(self.engine)

        self.inventory = db.Table(
            'inventory',
            self.metadata,
            db.Column('address', db.String, primary_key=True),
            db.Column('name', db.String),
            db.Column('device_type', db.String, default='cisco_ios'),
            db.Column('group', db.String, nullable=False),
        )

        self.connect()
        self.metadata.create_all()
        self.disconnect()

    def connect(self):
        self.conn = self.engine.connect()
        if self.conn.closed:
            raise OSError("Tried to connect to DB server but connection still closed.")

    def disconnect(self):
        self.conn.close()

    def insert(self):
        pass

    def select(self):
        pass

    def update(self):
        pass

    def delete(self):
        pass

if __name__ == "__main__":
    test = DataBase("mysql+mysqlconnector://root:mysql@localhost:3306/inventory_db")

Initial troubleshooting shows that whenever I am using "metadata" it is causing this error.
I if comment out "self.metadata.create_all()" and "self.metadata = db.MetaData(self.engine)" I do not get this error.


问:
"stderr;" as a statement throws no warning
Suppose I have a source code like this:

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

FILE *p;

int main(void) {
    p;
}
</code>```

... which will compile (using gcc) without any errors or warnings – unless I turn on -Wall, in which case a statement with no effect warning will be output.

However if the code went like this:

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

int main(void) {
    stderr;
}
</code>```

... no warnings would be shown regardless of -Wall.

Am I missing something here?

gcc version 9.3.0

答:
Yes... and if you write something like:

```<code>0;
</code>```

or

```<code>#include <math.h>
int main()
{

    cos(2.0*M_PI + 7.0);
}
</code>```

you'll get the same result (nothing will happen).  The reason is that a statement can be any expression (of any type) followed by a semicolon ; in C.  The expression value is just dropped, and execution continues with the next statement (in your case there's none).  In my examples, the 0 value of the expression, or the string literal "Hello world" are just dropped by the compiler with a null result.

Body:
Suppose I have a source code like this:

#include <stdio.h>

FILE *p;

int main(void) {
    p;
}

... which will compile (using gcc) without any errors or warnings – unless I turn on -Wall, in which case a statement with no effect warning will be output.

However if the code went like this:

#include <stdio.h>

int main(void) {
    stderr;
}

... no warnings would be shown regardless of -Wall.

Am I missing something here?

gcc version 9.3.0

Body:
Yes... and if you write something like:

0;

or

#include <math.h>
int main()
{

    cos(2.0*M_PI + 7.0);
}

you'll get the same result (nothing will happen).  The reason is that a statement can be any expression (of any type) followed by a semicolon ; in C.  The expression value is just dropped, and execution continues with the next statement (in your case there's none).  In my examples, the 0 value of the expression, or the string literal "Hello world" are just dropped by the compiler with a null result.