问:
c# and dynamic string scripting
I'd love some ideas about how I should implement a key part of a project I am working on.  Essentially it is data mapping, where I copy field x and put it into field y.  However, there needs to be some ability to dynamically change (using string manipulation) that value during the transition.

What I would like is a textbox where a user could enter script allowing them to modify that value using a scripting language, ideally VBScript.  That would then allow them to do simple manipulations such this example, which would take a substring:

```<code>Mid({input_value}, 2, 4)
</code>```

Where

```<code>{input_value}
</code>```

Would be replaced by the actual value at runtime.

So, for example, if the input from "field x" was "This is a test" and they used the above example of start = 2 and length = 4, the value saved into "field y" would be "his "

I know how I could run VBScript from C# as a scipt, that's not a problem.  However, Is it possible to run and evaluate srcipts such as above at runtime and record the output back into a C# variable?

Otherwise, does anyone have any suggestions about how I could approach this?

Many thanks

答:
Here is a working example using runtime compilation of expressions.  I borrowed the concept and most of the code from here.</p>

```<code>static void Main(string[] args)
{
    string input = "This is a test";
    string method = "Mid(x, 2, 4)";  // 'x' represents the input value
    string output = Convert(method, input);
    Console.WriteLine("Result: " + output);
    Console.ReadLine();
}

// Convert input using given vbscript logic and return as output string
static string Convert(string vbscript, string input)
{
    var func = GetFunction(vbscript);
    return func(input);
}

// Create a function from a string of vbscript that can be applied
static Func<string, string> GetFunction(string vbscript)
{
    // generate simple code snippet to evaluate expression
    VBCodeProvider prov = new VBCodeProvider();
    CompilerResults results = prov.CompileAssemblyFromSource(
        new CompilerParameters(new[] { "System.Core.dll" }),
        @"
Imports System
Imports System.Linq.Expressions
Imports Microsoft.VisualBasic

Class MyConverter

Public Shared Function Convert() As Expression(Of Func(Of String, String))
    return Function(x) " + vbscript + @"
End Function

End Class
"
        );

    // make sure no errors occurred in the conversion process
    if (results.Errors.Count == 0)
    {
        // retrieve the newly prepared function by executing the code
        var expr = (Expression<Func<string, string>>)
            results.CompiledAssembly.GetType("MyConverter")
                .GetMethod("Convert").Invoke(null, null);
        Func<string, string> func = expr.Compile();

        // create a compiled function ready to apply and return
        return func;
    }
    else
    {
        return null;
    }
}
</code>```

Title: c# and dynamic string scripting

Body:
I'd love some ideas about how I should implement a key part of a project I am working on.  Essentially it is data mapping, where I copy field x and put it into field y.  However, there needs to be some ability to dynamically change (using string manipulation) that value during the transition.

What I would like is a textbox where a user could enter script allowing them to modify that value using a scripting language, ideally VBScript.  That would then allow them to do simple manipulations such this example, which would take a substring:

Mid({input_value}, 2, 4)

Where

{input_value}

Would be replaced by the actual value at runtime.

So, for example, if the input from "field x" was "This is a test" and they used the above example of start = 2 and length = 4, the value saved into "field y" would be "his "

I know how I could run VBScript from C# as a scipt, that's not a problem.  However, Is it possible to run and evaluate srcipts such as above at runtime and record the output back into a C# variable?

Otherwise, does anyone have any suggestions about how I could approach this?

Many thanks

Body:
Here is a working example using runtime compilation of expressions.  I borrowed the concept and most of the code from here.

static void Main(string[] args)
{
    string input = "This is a test";
    string method = "Mid(x, 2, 4)";  // 'x' represents the input value
    string output = Convert(method, input);
    Console.WriteLine("Result: " + output);
    Console.ReadLine();
}

// Convert input using given vbscript logic and return as output string
static string Convert(string vbscript, string input)
{
    var func = GetFunction(vbscript);
    return func(input);
}

// Create a function from a string of vbscript that can be applied
static Func<string, string> GetFunction(string vbscript)
{
    // generate simple code snippet to evaluate expression
    VBCodeProvider prov = new VBCodeProvider();
    CompilerResults results = prov.CompileAssemblyFromSource(
        new CompilerParameters(new[] { "System.Core.dll" }),
        @"
Imports System
Imports System.Linq.Expressions
Imports Microsoft.VisualBasic

Class MyConverter

Public Shared Function Convert() As Expression(Of Func(Of String, String))
    return Function(x) " + vbscript + @"
End Function

End Class
"
        );

    // make sure no errors occurred in the conversion process
    if (results.Errors.Count == 0)
    {
        // retrieve the newly prepared function by executing the code
        var expr = (Expression<Func<string, string>>)
            results.CompiledAssembly.GetType("MyConverter")
                .GetMethod("Convert").Invoke(null, null);
        Func<string, string> func = expr.Compile();

        // create a compiled function ready to apply and return
        return func;
    }
    else
    {
        return null;
    }
}


来源: stackexchange

问:
Array of JavaScript arrow functions
I'm implementing the card game Hearts in JavaScript, and one of the core elements of the game is that you can pass your cards to other players. My game has strictly 4 players, no more, no less.

The passing order goes left, right, straight ahead, then no passing. Therefore, P1 would pass to P2, P4, P3, and then pass to nobody. The cycle loops until the game is over.

I am trying to implement this logic via arrow functions, however, it is not working. What I am trying to do is print out the player, and the player that they should pass to, based on a given index.

Here is my code, I hope it is clear what I am trying to do.

const players = [1, 2, 3, 4];
const passingOrder = 2;
const passCards = [
  i => (i + 1) % 4, //pass left
  i => (i - 1 + 4) % 4, //pass right
  i => (i + 2) % 4, //pass straight
  i => i //pass to ones self
];

players.forEach((player, index) => {
  console.log(player + "passes to " + passCards[passingOrder](index))
})```

答:
We're going to cheat. Rather than waste time trying to solve this in an overly creative way, we're going to make an object that lays out the association between players and their passing direction. Let's skip the modulus for this one.

Doing things this way also happens to keep our code readable, and is more intuitive at first glance. Notice how we could easily extend this to three dimensions by just adding up and down keys to passingOrder and directions.

Sometimes it pays off to be lazy!

var players = [1, 2, 3, 4];
var passingOrder = ["left", "right", "center"];
var directions = {
  1: {
    left: 2,
    center: 3,
    right: 4
  },
  2: {
    left: 3,
    center: 4,
    right: 1
  },
  3: {
    left: 4,
    center: 1,
    right: 2
  },
  4: {
    left: 1,
    center: 2,
    right: 3
  }
};

players.forEach(
  player => passingOrder.forEach(
    pass => console.log(player, "passes to", directions[player][pass])
  )
);```

ContentLicense: CC BY-SA 4.0

Title: Array of JavaScript arrow functions


问:
When i make request to googleapis, getting 400 Bad Request
I am trying to get the list of groups (distribution lists) for a specific user. It is getting failed.

Request is

```<code>`GET /admin/directory/v1/groups HTTP/1.1
Host: www.googleapis.com
Content-length: 0
Authorization: Bearer ya29.Il-9B-9Z88RKqK73dr-NyeeJnCz0PqlPrMgxlr0JO6gc2q2jcROxsu7y6EaTHAlRkJatv5l3kd_PIPHrB7wXeMvfe0YTXupzupJ8-PUyrRcCIBE_qpPP8V7NoM0JJp`
</code>```

But the I am getting the error response shown below.

```<code>{
    "error": {
        "code": 400,
        "message": "Bad Request",
        "errors": [
            {
                "domain": "global",
                "message": "Bad Request",
                "reason": "badRequest"
            }
        ]
    }
}
</code>```

Not only when getting groups but every API call from googleapis.com is behaving like this.

答:
I had the same error/confusion about usage of some of the google apis.

I'm assuming you're using a service account with domain-wide delegation access rights?

Assuming yes, the issue is that in addition to the service account credentials, you need to set a user that the google credentials will impersonate when making the request.  That is, the domain wide delegation only allows you to act as though you are one of the actual users, on my understanding.

I couldn't see any way to set this via google base api, other than using the builder directly.  Here is a sample:

  static GoogleCredential createCredential(HttpTransport transport, JsonFactory jsonFactory) throws Exception {
    final String credentialJsonPath = System.getProperty("user.home") + "/.config/gcloud/service-cred-from-console.json";
    try (InputStream credentialStream = new FileInputStream(credentialJsonPath)) {
      final GoogleCredential firstPassCred = GoogleCredential.fromStream(credentialStream, transport, jsonFactory);

      return new GoogleCredential.Builder()
          .setTransport(transport)
          .setJsonFactory(jsonFactory)
          .setServiceAccountId(firstPassCred.getServiceAccountId())
          .setServiceAccountProjectId(firstPassCred.getServiceAccountProjectId())
          .setServiceAccountPrivateKey(firstPassCred.getServiceAccountPrivateKey())
          .setServiceAccountPrivateKeyId(firstPassCred.getServiceAccountPrivateKeyId())
          // service accounts must act on behalf of an actual user and have scope
          .setServiceAccountScopes(Lists.newArrayList(GmailScopes.GMAIL_COMPOSE, GmailScopes.GMAIL_SETTINGS_SHARING))
          .setServiceAccountUser("a.real.gsuite.account@example.com")
          .build();
    }
  }
```

The important parts are defining the ServiceAccountUser (who you impersonate) and the ServiceAccountScope(s) you are assuming for that user.

I posted an example gmail api gist.  You could run this through a local proxy like charles (et al) if you want the equiv. REST call sequence.

Body:
I am trying to get the list of groups (distribution lists) for a specific user. It is getting failed.

Request is

`GET /admin/directory/v1/groups HTTP/1.1
Host: www.googleapis.com
Content-length: 0
Authorization: Bearer ya29.Il-9B-9Z88RKqK73dr-NyeeJnCz0PqlPrMgxlr0JO6gc2q2jcROxsu7y6EaTHAlRkJatv5l3kd_PIPHrB7wXeMvfe0YTXupzupJ8-PUyrRcCIBE_qpPP8V7NoM0JJp`

But the I am getting the error response shown below.

{
    "error": {
        "code": 400,
        "message": "Bad Request",
        "errors": [
            {
                "domain": "global",
                "message": "Bad Request",
                "reason": "badRequest"
            }
        ]
    }
}

Not only when getting groups but every API call from googleapis.com is behaving like this.

Body:
I had the same error/confusion about usage of some of the google apis.

I'm assuming you're using a service account with domain-wide delegation access rights?

Assuming yes, the issue is that in addition to the service account credentials, you need to set a user that the google credentials will impersonate when making the request.  That is, the domain wide delegation only allows you to act as though you are one of the actual users, on my understanding.

I couldn't see any way to set this via google base api, other than using the builder directly.  Here is a sample:

  static GoogleCredential createCredential(HttpTransport transport, JsonFactory jsonFactory) throws Exception {
    final String credentialJsonPath = System.getProperty("user.home") + "/.config/gcloud/service-cred-from-console.json";
    try (InputStream credentialStream = new FileInputStream(credentialJsonPath)) {
      final GoogleCredential firstPassCred = GoogleCredential.fromStream(credentialStream, transport, jsonFactory);

      return new GoogleCredential.Builder()
          .setTransport(transport)
          .setJsonFactory(jsonFactory)
          .setServiceAccountId(firstPassCred.getServiceAccountId())
          .setServiceAccountProjectId(firstPassCred.getServiceAccountProjectId())
          .setServiceAccountPrivateKey(firstPassCred.getServiceAccountPrivateKey())
          .setServiceAccountPrivateKeyId(firstPassCred.getServiceAccountPrivateKeyId())
          // service accounts must act on behalf of an actual user and have scope
          .setServiceAccountScopes(Lists.newArrayList(GmailScopes.GMAIL_COMPOSE, GmailScopes.GMAIL_SETTINGS_SHARING))
          .setServiceAccountUser("a.real.gsuite.account@example.com")
          .build();
    }
  }

The important parts are defining the ServiceAccountUser (who you impersonate) and the ServiceAccountScope(s) you are assuming for that user.

I posted an example gmail api gist.  You could run this through a local proxy like charles (et al) if you want the equiv. REST call sequence.


问:
Django RF - How to insert into pivot table using name instead of id without querying the id?
For example I have the ff:

models:

```<code>class Store(models.Model):
    name = models.CharField(max_length = 20)

class Product(models.Model):
    name = models.CharField(max_length = 20)

class StoreProducts(models.Model):
    store = models.ForeignKey(Store)
    product = models.ForeignKey(Product)
    qty = models.IntegerField()
</code>```

serializer:

```<code>class StoreProductsSerializer(serializers.ModelSerializer):
    class Meta:
        model = StoreProducts
        fields = ('store', 'product', 'qty')
</code>```

And defined values:

```<code>Store (id, name):
 1, store_1
 2, store_2

Product (id, name):
 1, product_1
 2, product_2
</code>```

Now in the views, I want to add into the StoreProducts from post request without querying the ids of Store and Product like this:

```<code>data = {
'store': 'store_1',
'product': 'product_1',
'qty': 1
}

serializer = StoreProductsSerializer(data=data)
    if serializer.is_valid():
        serializer.save()
</code>```

Is this possible and how? Thanks

答:
You can take value that you want and in validate method you can change it with object. But you must use unique field for this method.I'm not sure whether it is a good way There is a sample:</p>

```<code>class StoreProductsSerializer(serializers.ModelSerializer):
    class Meta:
        model = StoreProducts
        fields = ('store', 'product', 'qty')

    def validate(self, attrs):
        attrs['product'] = Product.objects.get(name=attrs['product'])
        attrs['store'] = Store.objects.get(name=attrs['store'])
        return attrs
</code>```

Body:
For example I have the ff:

models:

class Store(models.Model):
    name = models.CharField(max_length = 20)

class Product(models.Model):
    name = models.CharField(max_length = 20)

class StoreProducts(models.Model):
    store = models.ForeignKey(Store)
    product = models.ForeignKey(Product)
    qty = models.IntegerField()

serializer:

class StoreProductsSerializer(serializers.ModelSerializer):
    class Meta:
        model = StoreProducts
        fields = ('store', 'product', 'qty')

And defined values:

Store (id, name):
 1, store_1
 2, store_2

Product (id, name):
 1, product_1
 2, product_2

Now in the views, I want to add into the StoreProducts from post request without querying the ids of Store and Product like this:

data = {
'store': 'store_1',
'product': 'product_1',
'qty': 1
}

serializer = StoreProductsSerializer(data=data)
    if serializer.is_valid():
        serializer.save()

Is this possible and how? Thanks

Body:
You can take value that you want and in validate method you can change it with object. But you must use unique field for this method.I'm not sure whether it is a good way There is a sample:

class StoreProductsSerializer(serializers.ModelSerializer):
    class Meta:
        model = StoreProducts
        fields = ('store', 'product', 'qty')

    def validate(self, attrs):
        attrs['product'] = Product.objects.get(name=attrs['product'])
        attrs['store'] = Store.objects.get(name=attrs['store'])
        return attrs


问:
What did I install (NPM)?
I was trying to install forever with the package manager NPM.

I ran the following code:

```<code>sudo npm install foever -g
</code>```

I misspelled "forever" obviously, but it did something. It said:

foever@0.0.1-security
  updated 1 package in 0.163s

I can't find any info on foever. Does anyone have any idea what this did to my system?

答:
Technically, you installed the foever package.

The original foever package was probably a malicious package used to typosquat the forever package. NPM recognized this, removed the malicious package, and placed an empty package there instead to prevent future (malicious) usage of this name.

Title: What did I install (NPM)?

Body:
I was trying to install forever with the package manager NPM.

I ran the following code:

sudo npm install foever -g

I misspelled "forever" obviously, but it did something. It said:

foever@0.0.1-security
  updated 1 package in 0.163s

I can't find any info on foever. Does anyone have any idea what this did to my system?


问:
Tools for static type checking in Python
I'm working with a large existing Python codebase and would like to start adding in type annotations so I can get some level of static checking.  I'm imagining something like Erlang, Strongtalk, or Typed Scheme/Racket.

I've seen quick-and-dirty decorators that insert dynamic checks based on function parameter and return type annotations, but I'm looking for something that is more robust and that performs checks at compile-time.

What tools are available right now for this kind of thing?  I'm familiar with compilers and type checking and am definitely willing to improve an incomplete tool if it has a good foundation.

(Note: I'm not interested in a discussion of the pros/cons of static typing.)

EDIT: An example:

```<code>def put(d, k, v):
   d[k] = v
</code>```

I'd like to be able to annotate the put function as having type put<K,V>(dict<K,V>, K, V) -> None.

UPDATE: The new PEP 484 (Sep 2014) defines a standard for static typing and type annotations in Python 3.5+.  There's a type-checking tool called mypy that is compatible with PEP 484.

答:
Edit 2016-11-11: Just use mypy. Type hints can be added gradually. In Python 3 source code, it verifies standard PEP 484 type hints. Types can still be expressed in Python 2 using special comments. Guido likes it.

This post was originally written a long time ago before mypy was a thing. I've preserved the post's original content below, even though it isn't quite accurate.

Original post:

You might want to check out some of the projects mentioned in this related StackOverflow post on static analysis for Python.

In summary:

pylint

PyFlakes

PyChecker

Since Python uses duck typing extensively, things that might be called "type errors" in other languages might end up being "object X doesn't support method Y" in Python.

Edit 2011-05-17:

I agree with delnan that static typing is not possible for Python [apparently wrong].  But since our skepticism doesn't seem to deter you, I can only give you more information on the subject.  I present:

A discussion of type inference for Python.  (Other links are from here.)

Guido van van Rossum's articles on adding optional static typing: part 1 and part 2.

RPython, a subset of Python that might stand a chance of being statically analyzed enough to do some form of type checking.

ContentLicense: CC BY-SA 3.0

Body:
I'm working with a large existing Python codebase and would like to start adding in type annotations so I can get some level of static checking.  I'm imagining something like Erlang, Strongtalk, or Typed Scheme/Racket.

I've seen quick-and-dirty decorators that insert dynamic checks based on function parameter and return type annotations, but I'm looking for something that is more robust and that performs checks at compile-time.

What tools are available right now for this kind of thing?  I'm familiar with compilers and type checking and am definitely willing to improve an incomplete tool if it has a good foundation.

(Note: I'm not interested in a discussion of the pros/cons of static typing.)

EDIT: An example:

def put(d, k, v):
   d[k] = v

I'd like to be able to annotate the put function as having type put<K,V>(dict<K,V>, K, V) -> None.

UPDATE: The new PEP 484 (Sep 2014) defines a standard for static typing and type annotations in Python 3.5+.  There's a type-checking tool called mypy that is compatible with PEP 484.


问:
Django Rss Feed add image to description
I am trying to use Django rss feeds to view feeds on rss viewer app.

i used from django.contrib.syndication.views import Feed to create rss feeds

but it only had 3 fields title, description and link
i added custom fields by using from django.utils.feedgenerator import Rss201rev2Feed

and it generates the extra fields with no issues

but when i open it with a rss viewer it doesn't show those extra fields or the image

My question is how can i make those extra fields show up in app ?

does it not show up because app only shows title, description and link and those other fields are not processed ?

so how can i embed image and other fields in description so it shows up (most importantly image show up) ?

i have went over documentation many times can't seem to get it right.

here is the view code from Django app

```<code>class CustomFeedGenerator(Rss201rev2Feed):
    def add_item_elements(self, handler, item):
        super(CustomFeedGenerator, self).add_item_elements(handler, item)
        handler.addQuickElement(u"image", item['image'])
        handler.addQuickElement(u"seller_name", item['seller_name'])
        handler.addQuickElement(u"price", item['price'])

class LatestPostsFeed(Feed):
    title = "www.marktplaats.nl"
    link = "/feeds/"
    description = "Updates on changes and additions to posts published in the starter."

    feed_type = CustomFeedGenerator

    def items(self):
        return Check_Ads_One.objects.order_by('title')[:5]

    def item_title(self, item):
        return item.title

    def item_description(self, item):
        return item.paragraph

    def item_link(self, item):
        return item.prod_link

    def item_extra_kwargs(self, item):

        return { 'image': item.image_link,
                'seller_name' : item.seller_name,
                'price': item.price,}
</code>```

I'm using Rss Savvy for the reader app

答:
<image></image> is not a standard element of Items as per RSS Specification stated here. But it is a valid element of channel. Anyway, there are several ways you can add image to feed. Like:

Using enclosures

As stated here, you can use enclosures to add image in feed. Django Feed Framework also provides add_enclosures() function which we can use. Here are two possible solutions based on that:

First Solution (Image Stored in Django)

I am assuming you have an image field in the model like this:

```<code>class Check_Ads_One(models.Model):
   image = models.ImageField()
</code>```

Then update the LatestPostsFeed class like this:

```<code>class LatestPostsFeed(Feed):
    title = "www.marktplaats.nl"
    link = "/feeds/"
    description = "Updates on changes and additions to posts published in the starter."

    feed_type = feedgenerator.Rss201rev2Feed

    # Rest of the code

    def get_object(self, request, *args, **kwargs):
        self.request = request
        return super(LatestPostsFeed, self).get_object(request, *args, **kwargs)

    def get_image_url(self, url):
        return self.request.build_absolute_uri('/media{}'.format(url))

    def item_enclosures(self, item):
        return [feedgenerator.Enclosure(self.get_image_url(item.image.url), str(item.image.size), 'image/{}'.format(item.image.name.split('.')[-1]))]

</code>```

Second Solution (Image not Stored in Django)

If you are storing the links of image instead of actual image, then use the following approach:

```<code>import urllib

class LatestPostsFeed(Feed):
    title = "www.marktplaats.nl"
    link = "/feeds/"
    description = "Updates on changes and additions to posts published in the starter."

    feed_type = feedgenerator.Rss201rev2Feed

    # Rest of the code

    def get_size_and_type_of_image(self, image_url):
       # This method can be moved to models.py, and on save of `Check_Ads_One` it will calculate the size and type of image from url and store in DB. Then it will much optimized solution
       data = urllib.urlopen(image_url)
       return data['Content-Length'], data['Content-Type']

    def item_enclosures(self, item):
        content_length, content_type = self.get_size_and_type_of_image(item.image)
        return [feedgenerator.Enclosure(item.image, content_length, content_type)]
</code>```

Image information in CDATA(alternative solution)

You can add CDATA tag in description and add image there:

```<code>def item_description(self, item):
    return '<![CDATA[\n{} <img src="{}" alt="{}">\n]>'.format(item.paragraph, item.image, item.title)
</code>```

More information can be found in this StackOverflow Answer

Body:
I am trying to use Django rss feeds to view feeds on rss viewer app.

i used from django.contrib.syndication.views import Feed to create rss feeds

but it only had 3 fields title, description and link
i added custom fields by using from django.utils.feedgenerator import Rss201rev2Feed

and it generates the extra fields with no issues

but when i open it with a rss viewer it doesn't show those extra fields or the image

My question is how can i make those extra fields show up in app ?

does it not show up because app only shows title, description and link and those other fields are not processed ?

so how can i embed image and other fields in description so it shows up (most importantly image show up) ?

i have went over documentation many times can't seem to get it right.

here is the view code from Django app

class CustomFeedGenerator(Rss201rev2Feed):
    def add_item_elements(self, handler, item):
        super(CustomFeedGenerator, self).add_item_elements(handler, item)
        handler.addQuickElement(u"image", item['image'])
        handler.addQuickElement(u"seller_name", item['seller_name'])
        handler.addQuickElement(u"price", item['price'])

class LatestPostsFeed(Feed):
    title = "www.marktplaats.nl"
    link = "/feeds/"
    description = "Updates on changes and additions to posts published in the starter."

    feed_type = CustomFeedGenerator

    def items(self):
        return Check_Ads_One.objects.order_by('title')[:5]

    def item_title(self, item):
        return item.title

    def item_description(self, item):
        return item.paragraph

    def item_link(self, item):
        return item.prod_link

    def item_extra_kwargs(self, item):

        return { 'image': item.image_link,
                'seller_name' : item.seller_name,
                'price': item.price,}

I'm using Rss Savvy for the reader app

Body:
<image></image> is not a standard element of Items as per RSS Specification stated here. But it is a valid element of channel. Anyway, there are several ways you can add image to feed. Like:

Using enclosures

As stated here, you can use enclosures to add image in feed. Django Feed Framework also provides add_enclosures() function which we can use. Here are two possible solutions based on that:

First Solution (Image Stored in Django)

I am assuming you have an image field in the model like this:

class Check_Ads_One(models.Model):
   image = models.ImageField()

Then update the LatestPostsFeed class like this:

class LatestPostsFeed(Feed):
    title = "www.marktplaats.nl"
    link = "/feeds/"
    description = "Updates on changes and additions to posts published in the starter."

    feed_type = feedgenerator.Rss201rev2Feed

    # Rest of the code

    def get_object(self, request, *args, **kwargs):
        self.request = request
        return super(LatestPostsFeed, self).get_object(request, *args, **kwargs)

    def get_image_url(self, url):
        return self.request.build_absolute_uri('/media{}'.format(url))

    def item_enclosures(self, item):
        return [feedgenerator.Enclosure(self.get_image_url(item.image.url), str(item.image.size), 'image/{}'.format(item.image.name.split('.')[-1]))]

Second Solution (Image not Stored in Django)

If you are storing the links of image instead of actual image, then use the following approach:

import urllib

class LatestPostsFeed(Feed):
    title = "www.marktplaats.nl"
    link = "/feeds/"
    description = "Updates on changes and additions to posts published in the starter."

    feed_type = feedgenerator.Rss201rev2Feed

    # Rest of the code

    def get_size_and_type_of_image(self, image_url):
       # This method can be moved to models.py, and on save of `Check_Ads_One` it will calculate the size and type of image from url and store in DB. Then it will much optimized solution
       data = urllib.urlopen(image_url)
       return data['Content-Length'], data['Content-Type']

    def item_enclosures(self, item):
        content_length, content_type = self.get_size_and_type_of_image(item.image)
        return [feedgenerator.Enclosure(item.image, content_length, content_type)]

Image information in CDATA(alternative solution)

You can add CDATA tag in description and add image there:

def item_description(self, item):
    return '<![CDATA[\n{} <img src="{}" alt="{}">\n]>'.format(item.paragraph, item.image, item.title)

More information can be found in this StackOverflow Answer


问:
Fixed element positioning at the bottom of the viewport - without resorting to position:fixed (pure CSS solution)
I'm using position:fixed to fix a navbar at the bottom of the page in one of my mobile web projects.

However, browser-support for position:fixed is sometimes non-existent (e.g. Opera Mini), and thus my navbar breaks down for a small, yet un-ignorable % of users of the said web app.

Is there a pure CSS way to achieve the same effect in some other way? E.g. flexbox and z-index (or something)? It'll be best if it relies on properties well-supported across all browsers.

To be exact: I'm not looking for a sticky footer that sticks to the bottom when the page content is sparse, and otherwise pushes down. I'm looking for a way to fix something to the page's bottom, and allow the content to scroll "underneath it".

There are several answers for a question like mine on SO and other places. But they mostly fall back to position:fixed (or JS). I want neither. So are there any other solutions available? Would love to see an illustrative example from industry experts. Thanks in advance.

答:
Ok, this is very basic, but you could try something like this:</p>

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
        }

        header, footer {
            background-color: blue;
            height: 80px;
        }

        section {
            height: calc(100% - 160px);
            display: flex;
            flex-direction: column;
            justify-content: space-around;
            overflow-y: auto;
        }
    </style>
</head>
<body>
    <header></header>
    <section></section>
    <footer></footer>
</body>
</html>
</code>```

Body:
Ok, this is very basic, but you could try something like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
        }

        header, footer {
            background-color: blue;
            height: 80px;
        }

        section {
            height: calc(100% - 160px);
            display: flex;
            flex-direction: column;
            justify-content: space-around;
            overflow-y: auto;
        }
    </style>
</head>
<body>
    <header></header>
    <section></section>
    <footer></footer>
</body>
</html>


问:
Python - Count spaces, not blank lines
Is there a way to compress a text file and remove the blank lines in order for me to count the spaces in the text? I have a text file of about 20 lines and I want to count the spaces between the words. But I thin I count the white lines as well since i get over 800 in the counter.

```<code>def spaces():
"""
Counting spaces
"""

number_of_spaces = 0

with open(TEXT, "r") as fh:
    for line in fh:
        space = line.split()
        for i in space:
            for char in i:
                if char.isspace():
                    number_of_spaces += 1

return number_of_spaces
</code>```

Regards

答:
This Below code counts the number of blank spaces and also the number of lines separately.
Hope this helps.</p>

```<code>import re
count = 0
fname = input("Enter file name: ")

with open(fname,'r') as f:       #This counts the blank space
    print("Number of space: ", len(re.findall(r' ', f.read())))

with open(fname, 'r') as f:      #This counts the number of lines
    for line in f:
        count += 1
print("Total number of lines is:", (count - 1))
</code>```

Title: Python - Count spaces, not blank lines

Body:
Is there a way to compress a text file and remove the blank lines in order for me to count the spaces in the text? I have a text file of about 20 lines and I want to count the spaces between the words. But I thin I count the white lines as well since i get over 800 in the counter.

def spaces():
"""
Counting spaces
"""

number_of_spaces = 0

with open(TEXT, "r") as fh:
    for line in fh:
        space = line.split()
        for i in space:
            for char in i:
                if char.isspace():
                    number_of_spaces += 1

return number_of_spaces

Regards

Body:
This Below code counts the number of blank spaces and also the number of lines separately.
Hope this helps.

import re
count = 0
fname = input("Enter file name: ")

with open(fname,'r') as f:       #This counts the blank space
    print("Number of space: ", len(re.findall(r' ', f.read())))

with open(fname, 'r') as f:      #This counts the number of lines
    for line in f:
        count += 1
print("Total number of lines is:", (count - 1))


问:
How can I use bsub to consider two sets of inputs for my code
I use the following shell script to send jobs to the server:

```<code>#!/bin/bash
#BSUB -J randJobName_ul0vm[1-3]%22
#BSUB -oo <pathToLog>/log/randJobName_ul0vm.o.%J.%I
#BSUB -q "server.q"
#BSUB -n 2
#BSUB -R "span[hosts=1]"

JOB_ID=$LSB_JOBID
SGE_TASK_ID=$LSB_JOBINDEX
JOB_NAME=$LSB_JOBNAME
Id=$((SGE_TASK_ID-1))
declare -a Input
Input[0]="input1 input2"
Input[1]="input3 input4"
Input[2]="input5 input6"

python pythoncode.py parameter1 ${Input[${Id}]}
</code>```

So, it gives the following inputs to the pthoncode.py:

```<code>parameter1 input1 input2
parameter1 input3 input4
parameter1 input5 input6
</code>```

How can I modify it so that it also gives the following inputs?

```<code>parameter2 input1 input2
parameter2 input3 input4
parameter2 input5 input6
</code>```

Note that parameter1 is replaced with parameter2 here.

I used the following code but it says index out of range. I don't understand why:

```<code>#!/bin/bash
#BSUB -J randJobName_ul0vm[1-6]%22
#BSUB -oo <pathToLog>/log/randJobName_ul0vm.o.%J.%I
#BSUB -q "server.q"
#BSUB -n 2
#BSUB -R "span[hosts=1]"

JOB_ID=$LSB_JOBID
SGE_TASK_ID=$LSB_JOBINDEX
JOB_NAME=$LSB_JOBNAME
Id=$((SGE_TASK_ID-1))
declare -a Input
Input[0]="input1 input2"
Input[1]="input3 input4"
Input[2]="input5 input6"

python pythoncode.py parameter1 ${Input[${Id}]}
python pythoncode.py parameter2 ${Input[${Id}]}
</code>```

答:
According to this randJobName why don't you just use RANDOM?

```<code>parameter="parameter$((1+RANDOM%2))"
</code>```

And in input

```<code>input=${Input[$((RANDOM%2))]}
</code>```

Body:
I use the following shell script to send jobs to the server:

#!/bin/bash
#BSUB -J randJobName_ul0vm[1-3]%22
#BSUB -oo <pathToLog>/log/randJobName_ul0vm.o.%J.%I
#BSUB -q "server.q"
#BSUB -n 2
#BSUB -R "span[hosts=1]"

JOB_ID=$LSB_JOBID
SGE_TASK_ID=$LSB_JOBINDEX
JOB_NAME=$LSB_JOBNAME
Id=$((SGE_TASK_ID-1))
declare -a Input
Input[0]="input1 input2"
Input[1]="input3 input4"
Input[2]="input5 input6"

python pythoncode.py parameter1 ${Input[${Id}]}

So, it gives the following inputs to the pthoncode.py:

parameter1 input1 input2
parameter1 input3 input4
parameter1 input5 input6

How can I modify it so that it also gives the following inputs?

parameter2 input1 input2
parameter2 input3 input4
parameter2 input5 input6

Note that parameter1 is replaced with parameter2 here.

I used the following code but it says index out of range. I don't understand why:

#!/bin/bash
#BSUB -J randJobName_ul0vm[1-6]%22
#BSUB -oo <pathToLog>/log/randJobName_ul0vm.o.%J.%I
#BSUB -q "server.q"
#BSUB -n 2
#BSUB -R "span[hosts=1]"

JOB_ID=$LSB_JOBID
SGE_TASK_ID=$LSB_JOBINDEX
JOB_NAME=$LSB_JOBNAME
Id=$((SGE_TASK_ID-1))
declare -a Input
Input[0]="input1 input2"
Input[1]="input3 input4"
Input[2]="input5 input6"

python pythoncode.py parameter1 ${Input[${Id}]}
python pythoncode.py parameter2 ${Input[${Id}]}

Body:
According to this randJobName why don't you just use RANDOM?

parameter="parameter$((1+RANDOM%2))"

And in input

input=${Input[$((RANDOM%2))]}


问:
Get rid of override reason for TFS
I'd like to get rid of an override reason for some code that I've been working on, where previous shelvesets I made from it required an override reason to deal with checkin policy warnings, but where the current version does not.

However, while I can see in Team Explorer the field for override reason when my code violates checkin policy, I can't see the field when it doesn't violate the policy.

Short of deliberately making my code violate checkin policy, how can I empty out the override reason?

答:
The shelveset saves and stores not only your file revisions, but also the Comment, the list of Related Work Items, and check-in notes (if you evaluate policies before shelving).

Select either of the following check boxes:

Preserve pending change locally : By default, this check box is selected. When this check box is selected, your pending changes
(including the comment and the Related Work Items list) are not
removed from your workspace. If you want to clean your workspace to
work on another task, you should clear this check box.

Evaluate Policies and check-in notes before shelving: When you select this check box, all check-in policies are evaluated before the
shelveset is created.

So you could uncheck Evaluate Policies and check-in notes before shelving when you are trying to unshelve. This will not keep any override reason in Team Explore.

If there is any override reason cached in Team Explore. Just manually delete them.

According to your situation, since you are working on multiple shelvesets and not check in pending changes frequently.

Since check in policy will only validate when you are trying to check in pending changes. There is no need to Evaluate Policies and check-in notes for all shelvesets each time. Which may make things complicated and confused.

The best way is unchecking this option during the shelve. And make sure you do not
violate  the policy after finally check in option.

Hope this is clearly and helpful.

Title: Get rid of override reason for TFS


答:
```<code><?php
$data = file_get_contents('test.json');
$data =json_decode($data,TRUE);
 $dataA= array();
foreach($data as $singleArray){
array_push($dataA, $singleArray['Line']);

}
$arrayChunks= array_chunk($dataA, 3);

?>
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<table>
    <thead>
        <th>Names</th>
        <th>Department</th>

    </thead>
    <tbody>
       <?php
            foreach($arrayChunks as $array){
                if(empty($array[0]) || empty($array[1]) || empty($array[2]))continue;
       ?>
        <tr>
            <td><?php echo $array[1]; ?></td>
            <td><?php echo $array[2]; ?></td>

        </tr>
        <?php
        }

        ?>
    </tbody>
</table>

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

Hi Its exactly what you are looking. try to check this and setup output as you need. Its just idea you can surely improve your problem using this. Thanks

Title: How to print a table by given row index and column index put the Line value in table Column value in json data in php

Body:
i am trying to print a table from json data which contain row index and column index my array is given below

[{"ID":["64103487-ab83-4ce2-ba22-e4c83184eeda"],"RowIndex":1,"ColumnIndex":1,"Line":""},{"ID":["a38cb3ca-9565-463c-830d-f686cb2a965e"],"RowIndex":1,"ColumnIndex":2,"Line":""},{"ID":["73863297-6182-4c24-a5cc-13a20f8b9b97"],"RowIndex":1,"ColumnIndex":3,"Line":"Department"},{"ID":["6c87f8d1-e7b5-49e6-8d45-049532177b0e"],"RowIndex":2,"ColumnIndex":1,"Line":""},{"ID":["ef36343e-e89a-4671-9672-310fdd451111","5e210db5-979e-4b88-9ac1-8d7d3776569c"],"RowIndex":2,"ColumnIndex":2,"Line":""},{"ID":["301021a5-9a2b-4147-85f1-def1b91c0543"],"RowIndex":2,"ColumnIndex":3,"Line":"Sales"},{"ID":["503339ef-2892-460d-9638-d08a6ebeaf5a"],"RowIndex":3,"ColumnIndex":1,"Line":"3"},{"ID":["8fff1706-8091-4ee4-9515-627e68758109","98d44dc1-a620-4de9-9eb0-4af878a46b6f"],"RowIndex":3,"ColumnIndex":2,"Line":"Justin Shore"},{"ID":["07172dfe-2037-4355-87c8-03fef616634c"],"RowIndex":3,"ColumnIndex":3,"Line":"Marketing"},{"ID":["c88a583d-f5c8-48fb-aaa8-8a1bda6bf1d5"],"RowIndex":4,"ColumnIndex":1,"Line":"4"},{"ID":["30696ecb-aabc-4735-bdf8-47f864260e26","4179cd2e-8132-4baa-afec-41d4b33870a3"],"RowIndex":4,"ColumnIndex":2,"Line":"Lexi Barringer"},{"ID":["a67c9508-7731-4953-b88e-df7dd58c6c34"],"RowIndex":4,"ColumnIndex":3,"Line":"Finance"},{"ID":["153f68af-a9aa-49a9-ab26-ad9f89e21ecc"],"RowIndex":5,"ColumnIndex":1,"Line":"5"},{"ID":["0916eb3e-e8e0-43fd-a424-bada4c95080b","66dd35de-f4d7-48e3-bb4a-a42e158c28c7"],"RowIndex":5,"ColumnIndex":2,"Line":"Safa thsan"},{"ID":["2aa280ff-b527-4b4b-9ca5-3538a3fcbb98"],"RowIndex":5,"ColumnIndex":3,"Line":"Sales"},{"ID":["3d9af0ca-e0e8-4747-bfc7-85273a053a0f"],"RowIndex":6,"ColumnIndex":1,"Line":"6"},{"ID":["99314a19-0377-416d-bc25-6efcf4943abb","d001dfb2-d51c-460d-bbd7-d2340695dddb"],"RowIndex":6,"ColumnIndex":2,"Line":"Roy Flint"},{"ID":["66201bf3-aa64-4761-a291-040310b1b5cb"],"RowIndex":6,"ColumnIndex":3,"Line":"Finance"}]

and i want to ouput like the image given below

enter image description here

Body:
<?php
$data = file_get_contents('test.json');
$data =json_decode($data,TRUE);
 $dataA= array();
foreach($data as $singleArray){
array_push($dataA, $singleArray['Line']);

}
$arrayChunks= array_chunk($dataA, 3);

?>
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<table>
    <thead>
        <th>Names</th>
        <th>Department</th>

    </thead>
    <tbody>
       <?php
            foreach($arrayChunks as $array){
                if(empty($array[0]) || empty($array[1]) || empty($array[2]))continue;
       ?>
        <tr>
            <td><?php echo $array[1]; ?></td>
            <td><?php echo $array[2]; ?></td>

        </tr>
        <?php
        }

        ?>
    </tbody>
</table>

</body>
</html>

Hi Its exactly what you are looking. try to check this and setup output as you need. Its just idea you can surely improve your problem using this. Thanks


问:
How to mask string after first character
Let's say I have a string that consists of a person's name:

```<code>var name = "Jason, Bruno Mars";
</code>```

How do I mask the string with X for the name behind the comma and returns:

```<code>var name = "Jason, BXXXX MXXX";
</code>```

I have tried using the following methods but only front characters are masked:

```<code>string first, second, output;
bool hasSpace, hasComma;
int int_LENGTH;
var name = "Jason, Bruno Mars";
hasComma = name.Contains(",");

if (hasComma == true)
{
    int_LENGTH = name.IndexOf(",");
    if (int_LENGTH > 0)
    {
        first = name.Substring(0, int_LENGTH);
    }

    second = string.Join(",", name.Split(" ").Skip(1));
    hasSpace = second.Contains(" ");

    if (hasSpace == true)
    {
        second = string.Concat(new string('X', 12), second.Substring(second.Length - 4));
        output = first + "," + second;
    }
}
</code>```

Anyone has a better idea of how can I achieve the same result in a more efficient way?

答:
Efficient way of masking without Split, Regex, and using System.Linq:

For C# version < 7.2:

```<code>static string MaskName(string name)
{
    int indexOfComma = name.IndexOf(',');

    if (indexOfComma != -1)
    {
        char[] temp = name.ToCharArray();

        bool isFirstChar = true;

        for (int i = indexOfComma + 1; i < temp.Length; i++)
        {
            if (temp[i] == ' ')
                isFirstChar = true;
            else if (isFirstChar)
                isFirstChar = false;
            else
                temp[i] = 'X';
        }

        return new string(temp);
    }
    else
    {
        return name;
    }
}
</code>```

For C# version >= 7.2:

```<code>static string MaskName(ReadOnlySpan<char> name)
{
    int indexOfComma = name.IndexOf(',');

    if (indexOfComma != -1)
    {
        Span<char> temp = stackalloc char[name.Length];

        name.CopyTo(temp);

        bool isFirstChar = true;

        for (int i = indexOfComma + 1; i < temp.Length; i++)
        {
            if (temp[i] == ' ')
                isFirstChar = true;
            else if (isFirstChar)
                isFirstChar = false;
            else
                temp[i] = 'X';
        }

        return new string(temp);
    }
    else
    {
        return name.ToString();
    }
}
</code>```

Body:
Let's say I have a string that consists of a person's name:

var name = "Jason, Bruno Mars";

How do I mask the string with X for the name behind the comma and returns:

var name = "Jason, BXXXX MXXX";

I have tried using the following methods but only front characters are masked:

string first, second, output;
bool hasSpace, hasComma;
int int_LENGTH;
var name = "Jason, Bruno Mars";
hasComma = name.Contains(",");

if (hasComma == true)
{
    int_LENGTH = name.IndexOf(",");
    if (int_LENGTH > 0)
    {
        first = name.Substring(0, int_LENGTH);
    }

    second = string.Join(",", name.Split(" ").Skip(1));
    hasSpace = second.Contains(" ");

    if (hasSpace == true)
    {
        second = string.Concat(new string('X', 12), second.Substring(second.Length - 4));
        output = first + "," + second;
    }
}

Anyone has a better idea of how can I achieve the same result in a more efficient way?

Body:
Efficient way of masking without Split, Regex, and using System.Linq:

For C# version < 7.2:

static string MaskName(string name)
{
    int indexOfComma = name.IndexOf(',');

    if (indexOfComma != -1)
    {
        char[] temp = name.ToCharArray();

        bool isFirstChar = true;

        for (int i = indexOfComma + 1; i < temp.Length; i++)
        {
            if (temp[i] == ' ')
                isFirstChar = true;
            else if (isFirstChar)
                isFirstChar = false;
            else
                temp[i] = 'X';
        }

        return new string(temp);
    }
    else
    {
        return name;
    }
}

For C# version >= 7.2:

static string MaskName(ReadOnlySpan<char> name)
{
    int indexOfComma = name.IndexOf(',');

    if (indexOfComma != -1)
    {
        Span<char> temp = stackalloc char[name.Length];

        name.CopyTo(temp);

        bool isFirstChar = true;

        for (int i = indexOfComma + 1; i < temp.Length; i++)
        {
            if (temp[i] == ' ')
                isFirstChar = true;
            else if (isFirstChar)
                isFirstChar = false;
            else
                temp[i] = 'X';
        }

        return new string(temp);
    }
    else
    {
        return name.ToString();
    }
}


问:
Routine when starting boost::asio::io_service
I want to create an http client using boost asio. To have a structured and optimized I have  looked into the examples of boost asio to have some idea of what a good implementation should look like.

Mostly, I have followed the structure of HTTP Server, so I have a connection manager that holds a set of pointers to each individual connection. Now, the big difference here is that already in the constructor of server.cpp an asynchronous function is called, namely

```
acceptor_.async_accept(new_connection_->socket(),
      boost::bind(&server::handle_accept, this,
        boost::asio::placeholders::error));
```

and in the winmain.cpp the io_service is started through a function call to server::run():

```
io_service_.run();
```

In my implementation, since it's a client and not a server, I want to wait for the user to call a send() function before I start connecting to the server. I have therefore moved all connecting-to-server-related function calls into the connection class. When a user requests to send a msg to the server the following is called:

```
resolver.async_resolve(query,
                                   boost::bind(&connection::handle_resolve, boost::ref(*this),
                                               boost::asio::placeholders::error,
                                               boost::asio::placeholders::iterator));
io_service_.run();
```

I want to start every connection-object in one separate thread and this is really the background of my question. How do I do that in order to have a structured and optimized code?

I have tried, as HTTP Server 2 example, to set up a thread pool of io_services and assigning work to them so that they will not return until stopped. This seems like a good idea since I would the have the io services running in the background all the time. Consequently, I start the thread pool from my equivalent to server.cpp, in a thread:

```
boost::thread t(boost::bind(&geocast::enabler::io_service_pool::run, &io_service_pool_));
```

BUT, from my own trial and error analysis, it seems as you cannot start io_service BEFORE you have issued an asynchronous function, is that true? Because my program gets stuck. In my case I want to call async_resolve only when a user means to sends a POST request or a GET request. To support my theory; The Chat Client starts off by calling an async_connect and having an async_read as callback, this way they can safely call io_service.run() just after the client has been created. I don't want to read from the server all the time just to be able to start the io_service, because that is not how a normal client works, right? A browser does not read from every possible server on the planet without the user having navigated to a website...

If I don't use the thread pool from example 2 but start every connection-class in a separate class, each of which own its own io_service, everything works fine. But, a thread pool with a simple round-robin routine to select an appropriate io_service seems really attractive. What is the best approach for me to go multi-threaded? Am I just picky and should stick to one-connection-one-io_service-thing?

答:
When using ASIO, you are giving up control of the flow of your program over to ASIO. You can share control if you change your code to use a thread pool and call run_one() instead of run(). run_one() only dispatches one IO job to a thread, so if you have multiple events in the ioservice, you will have to call run_one() several times.

Have you thought about spawning a new thread as your boss thread and then having your boss thread create a bunch of worker threads? Your boss thread could call run() and then your UI's thread could call post() to dispatch a new unit of work. Along with not having to manually call and schedule tasks in the ioservice, it also makes the cleanup and shutdown more straight forward since your boss thread would block when it calls run().

Body:
I want to create an http client using boost asio. To have a structured and optimized I have  looked into the examples of boost asio to have some idea of what a good implementation should look like.

Mostly, I have followed the structure of HTTP Server, so I have a connection manager that holds a set of pointers to each individual connection. Now, the big difference here is that already in the constructor of server.cpp an asynchronous function is called, namely

acceptor_.async_accept(new_connection_->socket(),
      boost::bind(&server::handle_accept, this,
        boost::asio::placeholders::error));

and in the winmain.cpp the io_service is started through a function call to server::run():

io_service_.run();

In my implementation, since it's a client and not a server, I want to wait for the user to call a send() function before I start connecting to the server. I have therefore moved all connecting-to-server-related function calls into the connection class. When a user requests to send a msg to the server the following is called:

resolver.async_resolve(query,
                                   boost::bind(&connection::handle_resolve, boost::ref(*this),
                                               boost::asio::placeholders::error,
                                               boost::asio::placeholders::iterator));
io_service_.run();

I want to start every connection-object in one separate thread and this is really the background of my question. How do I do that in order to have a structured and optimized code?

I have tried, as HTTP Server 2 example, to set up a thread pool of io_services and assigning work to them so that they will not return until stopped. This seems like a good idea since I would the have the io services running in the background all the time. Consequently, I start the thread pool from my equivalent to server.cpp, in a thread:

boost::thread t(boost::bind(&geocast::enabler::io_service_pool::run, &io_service_pool_));

BUT, from my own trial and error analysis, it seems as you cannot start io_service BEFORE you have issued an asynchronous function, is that true? Because my program gets stuck. In my case I want to call async_resolve only when a user means to sends a POST request or a GET request. To support my theory; The Chat Client starts off by calling an async_connect and having an async_read as callback, this way they can safely call io_service.run() just after the client has been created. I don't want to read from the server all the time just to be able to start the io_service, because that is not how a normal client works, right? A browser does not read from every possible server on the planet without the user having navigated to a website...

If I don't use the thread pool from example 2 but start every connection-class in a separate class, each of which own its own io_service, everything works fine. But, a thread pool with a simple round-robin routine to select an appropriate io_service seems really attractive. What is the best approach for me to go multi-threaded? Am I just picky and should stick to one-connection-one-io_service-thing?


问:
React native Elements Input full width
I was trying to implement the Input from React Native Elements, which is the blue one. I want to make the Input have full width within the red view.
So I did

width: '100%', marginHorizontal: 0, padding: 0, and alignItems: 'stretch' independently.

But none of them didn't work. What is the problem?
This is the screenshot of the screen

And this is the corresponding code

```<code>    <View style = {styles.campusInputView}>
      <Input
        containerStyle = {styles.campusInputContainer}
        inputStyle = {styles.campusInput}
        placeholder = 'KAIST'
        editable = {false}
      />
    </View>
</code>```

with the style

```<code>  campusInputView: {
    borderWidth: 1,
    borderColor: 'red',
    position: 'absolute',
    top: height * 100 / 640,
    left: width * 45 / 360,
    width: width * 270 / 360,
  },
  campusInputContainer: {
    borderWidth: 1,
    borderColor: 'green',
    alignItems: 'stretch',
  },
  campusInput: {
    borderWidth: 1,
    borderColor: 'blue',
    flex: 1,
    fontFamily: 'NanumSquareB',
    fontSize: 20,
    paddingVertical: 0,
  },
</code>```

答:
Overwriting paddingHorizontal of containerStyle as 0 makes the input full width.
Overwriting only padding as 0 is not enough.

import { Input } from 'react-native-elements'

<Input
  containerStyle = {{ paddingHorizontal: 0 }}
  // other settings
/>
```

Title: React native Elements Input full width

Body:
I was trying to implement the Input from React Native Elements, which is the blue one. I want to make the Input have full width within the red view.
So I did

width: '100%', marginHorizontal: 0, padding: 0, and alignItems: 'stretch' independently.

But none of them didn't work. What is the problem?
This is the screenshot of the screen

And this is the corresponding code

    <View style = {styles.campusInputView}>
      <Input
        containerStyle = {styles.campusInputContainer}
        inputStyle = {styles.campusInput}
        placeholder = 'KAIST'
        editable = {false}
      />
    </View>

with the style

  campusInputView: {
    borderWidth: 1,
    borderColor: 'red',
    position: 'absolute',
    top: height * 100 / 640,
    left: width * 45 / 360,
    width: width * 270 / 360,
  },
  campusInputContainer: {
    borderWidth: 1,
    borderColor: 'green',
    alignItems: 'stretch',
  },
  campusInput: {
    borderWidth: 1,
    borderColor: 'blue',
    flex: 1,
    fontFamily: 'NanumSquareB',
    fontSize: 20,
    paddingVertical: 0,
  },


问:
Is it possible to transform a query joining onto a subselect into JPQL?
Given the following native SQL query containing a join to a subselect, is there a way to transform it into a JPQL query (or alternatively, is it possible to map this using @SqlResultSetMapping such that I don't have to execute thousands of subsequent queries to populate my objects (say in this case, Foo contains a reference to a single Bar and a list of Baz entities):

```<code>SELECT
    foo.*, bar.*, baz.*
FROM
    foo
        INNER JOIN
    bar ON foo.bar_id = bar.id
        INNER JOIN
    baz ON bar.baz_id = baz.id
        INNER JOIN
    (SELECT
        bar_id, MAX(some_int) ct
    FROM
        foo
    WHERE
        some_int <= 2
    GROUP BY bar_id) max_id ON max_id.bar_id = foo.bar_id
WHERE
    foo.some_int = max_id.ct;
</code>```

答:
Not directly with JPQL but you can use Blaze-Persistence on top of Hibernate to do this. See the following example: https://persistence.blazebit.com/documentation/1.5/core/manual/en_US/#subquery-in-from-clause

I'm assuming a JPA model here for the example. You will need the following CTE entity.

```<code>@CTE
@Entity
public class MyMaxEntity {
  @Id Integer id;
  Integer someInt;
}
</code>```

This is the query

```<code>criteriaBuilderFactory.create(entityManager, Foo.class, "foo")
  .fetch("bar.baz")
  .innerJoinOnSubquery(MyMaxEntity.class, "maxEnt")
    .from(Foo.class, "subFoo")
    .bind("id").select("subFoo.id")
    .bind("value").select("MAX(subFoo.someInt)")
    .where("subFoo.someInt").le(2)
  .end()
    .on("maxEnt.id").eqExpression("foo.bar.id")
  .end()
  .where("foo.someInt").eqExpression("maxEnt.value")
</code>```

Body:
Given the following native SQL query containing a join to a subselect, is there a way to transform it into a JPQL query (or alternatively, is it possible to map this using @SqlResultSetMapping such that I don't have to execute thousands of subsequent queries to populate my objects (say in this case, Foo contains a reference to a single Bar and a list of Baz entities):

SELECT
    foo.*, bar.*, baz.*
FROM
    foo
        INNER JOIN
    bar ON foo.bar_id = bar.id
        INNER JOIN
    baz ON bar.baz_id = baz.id
        INNER JOIN
    (SELECT
        bar_id, MAX(some_int) ct
    FROM
        foo
    WHERE
        some_int <= 2
    GROUP BY bar_id) max_id ON max_id.bar_id = foo.bar_id
WHERE
    foo.some_int = max_id.ct;

Body:
Not directly with JPQL but you can use Blaze-Persistence on top of Hibernate to do this. See the following example: https://persistence.blazebit.com/documentation/1.5/core/manual/en_US/#subquery-in-from-clause

I'm assuming a JPA model here for the example. You will need the following CTE entity.

@CTE
@Entity
public class MyMaxEntity {
  @Id Integer id;
  Integer someInt;
}

This is the query

criteriaBuilderFactory.create(entityManager, Foo.class, "foo")
  .fetch("bar.baz")
  .innerJoinOnSubquery(MyMaxEntity.class, "maxEnt")
    .from(Foo.class, "subFoo")
    .bind("id").select("subFoo.id")
    .bind("value").select("MAX(subFoo.someInt)")
    .where("subFoo.someInt").le(2)
  .end()
    .on("maxEnt.id").eqExpression("foo.bar.id")
  .end()
  .where("foo.someInt").eqExpression("maxEnt.value")


答:
Another option, using Regex.Matches to select the name parts except the first letter. The regex collects all string parts separated by a space, skipping what's before the comma.

The collections of Matches is then passed to Linq's Aggregate() method to perform the substitution.

A StringBuilder is used to store the strings generated by its own Replace() method:

```<code>string theName = "Jason Et Alt., Bruno Mars And More Names";
var matches = Regex.Matches(theName, @"(?!.*?,)\s+?.(\w+)");

string outName = matches.OfType<Match>().Aggregate(new StringBuilder(theName), (sb, m) =>
   sb.Replace(m.Groups[1].Value, new string('X', m.Groups[1].Length))).ToString();
</code>```

```<code>outname = Jason Et Alt., BXXXX MXXX AXX MXXX NXXXX
</code>```

Title: How to mask string after first character

Body:
Another option, using Regex.Matches to select the name parts except the first letter. The regex collects all string parts separated by a space, skipping what's before the comma.

The collections of Matches is then passed to Linq's Aggregate() method to perform the substitution.

A StringBuilder is used to store the strings generated by its own Replace() method:

string theName = "Jason Et Alt., Bruno Mars And More Names";
var matches = Regex.Matches(theName, @"(?!.*?,)\s+?.(\w+)");

string outName = matches.OfType<Match>().Aggregate(new StringBuilder(theName), (sb, m) =>
   sb.Replace(m.Groups[1].Value, new string('X', m.Groups[1].Length))).ToString();

outname = Jason Et Alt., BXXXX MXXX AXX MXXX NXXXX


问:
how to add duration time on google map draw path?
I able to draw path from source to destination it's working fine. but now I looking add to duration on path like google or ubar. tried but my duration marker little  bit away from drawer path.

```<code>let path = GMSPath(fromEncodedPath:objMapModel.arrayMapPath[0].routes.first?.overviewPolyline.points ?? "")
let rectangle = GMSPolyline(path: path)
rectangle.strokeWidth = 5.0
marker.map = mapView
rectangle.map = mapView
</code>```

I am looking something like this image. I want to add marker on path with duration time(ex 27h)

here is image more details

答:
Create your customMarker view and you use to markerInfowindow. plz try it.    </p>

```<code>func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {

    //Create customMarker and retur UIView
    return customMarker

}
OR
func mapView(_ mapView: GMSMapView, markerInfoContents marker: GMSMarker) -> UIView?
{
  let placeMarker = marker as! PlaceMarker
  let view = UIView(frame: CGRect.init(x: 0, y: 0, width: 150, height: 150))
  if let markerView = UIView.viewFromNibName(name: "MarkerView") as? MarkerView
  {
    infoView.nameLabel.text = placeMarker.name
    view.addSubview(markerView!)
    return view
   } else {
    return nil
  }
}
</code>```

Body:
I able to draw path from source to destination it's working fine. but now I looking add to duration on path like google or ubar. tried but my duration marker little  bit away from drawer path.

let path = GMSPath(fromEncodedPath:objMapModel.arrayMapPath[0].routes.first?.overviewPolyline.points ?? "")
let rectangle = GMSPolyline(path: path)
rectangle.strokeWidth = 5.0
marker.map = mapView
rectangle.map = mapView

I am looking something like this image. I want to add marker on path with duration time(ex 27h)

here is image more details

Body:
Create your customMarker view and you use to markerInfowindow. plz try it.

func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {

    //Create customMarker and retur UIView
    return customMarker

}
OR
func mapView(_ mapView: GMSMapView, markerInfoContents marker: GMSMarker) -> UIView?
{
  let placeMarker = marker as! PlaceMarker
  let view = UIView(frame: CGRect.init(x: 0, y: 0, width: 150, height: 150))
  if let markerView = UIView.viewFromNibName(name: "MarkerView") as? MarkerView
  {
    infoView.nameLabel.text = placeMarker.name
    view.addSubview(markerView!)
    return view
   } else {
    return nil
  }
}


问:
Problem dtyping 3 dimensional structured array
Beginner here!
I'm trying to to associate a different type for each different row of a 3 dimensional array. I tried an extended what I did with a 2 dimensional one but for some unknown reason it keeps giving me a TypeError: data type not understood. I need a huge list of Strings identified for a college project, I would appreciate your help. Im using the lastest python with the numpy package. :)</p>

```<code>dt = np.array([[('ID', 'i4'),('Name', 'U10')],
            [('ID', 'i4'),('Name', 'U10')],
            [('ID', 'i4'),('Name', 'U10')]])
Gthm_Extend_id = np.array([[(0, 'Red'),       ## Colors
                     (1, 'Orange'),
                     (2, 'Yellow'),
                     (3, 'Green'),
                     (4, 'Blue'),
                     (5, 'Purple'),
                     (6, 'Brown'),
                     (7, 'Black')],
                    [(0, 'Defender'),   ## Keywords
                     (1, 'First Strike'),
                     (2, 'FLying'),
                     (3, 'Haste'),
                     (4, 'Hexproof'),
                     (5, 'Indestructible'),
                     (6, 'Lifelink'),
                     (7, 'Trample'),
                     (8, 'Taunt')],
                     [(0, 'Devils'),    ## Tribe[enter image description here][1]s
                      (1, 'Whales'),
                      (2, 'Seraphins'),
                      (3, 'Beasts'),
                      (4, 'Turtles'),
                      (5, 'Octopuses'),
                      (6, 'Ogres'),
                      (7, 'Horrors')]],
                     dtype = dt)
</code>```

Body:
Beginner here!
I'm trying to to associate a different type for each different row of a 3 dimensional array. I tried an extended what I did with a 2 dimensional one but for some unknown reason it keeps giving me a TypeError: data type not understood. I need a huge list of Strings identified for a college project, I would appreciate your help. Im using the lastest python with the numpy package. :)

dt = np.array([[('ID', 'i4'),('Name', 'U10')],
            [('ID', 'i4'),('Name', 'U10')],
            [('ID', 'i4'),('Name', 'U10')]])
Gthm_Extend_id = np.array([[(0, 'Red'),       ## Colors
                     (1, 'Orange'),
                     (2, 'Yellow'),
                     (3, 'Green'),
                     (4, 'Blue'),
                     (5, 'Purple'),
                     (6, 'Brown'),
                     (7, 'Black')],
                    [(0, 'Defender'),   ## Keywords
                     (1, 'First Strike'),
                     (2, 'FLying'),
                     (3, 'Haste'),
                     (4, 'Hexproof'),
                     (5, 'Indestructible'),
                     (6, 'Lifelink'),
                     (7, 'Trample'),
                     (8, 'Taunt')],
                     [(0, 'Devils'),    ## Tribe[enter image description here][1]s
                      (1, 'Whales'),
                      (2, 'Seraphins'),
                      (3, 'Beasts'),
                      (4, 'Turtles'),
                      (5, 'Octopuses'),
                      (6, 'Ogres'),
                      (7, 'Horrors')]],
                     dtype = dt)

Body:
In [327]: dt = np.dtype([('ID', 'i4'),('Name', 'U10')])
In [328]: np.array([[(0, 'Red'),       ## Colors
     ...:                      (1, 'Orange'),
     ...:                      (2, 'Yellow'),
     ...:                      (3, 'Green'),
     ...:                      (4, 'Blue'),
     ...:                      (5, 'Purple'),
     ...:                      (6, 'Brown'),
     ...:                      (7, 'Black')],
     ...:                     [(0, 'Defender'),   ## Keywords
     ...:                      (1, 'First Strike'),
     ...:                      (2, 'FLying'),
     ...:                      (3, 'Haste'),
     ...:                      (4, 'Hexproof'),
     ...:                      (5, 'Indestructible'),
     ...:                      (6, 'Lifelink'),
     ...:                      (7, 'Trample'),
     ...:                      ],
     ...:                      [(0, 'Devils'),    ## Tribe[enter image description here][1]s
     ...:                       (1, 'Whales'),
     ...:                       (2, 'Seraphins'),
     ...:                       (3, 'Beasts'),
     ...:                       (4, 'Turtles'),
     ...:                       (5, 'Octopuses'),
     ...:                       (6, 'Ogres'),
     ...:                       (7, 'Horrors')]],
     ...:                      dt
     ...:                     )
Out[328]:
array([[(0, 'Red'), (1, 'Orange'), (2, 'Yellow'), (3, 'Green'),
        (4, 'Blue'), (5, 'Purple'), (6, 'Brown'), (7, 'Black')],
       [(0, 'Defender'), (1, 'First Stri'), (2, 'FLying'), (3, 'Haste'),
        (4, 'Hexproof'), (5, 'Indestruct'), (6, 'Lifelink'),
        (7, 'Trample')],
       [(0, 'Devils'), (1, 'Whales'), (2, 'Seraphins'), (3, 'Beasts'),
        (4, 'Turtles'), (5, 'Octopuses'), (6, 'Ogres'), (7, 'Horrors')]],
      dtype=[('ID', '<i4'), ('Name', '<U10')])
In [329]: _.shape
Out[329]: (3, 8)


问:
x86 Assembly: Loops!
Okay, long story short, I'm learning assembly, and I'm trying to make a loop print out the ascii characters "0" - "9".
So, I did all of the basics I've been seeing in examples, like saving register states with pushad and popad, allocating stack space, and making sure I leave things the way they started.
So I managed this small example:

```<code>;
; Hello_World.asm
; (NASM Syntax, Windows)

    extern _printf

    section .text

_main:
  pushad                ; save register states

  push  ebp             ; save old stack
  mov       ebp, esp    ; prepare new stack
  sub       esp, 1*4    ; allocate 4 bytes

  mov       byte [esp + 0], 48  ; add ascii '0' to stack
  mov       byte [esp + 1], 0   ; add ascii NULL terminator to stack

  push  esp;        ; push the string in the stacks refrence
  call  _printf     ; call printf()
  add   esp, 4      ; pop string refrence

  add   esp, 1*4    ; deallocate 4 bytes
  mov   esp, ebp    ; close this stack
  pop   ebp         ; restore old stack

  popad             ; restore register states
  ret               ; leave this function
</code>```

This works, it prints out '0', but that's a little on the safe side. I tried adding a loop into it, but things just fall apart there. I read that the 'loop' opcode is supposed to decrement the ECX register, and go back to the label parameter should ECX > 0, however, I don't think I've quite got it yet.

So I add a few lines, and come up with this:

```<code>;
; Hello_World.asm
;

    extern _printf
    global _main

    section .text

_main:
  pushad                ; save register states

  push  ebp         ; save old stack
  mov   ebp, esp    ; prepare new stack
  sub   esp, 1*4    ; allocate 4 bytes

  mov   byte [esp + 0], 48  ; add ascii '0' to stack
  mov   byte [esp + 1], 0   ; add ascii NULL terminator to stack

  mov   ecx, 9      ; set loop counter to 9

aLoop:
  inc   byte [esp + 0]  ; increment ascii character
  push  esp;        ; push the string in the stacks refrence
  call  _printf     ; call printf()
  add   esp, 4      ; pop string refrence
  loop  aLoop           ; loop back to aLoop if ecx > 0

  add   esp, 1*4    ; deallocate 4 bytes
  mov   esp, ebp    ; close this stack
  pop   ebp         ; restore old stack

  popad             ; restore register states
  ret                   ; leave this function
</code>```

Well, now things go crazy. I run it in command prompt and I hear this beeping through my headphones, and it's cycling through every ascii character, printing them all out. So after about 5 seconds of flying characters, I assume something overflows, and it just crashes.

I'm pretty new to assembly (today's my first day of real coding), and I don't see what's going wrong. Could someone please explain how I could better implement a loop ?

Thanks ahead!
-Jason

答:
okay, well, what you're describing is that the loop isn't terminating for some reason.  That means the problem pretty well has to be here:

```<code>  add   esp, 4      ; pop string refrence
  loop  aLoop       ; loop back to aLoop if ecx > 0
</code>```

This sounds like a job for a debugger: what's really happening to ecx?

Well, I note that you're setting ecx to 9.   You're then adding 4 to esp.  When are you changing ecx? (Yes, I know it's supposed to be happening in the loop instruction, but if that were working you wouldn't be asking.  What's really happening to ecx?)

The beeping, by the way, is easy: as you cycle through all the ASCII characters, you're hitting ASCII 0x07, the BEL character.

Title: x86 Assembly: Loops!

Body:
Okay, long story short, I'm learning assembly, and I'm trying to make a loop print out the ascii characters "0" - "9".
So, I did all of the basics I've been seeing in examples, like saving register states with pushad and popad, allocating stack space, and making sure I leave things the way they started.
So I managed this small example:

;
; Hello_World.asm
; (NASM Syntax, Windows)

    extern _printf

    section .text

_main:
  pushad                ; save register states

  push  ebp             ; save old stack
  mov       ebp, esp    ; prepare new stack
  sub       esp, 1*4    ; allocate 4 bytes

  mov       byte [esp + 0], 48  ; add ascii '0' to stack
  mov       byte [esp + 1], 0   ; add ascii NULL terminator to stack

  push  esp;        ; push the string in the stacks refrence
  call  _printf     ; call printf()
  add   esp, 4      ; pop string refrence

  add   esp, 1*4    ; deallocate 4 bytes
  mov   esp, ebp    ; close this stack
  pop   ebp         ; restore old stack

  popad             ; restore register states
  ret               ; leave this function

This works, it prints out '0', but that's a little on the safe side. I tried adding a loop into it, but things just fall apart there. I read that the 'loop' opcode is supposed to decrement the ECX register, and go back to the label parameter should ECX > 0, however, I don't think I've quite got it yet.

So I add a few lines, and come up with this:

;
; Hello_World.asm
;

    extern _printf
    global _main

    section .text

_main:
  pushad                ; save register states

  push  ebp         ; save old stack
  mov   ebp, esp    ; prepare new stack
  sub   esp, 1*4    ; allocate 4 bytes

  mov   byte [esp + 0], 48  ; add ascii '0' to stack
  mov   byte [esp + 1], 0   ; add ascii NULL terminator to stack

  mov   ecx, 9      ; set loop counter to 9

aLoop:
  inc   byte [esp + 0]  ; increment ascii character
  push  esp;        ; push the string in the stacks refrence
  call  _printf     ; call printf()
  add   esp, 4      ; pop string refrence
  loop  aLoop           ; loop back to aLoop if ecx > 0

  add   esp, 1*4    ; deallocate 4 bytes
  mov   esp, ebp    ; close this stack
  pop   ebp         ; restore old stack

  popad             ; restore register states
  ret                   ; leave this function

Well, now things go crazy. I run it in command prompt and I hear this beeping through my headphones, and it's cycling through every ascii character, printing them all out. So after about 5 seconds of flying characters, I assume something overflows, and it just crashes.

I'm pretty new to assembly (today's my first day of real coding), and I don't see what's going wrong. Could someone please explain how I could better implement a loop ?

Thanks ahead!
-Jason

Body:
okay, well, what you're describing is that the loop isn't terminating for some reason.  That means the problem pretty well has to be here:

  add   esp, 4      ; pop string refrence
  loop  aLoop       ; loop back to aLoop if ecx > 0

This sounds like a job for a debugger: what's really happening to ecx?

Well, I note that you're setting ecx to 9.   You're then adding 4 to esp.  When are you changing ecx? (Yes, I know it's supposed to be happening in the loop instruction, but if that were working you wouldn't be asking.  What's really happening to ecx?)

The beeping, by the way, is easy: as you cycle through all the ASCII characters, you're hitting ASCII 0x07, the BEL character.


问:
Overcoming erasure case study; currying Maps
I have been struggling with the following Scala code

```<code>def curry[A,B,C,U](m: Map[(A,B,C),U], a: A): Map[(B,C),U] = m.collect { case ((aa,b,c),v) if aa == a => (b,c) -> v }
def curry[A,B,C,U](m: Map[(A,B,C),U], b: B): Map[(A,C),U] = m.collect { case ((a,bb,c),v) if bb == b => (a,c) -> v }
</code>```

I cannot compile this as both functions are the same after Erasure, and I have to resort to terrible workarounds (like curry1, curry2, curry12 etc.)

Error: double definition:
  def curry[A, B, C, U](m: Map[(A, B, C),U], a: A): Map[(B, C),U] at line 152 and
  def curry[A, B, C, U](m: Map[(A, B, C),U], b: B): Map[(A, C),U] at line 153
  have same type after erasure: (m: scala.collection.immutable.Map, a: Object)scala.collection.immutable.Map
    def curry[A,B,C,U](m: Map[(A,B,C),U], b: B): Map[(A,C),U] = m.collect { case ((a,bb,c),v) if bb == b => (a,c) -> v }

Is there a way to make this work? Dire situations allow for dire solutions (aka reflection and TypeTags maybe?)

答:
A workaround:

```<code>def curry[A,B,C,U](m: Map[(A,B,C),U], a: A): Map[(B,C),U] = m.collect { case ((aa,b,c),v) if aa == a => (b,c) -> v }
def curry[A,B,C,U](m: Map[(A,B,C),U], b: B, dummy: Int = 0): Map[(A,C),U] = m.collect { case ((a,bb,c),v) if bb == b => (a,c) -> v }
</code>```

Or:

```<code>def curry[A,B,C,U](m: Map[(A,B,C),U], a: A): Map[(B,C),U] = m.collect { case ((aa,b,c),v) if aa == a => (b,c) -> v }
def curry[A,B,C,U](m: Map[(A,B,C),U], b: B)(implicit d: DummyImplicit): Map[(A,C),U] = m.collect { case ((a,bb,c),v) if bb == b => (a,c) -> v }
</code>```

Body:
I have been struggling with the following Scala code

def curry[A,B,C,U](m: Map[(A,B,C),U], a: A): Map[(B,C),U] = m.collect { case ((aa,b,c),v) if aa == a => (b,c) -> v }
def curry[A,B,C,U](m: Map[(A,B,C),U], b: B): Map[(A,C),U] = m.collect { case ((a,bb,c),v) if bb == b => (a,c) -> v }

I cannot compile this as both functions are the same after Erasure, and I have to resort to terrible workarounds (like curry1, curry2, curry12 etc.)

Error: double definition:
  def curry[A, B, C, U](m: Map[(A, B, C),U], a: A): Map[(B, C),U] at line 152 and
  def curry[A, B, C, U](m: Map[(A, B, C),U], b: B): Map[(A, C),U] at line 153
  have same type after erasure: (m: scala.collection.immutable.Map, a: Object)scala.collection.immutable.Map
    def curry[A,B,C,U](m: Map[(A,B,C),U], b: B): Map[(A,C),U] = m.collect { case ((a,bb,c),v) if bb == b => (a,c) -> v }

Is there a way to make this work? Dire situations allow for dire solutions (aka reflection and TypeTags maybe?)

Body:
A workaround:

def curry[A,B,C,U](m: Map[(A,B,C),U], a: A): Map[(B,C),U] = m.collect { case ((aa,b,c),v) if aa == a => (b,c) -> v }
def curry[A,B,C,U](m: Map[(A,B,C),U], b: B, dummy: Int = 0): Map[(A,C),U] = m.collect { case ((a,bb,c),v) if bb == b => (a,c) -> v }

Or:

def curry[A,B,C,U](m: Map[(A,B,C),U], a: A): Map[(B,C),U] = m.collect { case ((aa,b,c),v) if aa == a => (b,c) -> v }
def curry[A,B,C,U](m: Map[(A,B,C),U], b: B)(implicit d: DummyImplicit): Map[(A,C),U] = m.collect { case ((a,bb,c),v) if bb == b => (a,c) -> v }


问:
pass const pointer of large struct to a function or a go channel
How to pass const pointer of large struct to a function or a go channel.
Purpose of this ask is:

Avoid the accidental modification of pointer by the function

Avoid the copy of the struct object while passing to
function/channel

This functionality is very common in C++, C#, Java, but how can we achieve the same in golang?

============== Update 2 ===================

Thank you @zarkams, @mkopriva and @peterSO
It was the compiler optimization causing the same result in both byValue() and byPointer().
Modified the functions byValue() and byPointer() by adding
data.array[0] = reverse(data.array[0]), just to make compiler not to make the functions inline.

```<code>func byValue(data Data) int {
    data.array[0] = reverse(data.array[0])
    return len(data.array)
}

func byPointer(data *Data) int {
    data.array[0] = reverse(data.array[0])
    return len(data.array)
}

func reverse(s string) string {
    runes := []rune(s)
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
    return string(runes)
}
</code>```

After that running the benchmarks, passing by pointer was much efficient than passing by value.

```<code>C:\Users\anikumar\Desktop\TestGo>go test -bench=.
goos: windows
goarch: amd64
BenchmarkByValue-4         18978             58228 ns/op               3 B/op          1 allocs/op
BenchmarkByPointer-4    40034295                33.1 ns/op             3 B/op          1 allocs/op
PASS
ok      _/C_/Users/anikumar/Desktop/TestGo      3.336s

C:\Users\anikumar\Desktop\TestGo>go test -gcflags -N -run=none -bench=.
goos: windows
goarch: amd64
BenchmarkByValue-4         20961             59380 ns/op               3 B/op          1 allocs/op
BenchmarkByPointer-4    31386213                36.5 ns/op             3 B/op          1 allocs/op
PASS
ok      _/C_/Users/anikumar/Desktop/TestGo      3.909s
</code>```

============== Update ===================

Based on feedback from @zerkms, I created a test to find the performance difference between copy by value and copy by the pointer.

```<code>package main

import (
    "log"
    "time"
)

const size = 99999

// Data ...
type Data struct {
    array [size]string
}

func main() {
    // Preparing large data
    var data Data
    for i := 0; i < size; i++ {
        data.array[i] = "This is really long string"
    }

    // Starting test
    const max = 9999999999
    start := time.Now()
    for i := 0; i < max; i++ {
        byValue(data)
    }
    elapsed := time.Since(start)
    log.Printf("By Value took %s", elapsed)

    start = time.Now()
    for i := 0; i < max; i++ {
        byPointer(&data)
    }
    elapsed = time.Since(start)
    log.Printf("By Pointer took %s", elapsed)
}

func byValue(data Data) int {
    data.array[0] = reverse(data.array[0])
    return len(data.array)
}

func byPointer(data *Data) int {
    data.array[0] = reverse(data.array[0])
    return len(data.array)
}

func reverse(s string) string {
    runes := []rune(s)
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
    return string(runes)
}
</code>```

After 10 iterations of the above program, I did not find any difference in execution time.

```<code>C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:52:03 By Value took 5.2798936s
2020/02/16 15:52:09 By Pointer took 5.3466306s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:52:18 By Value took 5.3596692s
2020/02/16 15:52:23 By Pointer took 5.2724685s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:52:29 By Value took 5.2359938s
2020/02/16 15:52:34 By Pointer took 5.2838676s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:52:42 By Value took 5.8374936s
2020/02/16 15:52:49 By Pointer took 6.9524342s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:53:40 By Value took 5.4364867s
2020/02/16 15:53:46 By Pointer took 5.8712875s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:53:54 By Value took 5.5481591s
2020/02/16 15:54:00 By Pointer took 5.5600314s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:54:10 By Value took 5.4753771s
2020/02/16 15:54:16 By Pointer took 6.4368084s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:54:24 By Value took 5.4783356s
2020/02/16 15:54:30 By Pointer took 5.5312314s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:54:39 By Value took 5.4853542s
2020/02/16 15:54:45 By Pointer took 5.5541164s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:54:57 By Value took 5.4633856s
2020/02/16 15:55:03 By Pointer took 5.4863226s
</code>```

Looks like @zerkms is right. It is not because of language, it is because of modern hardware.

答:
I think this is a really good question, and I don't know why people have marked it down.  (That is, the original question of using a "const pointer" to pass a large struct.)

The simple answer is that Go has no way to indicate that a function (or channel) taking a pointer is not going to modify the thing pointed to. Basically it is up to the creator of the function to document that the function will not modify the structure.

@Anil8753 as you explicitly mention channels I should explain something further.  Typically when using a channel you are passing data to another go-routine.  If you pass a pointer to the struct then the sender must be careful not to modify the struct after it has been sent (at least while the receiver could be reading it) and vice versa.  This would create a data race.

For this reason I typically pass structs by value with channels.  If you need to create something in the sender for exclusive use of the receiver then create a struct (on the heap) and send a pointer to it in the channel and never use it again (even assigning nil to the pointer to make this explicit).

@zerkms makes a very good point that before you optimize you should understand what is happening and make measurements.  However, in this case there is an obvious performance benefit to not copying memory around.  Whether this happens when the struct is 1KB, 1MB, or 1GB there will come a point where you want to pass by "reference" (ie a pointer to the struct) rather than by value (as long as you know the struct won't be modified or don't care if it is).

In theory and in practice copy by value will become very inefficient when the struct becomes large enough or the function is called many times.

Body:
How to pass const pointer of large struct to a function or a go channel.
Purpose of this ask is:

Avoid the accidental modification of pointer by the function

Avoid the copy of the struct object while passing to
function/channel

This functionality is very common in C++, C#, Java, but how can we achieve the same in golang?

============== Update 2 ===================

Thank you @zarkams, @mkopriva and @peterSO
It was the compiler optimization causing the same result in both byValue() and byPointer().
Modified the functions byValue() and byPointer() by adding
data.array[0] = reverse(data.array[0]), just to make compiler not to make the functions inline.

func byValue(data Data) int {
    data.array[0] = reverse(data.array[0])
    return len(data.array)
}

func byPointer(data *Data) int {
    data.array[0] = reverse(data.array[0])
    return len(data.array)
}

func reverse(s string) string {
    runes := []rune(s)
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
    return string(runes)
}

After that running the benchmarks, passing by pointer was much efficient than passing by value.

C:\Users\anikumar\Desktop\TestGo>go test -bench=.
goos: windows
goarch: amd64
BenchmarkByValue-4         18978             58228 ns/op               3 B/op          1 allocs/op
BenchmarkByPointer-4    40034295                33.1 ns/op             3 B/op          1 allocs/op
PASS
ok      _/C_/Users/anikumar/Desktop/TestGo      3.336s

C:\Users\anikumar\Desktop\TestGo>go test -gcflags -N -run=none -bench=.
goos: windows
goarch: amd64
BenchmarkByValue-4         20961             59380 ns/op               3 B/op          1 allocs/op
BenchmarkByPointer-4    31386213                36.5 ns/op             3 B/op          1 allocs/op
PASS
ok      _/C_/Users/anikumar/Desktop/TestGo      3.909s

============== Update ===================

Based on feedback from @zerkms, I created a test to find the performance difference between copy by value and copy by the pointer.

package main

import (
    "log"
    "time"
)

const size = 99999

// Data ...
type Data struct {
    array [size]string
}

func main() {
    // Preparing large data
    var data Data
    for i := 0; i < size; i++ {
        data.array[i] = "This is really long string"
    }

    // Starting test
    const max = 9999999999
    start := time.Now()
    for i := 0; i < max; i++ {
        byValue(data)
    }
    elapsed := time.Since(start)
    log.Printf("By Value took %s", elapsed)

    start = time.Now()
    for i := 0; i < max; i++ {
        byPointer(&data)
    }
    elapsed = time.Since(start)
    log.Printf("By Pointer took %s", elapsed)
}

func byValue(data Data) int {
    data.array[0] = reverse(data.array[0])
    return len(data.array)
}

func byPointer(data *Data) int {
    data.array[0] = reverse(data.array[0])
    return len(data.array)
}

func reverse(s string) string {
    runes := []rune(s)
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
    return string(runes)
}

After 10 iterations of the above program, I did not find any difference in execution time.

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:52:03 By Value took 5.2798936s
2020/02/16 15:52:09 By Pointer took 5.3466306s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:52:18 By Value took 5.3596692s
2020/02/16 15:52:23 By Pointer took 5.2724685s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:52:29 By Value took 5.2359938s
2020/02/16 15:52:34 By Pointer took 5.2838676s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:52:42 By Value took 5.8374936s
2020/02/16 15:52:49 By Pointer took 6.9524342s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:53:40 By Value took 5.4364867s
2020/02/16 15:53:46 By Pointer took 5.8712875s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:53:54 By Value took 5.5481591s
2020/02/16 15:54:00 By Pointer took 5.5600314s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:54:10 By Value took 5.4753771s
2020/02/16 15:54:16 By Pointer took 6.4368084s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:54:24 By Value took 5.4783356s
2020/02/16 15:54:30 By Pointer took 5.5312314s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:54:39 By Value took 5.4853542s
2020/02/16 15:54:45 By Pointer took 5.5541164s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:54:57 By Value took 5.4633856s
2020/02/16 15:55:03 By Pointer took 5.4863226s

Looks like @zerkms is right. It is not because of language, it is because of modern hardware.


问:
Cannot find element using xpath (Python and selenium)
I try to make some automations using Python+selenium (new to this). Unfortunatelly, inspecting elements of a specific webpage is more than hard. There is no id to use and I try xpath.
I want to select a drop down list , i inspect this element and I copy the xpath which is
//*[@id="frmMain:criteria:purchase_criteria_tab"]/div[13]/div[1]/div/button

my code is:

```<code>    NEXT_BUTTON_XPATH = "//*[@id='frmMain:criteria:purchase_criteria_tab']/div[13]/div[1]/div/button"
wait = WebDriverWait(driver, 10)
condition = expected_conditions.presence_of_element_located(
    (By.XPATH, NEXT_BUTTON_XPATH))
button = wait.until(condition)
button.click()
</code>```

and I cannot get the element
Any ideas? Thank you in advance.

答:
try this</p>

```<code>from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
try:
    # for click element element_to_be_clickable condition used
    button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable(By.XPATH, "elemnt_xpath")))
    button.click()

except Exception as e:
    print(e)
</code>```

Body:
I try to make some automations using Python+selenium (new to this). Unfortunatelly, inspecting elements of a specific webpage is more than hard. There is no id to use and I try xpath.
I want to select a drop down list , i inspect this element and I copy the xpath which is
//*[@id="frmMain:criteria:purchase_criteria_tab"]/div[13]/div[1]/div/button

my code is:

    NEXT_BUTTON_XPATH = "//*[@id='frmMain:criteria:purchase_criteria_tab']/div[13]/div[1]/div/button"
wait = WebDriverWait(driver, 10)
condition = expected_conditions.presence_of_element_located(
    (By.XPATH, NEXT_BUTTON_XPATH))
button = wait.until(condition)
button.click()

and I cannot get the element
Any ideas? Thank you in advance.

Body:
try this

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
try:
    # for click element element_to_be_clickable condition used
    button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable(By.XPATH, "elemnt_xpath")))
    button.click()

except Exception as e:
    print(e)


问:
PowerBI, Live connection to Bigquery is slow, how to troubleshoot?
I am connecting PowerBI to Bigquery view, it is slow, how to troubleshoot and understand if it PowerBI or Bigquery, I use the same view in datastudio and it is way faster.

I attached an example here

https://app.powerbi.com/view?r=eyJrIjoiNTg5MDVjYjktZmNjMi00MzJjLWEzY2UtMTJmMTllNzI3ZTk2IiwidCI6IjdmNjhjN2QwLTc0ZTgtNGE2Ni04NGI3LWZhMjdlMzYyNTFiOCJ9

in the console, I get this results

Query complete (1.5 sec elapsed, 8.4 MB processed)

I know there is an overhead to download the data from BQ to PowerBI, but it seems very slow for such a small data

答:
You could refresh this report from within Power BI Desktop with Performance Analyzer recording session, which should give you better understanding what is going on, where, and how long it takes:

You could also use DAX Studio to capture the queries sent to the data source, if you believe that they are slow:


问:
Can not work the build "flutter build apk" command, But "flutter build ios" can work

I am a beginner.
Currently I am trying to build my flutter app for iOS and android .
I can build successfully in ios by   “flutter build ios”.
But I have the following issue with "flutter build apk".
I will be very happy if someone can help to answer for the following issue (Ref attach img).

Doctor summary (to see all details, run flutter doctor -v):

```<code>Flutter (Channel stable, v1.12.13+hotfix.8, on Mac OS X 10.15.3 19D76, locale en-SG)
Android toolchain - develop for Android devices (Android SDK version 29.0.0)
Xcode - develop for iOS and macOS (Xcode 11.3.1)
Android Studio (version 3.5)
VS Code (version 1.42.1)
Connected device (1 available)
</code>```

答:
first try
flutter clean

then flutter pub cache repair

if the problem still persists,

Check for compilesdkversion everywhere in the folder and match it with one in android/app/build.gradle

Check here, same kind issue is closed in flutter

Body:
I am a beginner.
Currently I am trying to build my flutter app for iOS and android .
I can build successfully in ios by   “flutter build ios”.
But I have the following issue with "flutter build apk".
I will be very happy if someone can help to answer for the following issue (Ref attach img).

Doctor summary (to see all details, run flutter doctor -v):

Flutter (Channel stable, v1.12.13+hotfix.8, on Mac OS X 10.15.3 19D76, locale en-SG)
Android toolchain - develop for Android devices (Android SDK version 29.0.0)
Xcode - develop for iOS and macOS (Xcode 11.3.1)
Android Studio (version 3.5)
VS Code (version 1.42.1)
Connected device (1 available)


问:
Getting unknow columns from list to dataframe
I have my list contained other 119,554 lists in. All the lists have the same length of 334 lists. I needed to covert list into dataframe using df2=pd.DataFrame(df). The result shows (119554, 706)

I don't know why there are additional columns added. It should be (119554, 33) if I'm not wrong.

Any suggestion? Thank!

答:
Let's say you have the following lists within another list:

lst = [[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9],
       [10, 11, 12]]
```

<p>You can see that the list contains <em>4 lists</em> having <em>length 3</em>. Lists do not have <code>shape</code> attribute.</p>

<p>You can convert this list into a pandas dataframe in the following way:</p>

<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame(lst)
</code>```

The dataframe looks like this:

```<code>|    |   0 |   1 |   2 |
|---:|----:|----:|----:|
|  0 |   1 |   2 |   3 |
|  1 |   4 |   5 |   6 |
|  2 |   7 |   8 |   9 |
|  3 |  10 |  11 |  12 |
</code>```

The shape of the dataframe is:

print(df.shape)
```

<pre class="lang-py prettyprint-override"><code>>> (4, 3)
</code>```

Body:
Let's say you have the following lists within another list:

lst = [[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9],
       [10, 11, 12]]

You can see that the list contains 4 lists having length 3. Lists do not have shape attribute.

You can convert this list into a pandas dataframe in the following way:

df = pd.DataFrame(lst)

The dataframe looks like this:

|    |   0 |   1 |   2 |
|---:|----:|----:|----:|
|  0 |   1 |   2 |   3 |
|  1 |   4 |   5 |   6 |
|  2 |   7 |   8 |   9 |
|  3 |  10 |  11 |  12 |

The shape of the dataframe is:

print(df.shape)

>> (4, 3)