问:
Skype Bot Rest API, 403 The bot is not allowed to perform the requested operation
So I used an account and message my skype bot.

Received Message: {"text":"test","type":"message","timestamp":"2017-11-15T21:52:10.379Z","id":"1510782730376","channelId":"skype","serviceUrl":"https://smba.trafficmanager.net/apis/","from":{"id":"29:1tJkKyeNp1o5xbMfK9hxF_U2s7huwsAKi4LMD0kOJbkg"},"conversation":{"id":"29:1tJkKyeNp1o5xbMfK9hxF_U2s7huwsAKi4LMD0kOJbkg"},"recipient":{"id":"28:8a75f591-62bf-422b-be6c-4b4b8bd1a576","name":"SKYPE_BOT"},"entities":[{"locale":"ru-RU","country":"RU","platform":"Windows","type":"clientInfo"}],"channelData":{"text":"test"}}

Sending 'POST' request to URL : https://smba.trafficmanager.net/apis/v3/conversations/29:1tJkKyeNp1o5xbMfK9hxF_U2s7huwsAKi4LMD0kOJbkg/activities/1510782730376
Post parameters : {"replyToId":"1510782730376","recipient":{"id":"29:1tJkKyeNp1o5xbMfK9hxF_U2s7huwsAKi4LMD0kOJbkg"},"from":{"name":"SKYPE_BOT","id":"28:8a75f591-62bf-422b-be6c-4b4b8bd1a576"},"text":"Hello, test","type":"message","locale":"ru","conversation":{"id":"29:1tJkKyeNp1o5xbMfK9hxF_U2s7huwsAKi4LMD0kOJbkg"}}

Response Code : 403 Response message: Forbidden

403     The bot is not allowed to perform the requested operation.

what i'm doing wrong?

答:
To communicate with the Bot Connector service, you must specify an
  access token in the Authorization header of each API request, using
  this format:

Authorization: Bearer ACCESS_TOKEN

from: https://learn.microsoft.com/en-us/bot-framework/rest-api/bot-framework-rest-connector-authentication#bot-to-connector


来源: stackexchange

问:
how to pass two class instances to a method of the class in python
I made two trees in python with two different instances of the same class. I need to access the method in the class now with both the instances(roots) with which i created two trees.

```<code># To create a tree from scratch
class node:
    """To create nodes each time an instance has been
    created"""
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None

def issame(self,root1,root2):
  if root1 or root2:
    print(root1.data,root2.data)
    self.issame(root1.left,root2.left)

"""To insert the data manually"""
##First Tree
root1 = node(10)
root1.left = node(20)
root1.right = node(30)
root1.left.left = node(50)

##Second Tree
root2 = node(20)
root2.left = node(20)
root2.right = node(30)
root2.left.left = node(50)

issame(root1,root2)
</code>```

I read in some post that we can keep the issame function definition outside of the class and use self within. Now at the end if i call the function, it says issame doesn't exist. Issame is used to check if leaf nodes of tree are same and the method is not fully developed as i faced the problem in first step.

答:
You must choose whether you want issame() in the class, or outside, but it cannot be a hybrid of a little bit of both:

You must also override the __eq__ method of your Node class in order to compare two nodes with the operator ==

issame as a method:

```<code>class Node:
    """To create nodes each time an instance has been
    created"""
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None

    def __eq__(self, other):
        assert isinstance(other, Node)
        return self.data == other.data \
               and self.left == other.left \
               and self.right == other.right

    def issame(self, root2):
      return self == root2

"""To insert the data manually"""
##First Tree
root1 = Node(10)
root1.left = Node(20)
root1.right = Node(30)
root1.left.left = Node(50)

##Second Tree
root2 = Node(20)
root2.left = Node(20)
root2.right = Node(30)
root2.left.left = Node(50)

root1.issame(root2)          #<-- here you are calling issame on root1, with root2 as argument
</code>```

issame as a function:

```<code>class Node:
    """To create nodes each time an instance has been
    created"""
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None

    def __eq__(self, other):
        assert isinstance(other, Node)
        return self.data == other.data \
               and self.left == other.left \
               and self.right == other.right

def issame(root1, root2):
    return root1 == root2

"""To insert the data manually"""
##First Tree
root1 = Node(10)
root1.left = Node(20)
root1.right = Node(30)
root1.left.left = Node(50)

##Second Tree
root2 = Node(20)
root2.left = Node(20)
root2.right = Node(30)
root2.left.left = Node(50)

issame(root1, root2)       # < attention, different way of calling
                           # here you are calling issame passing root 1 and root2 as arguments
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I made two trees in python with two different instances of the same class. I need to access the method in the class now with both the instances(roots) with which i created two trees.

# To create a tree from scratch
class node:
    """To create nodes each time an instance has been
    created"""
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None

def issame(self,root1,root2):
  if root1 or root2:
    print(root1.data,root2.data)
    self.issame(root1.left,root2.left)

"""To insert the data manually"""
##First Tree
root1 = node(10)
root1.left = node(20)
root1.right = node(30)
root1.left.left = node(50)

##Second Tree
root2 = node(20)
root2.left = node(20)
root2.right = node(30)
root2.left.left = node(50)

issame(root1,root2)

I read in some post that we can keep the issame function definition outside of the class and use self within. Now at the end if i call the function, it says issame doesn't exist. Issame is used to check if leaf nodes of tree are same and the method is not fully developed as i faced the problem in first step.

Body:
You must choose whether you want issame() in the class, or outside, but it cannot be a hybrid of a little bit of both:

You must also override the __eq__ method of your Node class in order to compare two nodes with the operator ==

issame as a method:

class Node:
    """To create nodes each time an instance has been
    created"""
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None

    def __eq__(self, other):
        assert isinstance(other, Node)
        return self.data == other.data \
               and self.left == other.left \
               and self.right == other.right

    def issame(self, root2):
      return self == root2

"""To insert the data manually"""
##First Tree
root1 = Node(10)
root1.left = Node(20)
root1.right = Node(30)
root1.left.left = Node(50)

##Second Tree
root2 = Node(20)
root2.left = Node(20)
root2.right = Node(30)
root2.left.left = Node(50)

root1.issame(root2)          #<-- here you are calling issame on root1, with root2 as argument

issame as a function:

class Node:
    """To create nodes each time an instance has been
    created"""
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None

    def __eq__(self, other):
        assert isinstance(other, Node)
        return self.data == other.data \
               and self.left == other.left \
               and self.right == other.right

def issame(root1, root2):
    return root1 == root2

"""To insert the data manually"""
##First Tree
root1 = Node(10)
root1.left = Node(20)
root1.right = Node(30)
root1.left.left = Node(50)

##Second Tree
root2 = Node(20)
root2.left = Node(20)
root2.right = Node(30)
root2.left.left = Node(50)

issame(root1, root2)       # < attention, different way of calling
                           # here you are calling issame passing root 1 and root2 as arguments


问:
VS2015 build fails with no error message with Dynamic
I was writing a unit test on a piece of code that returned JSON. The type that it returns is an anonymous type, so I thought to verify the values on it I'd just cast the object to a dynamic to do my assertions.

However, when I do that, my build fails but I don't have any error messages. I was able to reproduce this with very simple code in a new Unit Test Project:

```<code>[TestMethod]
public void TestMethod1()
{
    var obj = new { someValue = true };

    dynamic asDynamic = obj;

    Assert.IsTrue(asDynamic.someValue);
}
</code>```

See below for a screenshot of the build failing

The build succeeds when I comment out the assertion though:

In contrast, I ran the following code in LinqPad 5 beta (which uses the Roslyn compiler) and had no issues:

```<code>var obj = new { someValue = true };
dynamic asDynamic = obj;
Console.WriteLine((asDynamic.someValue == true).ToString());
</code>```

True

What's going on here? Since the error isn't showing I can't tell if I'm using dynamic incorrectly, or if it can't find the overload to use for IsTrue() because of the dynamic, or if this is a bug in the compiler (though I highly doubt this, I don't have any evidence that there's something wrong with my code).

Regarding the overload issue, I tried Assert.IsTrue((bool)asDynamic.someValue); but the build still fails, still no error message.

Per @RonBeyer's comment, I had also tried more casting such as below to no avail:

```<code>    dynamic asDynamic = (dynamic)obj;
    Assert.IsTrue(((dynamic)asDynamic).someValue);

    Assert.IsTrue((bool)asDynamic.somevalue);
</code>```

Upon closer inspection, I found that there was an error listed in the Output window:

c:...\DynamicBuildFailTest\UnitTest1.cs(16,33,16,42): error CS0656: Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'

Okay, VS2013 is better at reporting the errors, I will search based on those:

Okay, adding a reference to Microsoft.CSharp fixed the build error, but I will leave this question open because it's presumably an issue with VS2015 that (in my mind) should be resolved.

答: As two people have noted in comments, for Net Core and NetStandard, this problem is sometimes fixed by adding a NuGet reference to Microsoft.CSharp.

Body:
I was writing a unit test on a piece of code that returned JSON. The type that it returns is an anonymous type, so I thought to verify the values on it I'd just cast the object to a dynamic to do my assertions.

However, when I do that, my build fails but I don't have any error messages. I was able to reproduce this with very simple code in a new Unit Test Project:

[TestMethod]
public void TestMethod1()
{
    var obj = new { someValue = true };

    dynamic asDynamic = obj;

    Assert.IsTrue(asDynamic.someValue);
}

See below for a screenshot of the build failing

The build succeeds when I comment out the assertion though:

In contrast, I ran the following code in LinqPad 5 beta (which uses the Roslyn compiler) and had no issues:

var obj = new { someValue = true };
dynamic asDynamic = obj;
Console.WriteLine((asDynamic.someValue == true).ToString());

True

What's going on here? Since the error isn't showing I can't tell if I'm using dynamic incorrectly, or if it can't find the overload to use for IsTrue() because of the dynamic, or if this is a bug in the compiler (though I highly doubt this, I don't have any evidence that there's something wrong with my code).

Regarding the overload issue, I tried Assert.IsTrue((bool)asDynamic.someValue); but the build still fails, still no error message.

Per @RonBeyer's comment, I had also tried more casting such as below to no avail:

    dynamic asDynamic = (dynamic)obj;
    Assert.IsTrue(((dynamic)asDynamic).someValue);

    Assert.IsTrue((bool)asDynamic.somevalue);

Upon closer inspection, I found that there was an error listed in the Output window:

c:...\DynamicBuildFailTest\UnitTest1.cs(16,33,16,42): error CS0656: Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'

Okay, VS2013 is better at reporting the errors, I will search based on those:

Okay, adding a reference to Microsoft.CSharp fixed the build error, but I will leave this question open because it's presumably an issue with VS2015 that (in my mind) should be resolved.


问:
PHP/Javascript - Instant search, but different?
I have a page with a blank search bar, and then a bunch on contacts below it in a table. Each contact is one div.

I want to be able to filter the contact table as text is entered into the search bar. (So, for instance, if "Fran" was typed in to the search bar, you'd only see contacts with "Fran" in their name. And then all would go back to default if "Fran" was deleted.)

Is this possible? How? (I found an instant search diy guide, but it only worked the way Google does, with a dropdown beneath the search bar.)

答:
I would suggest using this jquery plugin, it requires no ajax or server communication, it simply filters a rendered table according to an input box contents at every keystroke.

Make sure to also include the jquery library in your project along with this plugin for this to work.

ContentLicense: CC BY-SA 2.5


问:
Custom encoding function error
I have created a function that takes two string inputs from the user and returns one string value. It is intended to take one string holding a message or some form of text, and another holding a custom alphabet entered by the user. It will then return the message inputted by the user encoded using the alphabet provided by the user.

example:

```<code>text_to_encode = "abcd"
user_alphabet = "bcdefghijklmnopqrstuvwxyz"

print(encode(text_to_encode, user_alphabet))
</code>```

The encoding of my function works fine, however when it comes to a string containing spaces, it ignores the spaces and prints the encoded message without any spaces.

example:

```<code>text_to_encode = "ab cd"
user_alphabet = "bcdefghijklmnopqrstuvwxyz"

print(encode(text_to_encode, user_alphabet))
</code>```

The output of this would be:  "BCDE" when it SHOULD be "BC DE".

I don't know where I'm going wrong with my code, any help would be appreciated. This is what I have:

```<code>def encode(text_to_encode, user_alphabet):
 text_to_encode_list = []
 for ch in text_to_encode:
  text_to_encode_list.append(ch)

 user_alphabet_list = []
 for ch in user_alphabet:
  user_alphabet_list.append(ch)

 original_alphabet = "abcdefghijklmnopqrstuvwxyz"
 original_alphabet_list = []
 for ch in original_alphabet:
  original_alphabet_list.append(ch)

 result = []
 for value_x in text_to_encode_list:
  flag = False
  for value_y in original_alphabet:
   if value_x == original_alphabet_list[value_y]:
    flag = True
    result.append(user_alphabet_list[value_y])
    break
 if flag == False:
  result.append(value_x)

 encoded_text = ""
 for value in result:
  encoded_text += value

 return encoded_text.upper()
</code>```

答:
This code:

```<code> if flag == False:
  result.append(value_x)
</code>```

Needs to be in the for value_x loop. You have it after the end of the loop, so it only works if the last character in the input isn't found.

Title: Custom encoding function error

Body:
I have created a function that takes two string inputs from the user and returns one string value. It is intended to take one string holding a message or some form of text, and another holding a custom alphabet entered by the user. It will then return the message inputted by the user encoded using the alphabet provided by the user.

example:

text_to_encode = "abcd"
user_alphabet = "bcdefghijklmnopqrstuvwxyz"

print(encode(text_to_encode, user_alphabet))

The encoding of my function works fine, however when it comes to a string containing spaces, it ignores the spaces and prints the encoded message without any spaces.

example:

text_to_encode = "ab cd"
user_alphabet = "bcdefghijklmnopqrstuvwxyz"

print(encode(text_to_encode, user_alphabet))

The output of this would be:  "BCDE" when it SHOULD be "BC DE".

I don't know where I'm going wrong with my code, any help would be appreciated. This is what I have:

def encode(text_to_encode, user_alphabet):
 text_to_encode_list = []
 for ch in text_to_encode:
  text_to_encode_list.append(ch)

 user_alphabet_list = []
 for ch in user_alphabet:
  user_alphabet_list.append(ch)

 original_alphabet = "abcdefghijklmnopqrstuvwxyz"
 original_alphabet_list = []
 for ch in original_alphabet:
  original_alphabet_list.append(ch)

 result = []
 for value_x in text_to_encode_list:
  flag = False
  for value_y in original_alphabet:
   if value_x == original_alphabet_list[value_y]:
    flag = True
    result.append(user_alphabet_list[value_y])
    break
 if flag == False:
  result.append(value_x)

 encoded_text = ""
 for value in result:
  encoded_text += value

 return encoded_text.upper()

Body:
This code:

 if flag == False:
  result.append(value_x)

Needs to be in the for value_x loop. You have it after the end of the loop, so it only works if the last character in the input isn't found.


问:
Extract all values from data in JSON
I have a json response with multiple movie titles in "data". Is there a way to quickly extract them? I need an array with just movie titles.

```<code>{
  "page": "2",
  "per_page": 10,
  "total": 13,
  "total_pages": 2,
  "data": [{
    "Poster": "N/A",
    "Title": "They Call Me Spiderman",
    "Type": "movie",
    "Year": 2016,
    "imdbID": "tt5861236"
  }, {
    "Poster": "N/A",
    "Title": "The Death of Spiderman",
    "Type": "movie",
    "Year": 2015,
    "imdbID": "tt5921428"
  }, {
    "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BZDlmMGQwYmItNTNmOS00OTNkLTkxNTYtNDM3ZWVlMWUyZDIzXkEyXkFqcGdeQXVyMTA5Mzk5Mw@@._V1_SX300.jpg",
    "Title": "Spiderman in Cannes",
    "Type": "movie",
    "Year": 2016,
    "imdbID": "tt5978586"
  }]
}
</code>```

答:
You can use:

newtonsoft.

C# System.dynamic.

C# ExpandoObject Class.

In this way:

```<code>dynamic content = JsonConvert.DeserializeObject<ExpandoObject>(data);
</code>```

Something like this:

```<code>using System;
using System.Dynamic;
using Newtonsoft.Json;

public class Program
{
    public static void Main()
    {
        string data = @"{
  'page': '2',
  'per_page': 10,
  'total': 13,
  'total_pages': 2,
  'data': [{
    'Poster': 'N/A',
    'Title': 'They Call Me Spiderman',
    'Type': 'movie',
    'Year': 2016,
    'imdbID': 'tt5861236'
  }, {
    'Poster': 'N/A',
    'Title': 'The Death of Spiderman',
    'Type': 'movie',
    'Year': 2015,
    'imdbID': 'tt5921428'
  }, {
    'Poster': 'https://images-na.ssl-images-amazon.com/images/M/MV5BZDlmMGQwYmItNTNmOS00OTNkLTkxNTYtNDM3ZWVlMWUyZDIzXkEyXkFqcGdeQXVyMTA5Mzk5Mw@@._V1_SX300.jpg',
    'Title': 'Spiderman in Cannes',
    'Type': 'movie',
    'Year': 2016,
    'imdbID': 'tt5978586'
  }]
}";
        dynamic content = JsonConvert.DeserializeObject<ExpandoObject>(data);
        int i;
        int len = content.data.Count;
        string result = "";
        string[] myArray;
        for (i = 0; i < len; i++)
        {
            result += content.data[i].Title; // Extract the movie title.
            result += ","; // Conact with commas.
        }

        result = result.Substring(0, result.Length - 1);
        myArray = result.Split(','); // Array of string with the movie titles.
        Console.WriteLine(myArray[0]);
    }
}
</code>```

See in action: .NET Fiddle.

Title: Extract all values from data in JSON

Body:
I have a json response with multiple movie titles in "data". Is there a way to quickly extract them? I need an array with just movie titles.

{
  "page": "2",
  "per_page": 10,
  "total": 13,
  "total_pages": 2,
  "data": [{
    "Poster": "N/A",
    "Title": "They Call Me Spiderman",
    "Type": "movie",
    "Year": 2016,
    "imdbID": "tt5861236"
  }, {
    "Poster": "N/A",
    "Title": "The Death of Spiderman",
    "Type": "movie",
    "Year": 2015,
    "imdbID": "tt5921428"
  }, {
    "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BZDlmMGQwYmItNTNmOS00OTNkLTkxNTYtNDM3ZWVlMWUyZDIzXkEyXkFqcGdeQXVyMTA5Mzk5Mw@@._V1_SX300.jpg",
    "Title": "Spiderman in Cannes",
    "Type": "movie",
    "Year": 2016,
    "imdbID": "tt5978586"
  }]
}

Body:
You can use:

newtonsoft.

C# System.dynamic.

C# ExpandoObject Class.

In this way:

dynamic content = JsonConvert.DeserializeObject<ExpandoObject>(data);

Something like this:

using System;
using System.Dynamic;
using Newtonsoft.Json;

public class Program
{
    public static void Main()
    {
        string data = @"{
  'page': '2',
  'per_page': 10,
  'total': 13,
  'total_pages': 2,
  'data': [{
    'Poster': 'N/A',
    'Title': 'They Call Me Spiderman',
    'Type': 'movie',
    'Year': 2016,
    'imdbID': 'tt5861236'
  }, {
    'Poster': 'N/A',
    'Title': 'The Death of Spiderman',
    'Type': 'movie',
    'Year': 2015,
    'imdbID': 'tt5921428'
  }, {
    'Poster': 'https://images-na.ssl-images-amazon.com/images/M/MV5BZDlmMGQwYmItNTNmOS00OTNkLTkxNTYtNDM3ZWVlMWUyZDIzXkEyXkFqcGdeQXVyMTA5Mzk5Mw@@._V1_SX300.jpg',
    'Title': 'Spiderman in Cannes',
    'Type': 'movie',
    'Year': 2016,
    'imdbID': 'tt5978586'
  }]
}";
        dynamic content = JsonConvert.DeserializeObject<ExpandoObject>(data);
        int i;
        int len = content.data.Count;
        string result = "";
        string[] myArray;
        for (i = 0; i < len; i++)
        {
            result += content.data[i].Title; // Extract the movie title.
            result += ","; // Conact with commas.
        }

        result = result.Substring(0, result.Length - 1);
        myArray = result.Split(','); // Array of string with the movie titles.
        Console.WriteLine(myArray[0]);
    }
}

See in action: .NET Fiddle.


问:
How sites framework works?
I am trying to develop a ModelManager with an operation similar to the Sites Framework. Depending on a user's field, the ModelManager returns a queryset. I tried to imitate the operation of the Sites Framework but I do not understand how the SITE_ID is obtained dynamically with this function:

```<code>    def get_queryset(self):
    return super(CurrentSiteManager, self).get_queryset().filter(
        **{self._get_field_name() + '__id': settings.SITE_ID})
</code>```

It seems to be static :/.

I capture the user's field through a Middleware and assign it to request.field. How can I retrieve that field in the ModelManager and perform the query?

答:
I think you are missing the dynamic way to get the current site instance.
From the documentation example:

```<code>from django.contrib.sites.shortcuts import get_current_site

def article_detail(request, article_id):
    try:
        a = Article.objects.get(id=article_id,
            sites__id=get_current_site(request).id)
    except Article.DoesNotExist:
        raise Http404("Article does not exist on this site")
    # ...
</code>```

You should use the get_current_site method to get the current site.

It should be noted that it's not working if you actually define the current site in the settings like SITE_ID=1.

It looks up the current site based on request.get_host() if the SITE_ID setting is not defined.

You should read this part of the documentation actually explaining how django can get the current site in a dynamic fashion:

shortcuts.get_current_site(request)

A function that checks if django.contrib.sites is installed and returns either the current Site object or a RequestSite object based on the request. It looks up the current site based on request.get_host() if the SITE_ID setting is not defined.

Both a domain and a port may be returned by request.get_host() when the Host header has a port explicitly specified, e.g. example.com:80. In such cases, if the lookup fails because the host does not match a record in the database, the port is stripped and the lookup is retried with the domain part only. This does not apply to RequestSite which will always use the unmodified host.

And here is the code of the get_current actually called by get_current_site:

```<code>def get_current(self, request=None):
    """
    Return the current Site based on the SITE_ID in the project's settings.
    If SITE_ID isn't defined, return the site with domain matching
    request.get_host(). The ``Site`` object is cached the first time it's
    retrieved from the database.
    """
    from django.conf import settings
    if getattr(settings, 'SITE_ID', ''):
        site_id = settings.SITE_ID
        return self._get_site_by_id(site_id)
    elif request:
        return self._get_site_by_request(request)

    raise ImproperlyConfigured(
        "You're using the Django \"sites framework\" without having "
        "set the SITE_ID setting. Create a site in your database and "
        "set the SITE_ID setting or pass a request to "
        "Site.objects.get_current() to fix this error."
    )
</code>```

Title: How sites framework works?

Body:
I am trying to develop a ModelManager with an operation similar to the Sites Framework. Depending on a user's field, the ModelManager returns a queryset. I tried to imitate the operation of the Sites Framework but I do not understand how the SITE_ID is obtained dynamically with this function:

    def get_queryset(self):
    return super(CurrentSiteManager, self).get_queryset().filter(
        **{self._get_field_name() + '__id': settings.SITE_ID})

It seems to be static :/.

I capture the user's field through a Middleware and assign it to request.field. How can I retrieve that field in the ModelManager and perform the query?

Body:
I think you are missing the dynamic way to get the current site instance.
From the documentation example:

from django.contrib.sites.shortcuts import get_current_site

def article_detail(request, article_id):
    try:
        a = Article.objects.get(id=article_id,
            sites__id=get_current_site(request).id)
    except Article.DoesNotExist:
        raise Http404("Article does not exist on this site")
    # ...

You should use the get_current_site method to get the current site.

It should be noted that it's not working if you actually define the current site in the settings like SITE_ID=1.

It looks up the current site based on request.get_host() if the SITE_ID setting is not defined.

You should read this part of the documentation actually explaining how django can get the current site in a dynamic fashion:

shortcuts.get_current_site(request)

A function that checks if django.contrib.sites is installed and returns either the current Site object or a RequestSite object based on the request. It looks up the current site based on request.get_host() if the SITE_ID setting is not defined.

Both a domain and a port may be returned by request.get_host() when the Host header has a port explicitly specified, e.g. example.com:80. In such cases, if the lookup fails because the host does not match a record in the database, the port is stripped and the lookup is retried with the domain part only. This does not apply to RequestSite which will always use the unmodified host.

And here is the code of the get_current actually called by get_current_site:

def get_current(self, request=None):
    """
    Return the current Site based on the SITE_ID in the project's settings.
    If SITE_ID isn't defined, return the site with domain matching
    request.get_host(). The ``Site`` object is cached the first time it's
    retrieved from the database.
    """
    from django.conf import settings
    if getattr(settings, 'SITE_ID', ''):
        site_id = settings.SITE_ID
        return self._get_site_by_id(site_id)
    elif request:
        return self._get_site_by_request(request)

    raise ImproperlyConfigured(
        "You're using the Django \"sites framework\" without having "
        "set the SITE_ID setting. Create a site in your database and "
        "set the SITE_ID setting or pass a request to "
        "Site.objects.get_current() to fix this error."
    )


问:
How to Create a Web Form to Collect Data
Just to preface, I do have some programming experience at the basic level (HTML, CSS, Java, JavaScript, Python, VB.net, C++, C#) so I feel comfortable learning whatever I need to learn.

I am trying to create a web form to collect student information to be stored in a database/spreadsheet. I also want to be able to use information entered to send an e-mail to a reference (I am thinking drop-down list to select the recipient, but I might be a little ambitious with that). Then I want the reference to receiving a link to a web form that they would fill out and then that information would be connected back to the student.

For me, this is a huge project, but before I get started, I am looking for advice on what I need to learn. My default for making web pages is DreamWeaver (please don't criticize I am a novice) but am open to suggestions. Can anyone please advice me on what tools I will need to learn to complete this project? Can I use DreamWeaver? Can I use VB.net? Do I need PHP or some specific type of server setup (it's for a school, so the less I do on the server end, the better)?

Thank you for your help.

答:
You should consider using Google Forms. It may be basic, with simple fields and option selectors, but it has most of the capabilities you require. It is also extremely simple to set up.

It has dropdown menus for users to choose from emails.

You can link a Google Sheet to it, so all results are stored in a spreadsheet.


问:
MPI - How to create partial arrays for workers when array initialization value must be constant?
I don't have much experience with C++ or MPI currently, so I assume this will be an easy question to answer.

I want to be able to change the number of processes that can work on my array sort for experimentation purposes, but when I try to declare a partial array for my worker to work on, I receive an error stating that the array size variable, PART, needs to be constant.

Is this from how I calculated or parsed it, or from an MPI mechanic?

```<code>const int arraySize = 10000

int main(int argc, char ** argv)
    {
        MPI_Init(&argc, &argv);

        int rank;
        int size;

        MPI_Comm_rank(MPI_COMM_WORLD, &rank);
        MPI_Comm_size(MPI_COMM_WORLD, &size);

        const int PART = floor(arraySize / size);

        auto start = std::chrono::high_resolution_clock::now(); //start timer

        //================================ WORKER PROCESSES ===============================
        if (rank != 0)
        {
            int tmpArray[PART];       //HERE IS MY PROBLEM

            MPI_Recv(&tmpArray, PART, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);    //recieve data into local initalized array
            qsort(&tmpArray[0], PART, sizeof(int), compare);                                // quick sort
            MPI_Send(&tmpArray, PART, MPI_INT, 0, 0, MPI_COMM_WORLD);                       //send sorted array back to rank 0
        }
</code>```

答:
If the size of an array is determined at runtime, as in your case, this would give a variable length array, which is supported in C, but not in standard C++.
So in C++, the size of an array needs to be a (compile time) constant.

To overcome this, you'll have to use dynamic memory allocation. This can be achieved either through "classic C" functions malloc and free (which are rarely used in C++), through their C++-pendants new and delete (or new[] and delete[]), or - the preferred way - through the use of container objects like, for example, std::vector<int> that encapsulate this memory allocation issues for you.

Body:
I don't have much experience with C++ or MPI currently, so I assume this will be an easy question to answer.

I want to be able to change the number of processes that can work on my array sort for experimentation purposes, but when I try to declare a partial array for my worker to work on, I receive an error stating that the array size variable, PART, needs to be constant.

Is this from how I calculated or parsed it, or from an MPI mechanic?

const int arraySize = 10000

int main(int argc, char ** argv)
    {
        MPI_Init(&argc, &argv);

        int rank;
        int size;

        MPI_Comm_rank(MPI_COMM_WORLD, &rank);
        MPI_Comm_size(MPI_COMM_WORLD, &size);

        const int PART = floor(arraySize / size);

        auto start = std::chrono::high_resolution_clock::now(); //start timer

        //================================ WORKER PROCESSES ===============================
        if (rank != 0)
        {
            int tmpArray[PART];       //HERE IS MY PROBLEM

            MPI_Recv(&tmpArray, PART, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);    //recieve data into local initalized array
            qsort(&tmpArray[0], PART, sizeof(int), compare);                                // quick sort
            MPI_Send(&tmpArray, PART, MPI_INT, 0, 0, MPI_COMM_WORLD);                       //send sorted array back to rank 0
        }


问:
Different profile per spring boot application instance in cloud foundy
Is it possible to programmatically set a different profile for every instance of a spring boot application deployed in cloud foundry using for example ConfigurableEnvironment and cloud foundry instance index?</p>

答:
I would suggest that you look into using tasks.

https://docs.cloudfoundry.org/devguide/using-tasks.html

Here's roughly how this would work.

Run cf push to deploy your application to CF.  If you do not actually have an application to run, that is OK.  You just need to push the app and start it once so that it stages and creates a droplet.  After that, you can run cf stop to shutdown the instance (note: cf push --no-start won't work, because the app needs to stage at least once).

Run cf run-task <app> <command>.  This is where you kick off your batch jobs.  The <command> argument is going to be the full command to run your batch job.  In this, you can include an argument to indicate the profiles that should be used.  Ex:  --spring.profiles.active=dev,hsqldb.

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html

You need to use the full or relative path to the java exceutable because the Java buildpack does not put it onto the path.  If you wanted to run a task that printed the version of the JVM, you'd use this command '.java-buildpack/open_jdk_jre/bin/java -version'.

Ex: cf run-task <app> '.java-buildpack/open_jdk_jre/bin/java -version'

See this SO post though for drawbacks of hardcoding the path to the Java executable in your command.  My suggestion would be to take the command that's listed when you run cf push and modify to your needs.


问:
When using sum case when 000 converts only 0
In table1 there is data like:

```<code>id  date        value
1   10/09       500
2   10/09       400
3   10/09       300
4   11/09       200
5   11/09       100
6   11/09       000
</code>```

I want to set the data above within the show table:

```<code>date  | d1  |   d2   |  d3  |   d4  |   d5    | d6
----------------------------------------------------
10/09 | 500 |   400  |  300 |       |         |
----------------------------------------------------
11/09 |     |        |      |   200 |   100 |   000
----------------------------------------------------
</code>```

I am using the following sql query.

```<code>select date,
       sum(case when id = 1 then value end) as d1,
       sum(case when id = 2 then value end) as d2,
       sum(case when id = 3 then value end) as d3,
       sum(case when id = 4 then value end) as d4,
       sum(case when id = 5 then value end) as d5,
       sum(case when id = 6 then value end) as d6
from table1 GROUP BY date;
</code>```

My problem arises when I am using the above query, In the output table, for d6 column instead of 000 the value becomes only 0. How to overcome this problem?

Check SQL Fiddle here

答:
If this is a string value, then perhaps max() will do:

```<code>select date,
       max(case when id = 1 then value end) as d1,
       max(case when id = 2 then value end) as d2,
       max(case when id = 3 then value end) as d3,
       max(case when id = 4 then value end) as d4,
       max(case when id = 5 then value end) as d5,
       max(case when id = 6 then value end) as d6
from table1
group by date;
</code>```

You don't seem to actually want a sum().

Here is a SQL Fiddle.  Notice that the values have to be inserted into the column as strings.

Body:
In table1 there is data like:

id  date        value
1   10/09       500
2   10/09       400
3   10/09       300
4   11/09       200
5   11/09       100
6   11/09       000

I want to set the data above within the show table:

date  | d1  |   d2   |  d3  |   d4  |   d5    | d6
----------------------------------------------------
10/09 | 500 |   400  |  300 |       |         |
----------------------------------------------------
11/09 |     |        |      |   200 |   100 |   000
----------------------------------------------------

I am using the following sql query.

select date,
       sum(case when id = 1 then value end) as d1,
       sum(case when id = 2 then value end) as d2,
       sum(case when id = 3 then value end) as d3,
       sum(case when id = 4 then value end) as d4,
       sum(case when id = 5 then value end) as d5,
       sum(case when id = 6 then value end) as d6
from table1 GROUP BY date;

My problem arises when I am using the above query, In the output table, for d6 column instead of 000 the value becomes only 0. How to overcome this problem?

Check SQL Fiddle here

Body:
If this is a string value, then perhaps max() will do:

select date,
       max(case when id = 1 then value end) as d1,
       max(case when id = 2 then value end) as d2,
       max(case when id = 3 then value end) as d3,
       max(case when id = 4 then value end) as d4,
       max(case when id = 5 then value end) as d5,
       max(case when id = 6 then value end) as d6
from table1
group by date;

You don't seem to actually want a sum().

Here is a SQL Fiddle.  Notice that the values have to be inserted into the column as strings.


答: You can try jQuery auto complete plugin for the same</p>

Title: PHP/Javascript - Instant search, but different?

Body:
I have a page with a blank search bar, and then a bunch on contacts below it in a table. Each contact is one div.

I want to be able to filter the contact table as text is entered into the search bar. (So, for instance, if "Fran" was typed in to the search bar, you'd only see contacts with "Fran" in their name. And then all would go back to default if "Fran" was deleted.)

Is this possible? How? (I found an instant search diy guide, but it only worked the way Google does, with a dropdown beneath the search bar.)


问:
PyGObject GtkFileChooserDialog default button
When I create a GtkFileChooserDialog in Glade and then connect that to a Python class using Gtk.Builder, how do I tell it which is the default button?

Currently, my 'Open' button is the stock gtk-open button and when it's clicked, run() returns 0.  But double-clicking on a file or selecting a file and pressing Enter doesn't do anything.  As far as I can see, this is because the dialog doesn't know what the default button is in Glade, possibly because the 'Open' button isn't using one of GTK_RESPONSE_ACCEPT, GTK_RESPONSE_OK, GTK_RESPONSE_YES or GTK_RESPONSE_APPLY as its response code; but how do I set the response code to one of these when the button is created through Glade?

I'm using Gtk 3, Python 3 and PyGObject (ie gi.repository).

Edit: Here is the relevant bit of the Glade file:

```<code>  <object class="GtkFileChooserDialog" id="file_chooser">
    <property name="can_focus">False</property>
    <property name="modal">True</property>
    <property name="type_hint">dialog</property>
    <property name="select_multiple">True</property>
    <child internal-child="vbox">
      <object class="GtkBox">
        <property name="can_focus">False</property>
        <property name="orientation">vertical</property>
        <property name="spacing">2</property>
        <child internal-child="action_area">
          <object class="GtkButtonBox">
            <property name="can_focus">False</property>
            <property name="layout_style">end</property>
            <child>
              <object class="GtkButton" id="button1">
                <property name="label">gtk-cancel</property>
                <property name="visible">True</property>
                <property name="can_focus">True</property>
                <property name="receives_default">True</property>
                <property name="use_stock">True</property>
              </object>
              <packing>
                <property name="expand">True</property>
                <property name="fill">True</property>
                <property name="position">0</property>
              </packing>
            </child>
            <child>
              <object class="GtkButton" id="button2">
                <property name="label">gtk-open</property>
                <property name="visible">True</property>
                <property name="can_focus">True</property>
                <property name="receives_default">True</property>
                <property name="use_stock">True</property>
              </object>
              <packing>
                <property name="expand">True</property>
                <property name="fill">True</property>
                <property name="position">1</property>
              </packing>
            </child>
          </object>
          <packing>
            <property name="expand">False</property>
            <property name="fill">False</property>
            <property name="position">0</property>
          </packing>
        </child>
        <child>
          <placeholder/>
        </child>
      </object>
    </child>
    <action-widgets>
      <action-widget response="-1">button1</action-widget>
      <action-widget response="-5">button2</action-widget>
    </action-widgets>
  </object>
</code>```

答:
You can set the response id to a button in Glade. (General>Response ID) The response types are here.

GTK_RESPONSE_NONE    is -1

GTK_RESPONSE_REJECT  is -2

GTK_RESPONSE_ACCEPT  is -3

... so on until ...

GTK_RESPONSE_HELP    is -11

Body:
When I create a GtkFileChooserDialog in Glade and then connect that to a Python class using Gtk.Builder, how do I tell it which is the default button?

Currently, my 'Open' button is the stock gtk-open button and when it's clicked, run() returns 0.  But double-clicking on a file or selecting a file and pressing Enter doesn't do anything.  As far as I can see, this is because the dialog doesn't know what the default button is in Glade, possibly because the 'Open' button isn't using one of GTK_RESPONSE_ACCEPT, GTK_RESPONSE_OK, GTK_RESPONSE_YES or GTK_RESPONSE_APPLY as its response code; but how do I set the response code to one of these when the button is created through Glade?

I'm using Gtk 3, Python 3 and PyGObject (ie gi.repository).

Edit: Here is the relevant bit of the Glade file:

  <object class="GtkFileChooserDialog" id="file_chooser">
    <property name="can_focus">False</property>
    <property name="modal">True</property>
    <property name="type_hint">dialog</property>
    <property name="select_multiple">True</property>
    <child internal-child="vbox">
      <object class="GtkBox">
        <property name="can_focus">False</property>
        <property name="orientation">vertical</property>
        <property name="spacing">2</property>
        <child internal-child="action_area">
          <object class="GtkButtonBox">
            <property name="can_focus">False</property>
            <property name="layout_style">end</property>
            <child>
              <object class="GtkButton" id="button1">
                <property name="label">gtk-cancel</property>
                <property name="visible">True</property>
                <property name="can_focus">True</property>
                <property name="receives_default">True</property>
                <property name="use_stock">True</property>
              </object>
              <packing>
                <property name="expand">True</property>
                <property name="fill">True</property>
                <property name="position">0</property>
              </packing>
            </child>
            <child>
              <object class="GtkButton" id="button2">
                <property name="label">gtk-open</property>
                <property name="visible">True</property>
                <property name="can_focus">True</property>
                <property name="receives_default">True</property>
                <property name="use_stock">True</property>
              </object>
              <packing>
                <property name="expand">True</property>
                <property name="fill">True</property>
                <property name="position">1</property>
              </packing>
            </child>
          </object>
          <packing>
            <property name="expand">False</property>
            <property name="fill">False</property>
            <property name="position">0</property>
          </packing>
        </child>
        <child>
          <placeholder/>
        </child>
      </object>
    </child>
    <action-widgets>
      <action-widget response="-1">button1</action-widget>
      <action-widget response="-5">button2</action-widget>
    </action-widgets>
  </object>


问:
Django : migration success but not creating new table
I've been using django migration to handle database. recently, I split session into two, one is for reading and the other one is for writing. After done this, I made new migration file that adding new table and run it. It was successful,

```<code>Operations to perform:
Apply all migrations: food
Running migrations:
Applying food.0107_auto_20171116_0849... OK
</code>```

However, when I checked mysql database using shell, there was no new table. I deleted django migrations history and attempted few times more but the result was same. It says migration applied but there was no new table. This is my migration file

```<code># -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-11-16 08:49
from __future__ import unicode_literals

from django.db import migrations, models
import uuid

class Migration(migrations.Migration):

    dependencies = [
        ('bubi', '0106_auto_20171110_1452'),
    ]

    operations = [
        migrations.CreateModel(
           name='FoodHistory',
              fields=[
                  ('id', models.UUIDField(default=uuid.uuid4, primary_key=True, serialize=False)),
                  ('date', models.DateField(verbose_name='updated date')),
        ],
        options={
            'verbose_name': 'food updated date',
            'verbose_name_plural': 'food updated date',
        },
    ),
]
</code>```

I wonder if splited session may affects to do migrations. thanks!

EDIT

I added my local_settings.py

```<code>DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'food',
    'HOST': '127.0.0.1',
    'USER': 'apple',
    'PASSWORD': 'apple'
},
'read': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'food',
    'HOST': '127.0.0.1',
    'USER': 'apple',
    'PASSWORD': 'apple'
},
'write': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'food',
    'HOST': '127.0.0.1',
    'USER': 'apple',
    'PASSWORD': 'apple'
}
}
</code>```

答:
You should set database name to migrate others database:</p>

```<code>./manage.py migrate --database=write
</code>```

Body:
I've been using django migration to handle database. recently, I split session into two, one is for reading and the other one is for writing. After done this, I made new migration file that adding new table and run it. It was successful,

Operations to perform:
Apply all migrations: food
Running migrations:
Applying food.0107_auto_20171116_0849... OK

However, when I checked mysql database using shell, there was no new table. I deleted django migrations history and attempted few times more but the result was same. It says migration applied but there was no new table. This is my migration file

# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-11-16 08:49
from __future__ import unicode_literals

from django.db import migrations, models
import uuid

class Migration(migrations.Migration):

    dependencies = [
        ('bubi', '0106_auto_20171110_1452'),
    ]

    operations = [
        migrations.CreateModel(
           name='FoodHistory',
              fields=[
                  ('id', models.UUIDField(default=uuid.uuid4, primary_key=True, serialize=False)),
                  ('date', models.DateField(verbose_name='updated date')),
        ],
        options={
            'verbose_name': 'food updated date',
            'verbose_name_plural': 'food updated date',
        },
    ),
]

I wonder if splited session may affects to do migrations. thanks!

EDIT

I added my local_settings.py

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'food',
    'HOST': '127.0.0.1',
    'USER': 'apple',
    'PASSWORD': 'apple'
},
'read': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'food',
    'HOST': '127.0.0.1',
    'USER': 'apple',
    'PASSWORD': 'apple'
},
'write': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'food',
    'HOST': '127.0.0.1',
    'USER': 'apple',
    'PASSWORD': 'apple'
}
}

Body:
You should set database name to migrate others database:

./manage.py migrate --database=write


答: auto tmpArray = std::make_unique<int[]>(PART);

Title: MPI - How to create partial arrays for workers when array initialization value must be constant?


问:
How can we refresh an array displayed in an HTML element after an item is pushed to it?
This file is a simple to do list generator. it starts with three sample items being displayed in a div from a JS array. onclick of button one "push" a prompt comes up and whatever the user adds gets added to the array in JS. this works fine as per the console. the second button "shift" pulls the first item off the list (in traditional to do list style) as the user does one item at a time.the push and shift button both run corresponding JS functions which do the work perfectly. in the console the array is updated each time wither is used.

my question: how do i get the div to refresh the array "toDoListJoined" once a modification is made to the array "toDoList" thru the buttons???

```<code> <!DOCTYPE html>
 <html lang="en">

 <head>
 <meta charset="utf-8" />
 <title>JavaScript To Do List</title>
 </head>

 <body id="home">
   <button id="push" onclick="pushPrompt()">Add something to the end of your list</button>
   <button id="shift" onclick="shiftIt()">Remove the first item from your list</button>

 <p id="listPlace">
 <!--Here's where the magic happens-->
 </p>

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
 <script type="text/javascript">
   let toDoList = ["sample item 1", "sample item 2", "sample item 3"];
   let toDoListJoined = toDoList.join("<br>");
   let addItem = "";

document.getElementById("listPlace").innerHTML = toDoListJoined;

function pushPrompt() {
  addItem = prompt("What is the item you want to add to your list?", "Sample item");
  toDoList.push(addItem);
}

function shiftIt() {
  toDoList.shift();
}
 </script>

 </body>

</html>
</code>```

答:
You can create a new method so that the html is updated:</p>

```<code>//create a new method on the Array to push the item and update the HTML.
toDoList.pushAndUpdate= function(item) {
    //push the item into the array using the prototype push method.
    Array.prototype.push.call(this, item);
    //update the html of my element.
    document.getElementById("listPlace").innerHTML= this.join("<br>");
}
</code>```

Body:
This file is a simple to do list generator. it starts with three sample items being displayed in a div from a JS array. onclick of button one "push" a prompt comes up and whatever the user adds gets added to the array in JS. this works fine as per the console. the second button "shift" pulls the first item off the list (in traditional to do list style) as the user does one item at a time.the push and shift button both run corresponding JS functions which do the work perfectly. in the console the array is updated each time wither is used.

my question: how do i get the div to refresh the array "toDoListJoined" once a modification is made to the array "toDoList" thru the buttons???

 <!DOCTYPE html>

 <meta charset="utf-8" />
 <title>JavaScript To Do List</title>

   <button id="push" onclick="pushPrompt()">Add something to the end of your list</button>
   <button id="shift" onclick="shiftIt()">Remove the first item from your list</button>

Body:
You can create a new method so that the html is updated:

//create a new method on the Array to push the item and update the HTML.
toDoList.pushAndUpdate= function(item) {
    //push the item into the array using the prototype push method.
    Array.prototype.push.call(this, item);
    //update the html of my element.
    document.getElementById("listPlace").innerHTML= this.join("<br>");
}


问:
Red5: save incoming stream
We use Red5 server for video broadcasting. But periodically we have some problems with it.

Is it possible to save incoming Red5's video stream to file? It is useful to reproduce Red5 problems occurred during streaming.

答:
You can do this in two ways, one is by publishing in record mode and the other is by setting auto record in the configuration for Red5. The first option will only record the stream you are publishing and the second will record all streams no matter what mode is supplied at publishing time.

To set the server option, open your conf/red5.properties file and locate this entry, set it to true and restart red5:broadcaststream.auto.record=false

Title: Red5: save incoming stream


问:
iOS - Arrange subviews in circular shape
I have a  bunch of views in my app. I would like to arrange them in a circular shape and change their center depending on the number of views present.

So, if there are 3 views they would look like a triangle, but would still form a circle. If there are 4 it would look like a square but still form a circle, and so on...

In short, the centers of all views would sit on a imaginary circle.

Any suggestions?

答:
Here's a Swift 3 version of the accepted answer, as an UIView extension with offset arguments:</p>

```<code>public extension UIView {
  public func distributeSubviewsInACircle(xOffset: CGFloat, yOffset: CGFloat) {
      let center = CGPoint(x: self.bounds.size.width / 2, y: self.bounds.size.height / 2)
      let radius: CGFloat = self.bounds.size.width / 2
      let angleStep: CGFloat = 2 * CGFloat(Double.pi) / CGFloat(self.subviews.count)
      var count = 0
      for subview in self.subviews {
          let xPos = center.x + CGFloat(cosf(Float(angleStep) * Float(count))) * (radius - xOffset)
          let yPos = center.y + CGFloat(sinf(Float(angleStep) * Float(count))) * (radius - yOffset)
          subview.center = CGPoint(x: xPos, y: yPos)
          count += 1
      }
  }
}
</code>```

Body:
Here's a Swift 3 version of the accepted answer, as an UIView extension with offset arguments:

public extension UIView {
  public func distributeSubviewsInACircle(xOffset: CGFloat, yOffset: CGFloat) {
      let center = CGPoint(x: self.bounds.size.width / 2, y: self.bounds.size.height / 2)
      let radius: CGFloat = self.bounds.size.width / 2
      let angleStep: CGFloat = 2 * CGFloat(Double.pi) / CGFloat(self.subviews.count)
      var count = 0
      for subview in self.subviews {
          let xPos = center.x + CGFloat(cosf(Float(angleStep) * Float(count))) * (radius - xOffset)
          let yPos = center.y + CGFloat(sinf(Float(angleStep) * Float(count))) * (radius - yOffset)
          subview.center = CGPoint(x: xPos, y: yPos)
          count += 1
      }
  }
}


问:
Change Badge icon when notified
I'm using Xamarin Forms and I manage to send notifications to my applications in both iOS and Android using Firebase. I want to change the Badge icon every time a notification arrives, with the application in the background.
Similar to Twitter or Whatsapp.

How can I change the Badge of my application when my application is in the background?

答: I used MessagingCenter in Xamarin before. It is a publisher and subscriber event that you can use.</p>

Title: Change Badge icon when notified


问:
How to Automate QR Codes in Excel 2016
I need to generate a whole sheet of QR codes, (eventually about 1000), i am trying to automate the generation in Excel 2016, i currently have a sheet set up and have a URL to the generater using Google Apis, I just change the ID number in the url for it to take me to make the next code and take me to the correct place. I dont want to have to manually go and get the code and copy it into my document for each one.

Does anyone have any ideas that may help me out, i have set up the first 10 and this can be seen on the screenshot attached.

enter image description here

Thanks

答:
This is the closest thing I could find with what you are trying to do.

https://sites.google.com/site/e90e50fx/home/generate-qrcode-with-excel

It's generate a QR code image but I can't get it to do it for multiple cell values.

Title: How to Automate QR Codes in Excel 2016


问:
PL/SQL exception handling in function
I am trying to generate DIVIDE_BY_ZERO exception in my oracle PL/SQL program. I using function but when I run my program I am getting error which is shown below. Can anyone tell me what is wrong in my program ?

code:

```<code> CREATE OR REPLACE
PACKAGE CALCULATOR AS

  FUNCTION AddNumber(addend IN Number, Addend2 IN Number) RETURN NUMBER;
  FUNCTION DivNumber(divend IN Number, divend2 IN Number) RETURN NUMBER;

END CALCULATOR;
/

CREATE OR REPLACE
PACKAGE BODY CALCULATOR AS

  FUNCTION AddNumber(addend IN Number, Addend2 IN Number) RETURN NUMBER AS
  BEGIN
     return addend + addend2;

  END AddNumber;

  FUNCTION DivNumber(divend IN Number, divend2 IN Number) RETURN NUMBER AS
  BEGIN
         return divend / divend2;
         EXCEPTION
         WHEN ZERO_DIVIDE THEN
         NULL;
  END DivNumber;

END CALCULATOR;
/

select calculator.AddNumber(3,4) from dual;
select calculator.DivNumber(12,0) from dual;
</code>```

output:

答:
IMO you should never write code which throws an avoidable exception. There may be times when you can't avoid raising an exception but in this case you can. I suggest that you rewrite your function as follows:

```<code>FUNCTION DivNumber(numerator IN Number, denominator IN Number) RETURN NUMBER AS
BEGIN
  IF NVL(denominator, 0) <> 0 THEN
     return numerator / denominator;
  ELSE
    RETURN NULL;
  END IF;
END DivNumber;
</code>```

Best of luck.

Title: PL/SQL exception handling in function

Body:
I am trying to generate DIVIDE_BY_ZERO exception in my oracle PL/SQL program. I using function but when I run my program I am getting error which is shown below. Can anyone tell me what is wrong in my program ?

code:

 CREATE OR REPLACE
PACKAGE CALCULATOR AS

  FUNCTION AddNumber(addend IN Number, Addend2 IN Number) RETURN NUMBER;
  FUNCTION DivNumber(divend IN Number, divend2 IN Number) RETURN NUMBER;

END CALCULATOR;
/

CREATE OR REPLACE
PACKAGE BODY CALCULATOR AS

  FUNCTION AddNumber(addend IN Number, Addend2 IN Number) RETURN NUMBER AS
  BEGIN
     return addend + addend2;

  END AddNumber;

  FUNCTION DivNumber(divend IN Number, divend2 IN Number) RETURN NUMBER AS
  BEGIN
         return divend / divend2;
         EXCEPTION
         WHEN ZERO_DIVIDE THEN
         NULL;
  END DivNumber;

END CALCULATOR;
/

select calculator.AddNumber(3,4) from dual;
select calculator.DivNumber(12,0) from dual;

output:

Body:
IMO you should never write code which throws an avoidable exception. There may be times when you can't avoid raising an exception but in this case you can. I suggest that you rewrite your function as follows:

FUNCTION DivNumber(numerator IN Number, denominator IN Number) RETURN NUMBER AS
BEGIN
  IF NVL(denominator, 0) <> 0 THEN
     return numerator / denominator;
  ELSE
    RETURN NULL;
  END IF;
END DivNumber;

Best of luck.


问:
Excel - 2 data validation in the same cell
I want to combine 2 data validation into one cell. I can do it with separate cell, but had no idea on how to combining them.

First Validation: a list contains certain options for user to choose, and an others if it is not inside the list.

When Others is being selected, User can input their own data.

First Validation Setting

Second Validation: a cell that needs to starts with a certain format, else error message will appear. e.g. users can are only to allow to input in this format ABC xxxxx

Second Validation Setting

I want to combined the list validation and the custom validation to one cell F2. So users can choose either the options given, or choose other and input the data they want, but the format must be ABC xxxx.

Any suggestions and helps are appreciated. Thanks in advance

答:
Thanks @pnuts & @ YowE3K, with the reference from here. I had successfully achieve what I want.

Solution: Right Click F2 -> Format cells -> Custom -> Type "ABC "@


问:
How to launch html using Chrome at "--allow-file-access-from-files" mode?
I have the same situation with HERE

And to solve this problem I have to launch html file using Chrome at "--allow-file-access-from-files" mode.
I tried next steps many times, but it doesn't work.

start cmd under windows 7

direct to chrome.exe folder

do this chrome --allow-file-access-from-files file:///C:/test%20-%203.html

答: You may want to try Web Server for Chrome, which serves web pages from a local folder using HTTP. It's simple to use and would avoid the flag, which, as someone mentioned above, might make your file system vulnerable.

ContentLicense: CC BY-SA 4.0


问:
SQL - Flag consecutive value change in column
I'm going to do my best to explain my issue.

I have a dataset that looks similar to the following:

```<code>Row#    CusCode Status
1   100101  Green
2   100101  Green
3   100101  Red
4   100101  Amber
5   100101  Amber
6   100101  Green
7   100101  Red
8   100101  Red
9   100101  Red
10  200909  Red
11  200909  Amber
12  200909  Green
13  200909  Red
</code>```

I am trying to get this view as a next step:

```<code>Row#    CusCode Status  Required
1   100101  Green   1
2   100101  Green   1
3   100101  Red 2
4   100101  Amber   3
5   100101  Amber   3
6   100101  Green   4
7   100101  Red 5
8   100101  Red 5
9   100101  Red 5
10  200909  Red 1
11  200909  Amber   2
12  200909  Green   3
13  200909  Red 4
</code>```

Last step is for the dataset to look as follows:

```<code>CusCode Status  Required
100101  Green   1
100101  Red 2
100101  Amber   3
100101  Green   4
100101  Red 5
200909  Red 1
200909  Amber   2
200909  Green   3
200909  Red 4
</code>```

Please note the following:

I require that a counter be created based on the status change, irrespective if the status changes to an earlier status, intention is to flag consecutive duplicate records - Table 2 provides an illustration of this.

The dataset contains multiple records

The order in which the Status is displayed is most important and must output in the same order (Table 3 provides this view).

Your assistance will be greatly appreciated. :)

答:
For the first phase of this I would use LEAD() and then this allows me to locate each row that does (or does not) have a change in status. So then delete the unwanted rows, and voila! you have your end result by using ROW_NUMBER() on the surviving rows.

Regarding the "original order". You should never rely on the rows of a table being stored in a predictable order. Below I have used a "trick" to fool the over clause to apply an order that in effect does nothing and so "hopefully" the rows will be in the desired "original order", however this cannot be guaranteed. In practice it works, but you really should not rely on it. Add a datetime/datetime2 column as each row is created.

SQL Fiddle

MS SQL Server 2014 Schema Setup:

```<code>CREATE TABLE Table1
    ([RowNo] int, [CusCode] int, [Status] varchar(5))
;

INSERT INTO Table1
    ([RowNo], [CusCode], [Status])
VALUES
    (1, 100101, 'Green'),
    (2, 100101, 'Green'),
    (3, 100101, 'Red'),
    (4, 100101, 'Amber'),
    (5, 100101, 'Amber'),
    (6, 100101, 'Green'),
    (7, 100101, 'Red'),
    (8, 100101, 'Red'),
    (9, 100101, 'Red'),
    (10, 200909, 'Red'),
    (11, 200909, 'Amber'),
    (12, 200909, 'Green'),
    (13, 200909, 'Red')
;
</code>```

Delete Query:

```<code>with CTE as (
  select
       *
     , lead(status) over(partition by CusCode order by (select 1)) nxt_status
  from table1
  )
delete from CTE
where status = nxt_status
;
</code>```

Inspect Query

```<code>with CTE as (
  select
       *
     , row_number() over(partition by CusCode order by (select 1)) rn
  from table1
  )
select
*
from CTE
;
</code>```

Results:

```<code>| RowNo | CusCode | Status | rn |
|-------|---------|--------|----|
|     2 |  100101 |  Green |  1 |
|     3 |  100101 |    Red |  2 |
|     5 |  100101 |  Amber |  3 |
|     6 |  100101 |  Green |  4 |
|     9 |  100101 |    Red |  5 |
|    10 |  200909 |    Red |  1 |
|    11 |  200909 |  Amber |  2 |
|    12 |  200909 |  Green |  3 |
|    13 |  200909 |    Red |  4 |
</code>```

Body:
I'm going to do my best to explain my issue.

I have a dataset that looks similar to the following:

Row#    CusCode Status
1   100101  Green
2   100101  Green
3   100101  Red
4   100101  Amber
5   100101  Amber
6   100101  Green
7   100101  Red
8   100101  Red
9   100101  Red
10  200909  Red
11  200909  Amber
12  200909  Green
13  200909  Red

I am trying to get this view as a next step:

Row#    CusCode Status  Required
1   100101  Green   1
2   100101  Green   1
3   100101  Red 2
4   100101  Amber   3
5   100101  Amber   3
6   100101  Green   4
7   100101  Red 5
8   100101  Red 5
9   100101  Red 5
10  200909  Red 1
11  200909  Amber   2
12  200909  Green   3
13  200909  Red 4

Last step is for the dataset to look as follows:

CusCode Status  Required
100101  Green   1
100101  Red 2
100101  Amber   3
100101  Green   4
100101  Red 5
200909  Red 1
200909  Amber   2
200909  Green   3
200909  Red 4

Please note the following:

I require that a counter be created based on the status change, irrespective if the status changes to an earlier status, intention is to flag consecutive duplicate records - Table 2 provides an illustration of this.

The dataset contains multiple records

The order in which the Status is displayed is most important and must output in the same order (Table 3 provides this view).

Your assistance will be greatly appreciated. :)

Body:
For the first phase of this I would use LEAD() and then this allows me to locate each row that does (or does not) have a change in status. So then delete the unwanted rows, and voila! you have your end result by using ROW_NUMBER() on the surviving rows.

Regarding the "original order". You should never rely on the rows of a table being stored in a predictable order. Below I have used a "trick" to fool the over clause to apply an order that in effect does nothing and so "hopefully" the rows will be in the desired "original order", however this cannot be guaranteed. In practice it works, but you really should not rely on it. Add a datetime/datetime2 column as each row is created.

SQL Fiddle

MS SQL Server 2014 Schema Setup:

CREATE TABLE Table1
    ([RowNo] int, [CusCode] int, [Status] varchar(5))
;

INSERT INTO Table1
    ([RowNo], [CusCode], [Status])
VALUES
    (1, 100101, 'Green'),
    (2, 100101, 'Green'),
    (3, 100101, 'Red'),
    (4, 100101, 'Amber'),
    (5, 100101, 'Amber'),
    (6, 100101, 'Green'),
    (7, 100101, 'Red'),
    (8, 100101, 'Red'),
    (9, 100101, 'Red'),
    (10, 200909, 'Red'),
    (11, 200909, 'Amber'),
    (12, 200909, 'Green'),
    (13, 200909, 'Red')
;

Delete Query:

with CTE as (
  select
       *
     , lead(status) over(partition by CusCode order by (select 1)) nxt_status
  from table1
  )
delete from CTE
where status = nxt_status
;

Inspect Query

with CTE as (
  select
       *
     , row_number() over(partition by CusCode order by (select 1)) rn
  from table1
  )
select
*
from CTE
;

Results:

| RowNo | CusCode | Status | rn |
|-------|---------|--------|----|
|     2 |  100101 |  Green |  1 |
|     3 |  100101 |    Red |  2 |
|     5 |  100101 |  Amber |  3 |
|     6 |  100101 |  Green |  4 |
|     9 |  100101 |    Red |  5 |
|    10 |  200909 |    Red |  1 |
|    11 |  200909 |  Amber |  2 |
|    12 |  200909 |  Green |  3 |
|    13 |  200909 |    Red |  4 |


问:
How can I check if a given member_descriptor object holds a value for a reference instance
I'm working on an advanced interface that works mildly similar to Blender's property definitions.

what I'm doing to handle data is overwriting a member_descriptor object with a property that keeps reference of the member_descriptor's methods internally.

```<code>class Object(object):
    """an example"""
    __slots__ = ['item']
    def __init__(obj):
        obj.item = static_object() # stored in the descriptor and updated

def reassign():
    dscget = Object.item.__get__
    dscset = Object.item.__set__

    def setter(obj, val):
        """my problem lies here"""
        if hasattr(Object, 'item'): # this will create an infinite recursion loop
            dscget(obj,Object).update(val)
        elif val.__class__ is static_object: dscset(obj,val)
        else: print( 'FIXME: Object.item cannot be initialized with type %s'%val.__class__ )

    Object.item = property( dscget, setter )
</code>```

so since hasattr checks the property, which checks the property, and so on, what would be a more efficient and performative way of checking if the descriptor holds the required item??

I don't want to use try because except AttributeError is super slow...

for example:

```<code>    def setter(obj, val):
        """the slow method"""
        try: dscget(obj,Object).update(val)
        except AttributeError: # because the descriptor holds nothing.
            if val.__class__ is static_object: dscset(obj,val)
            else: print( 'FIXME: Object.item cannot be initialized with type %s'%val.__class__ )
</code>```

is there an alternate method, or is this poop the best I got??

答:
so after some bashes to the head, and talking with a bpy dev who told me to back up and think of a better approach, I've settled on this:

```<code>def reassign():

    class Object(object):
        __slots__ = ['item']
        def __new__(cls):
            obj = object.__new__(cls)
            dscset(obj,static_object())
            return obj
    globals()['Object'] = Object

    dscget = Object.item.__get__
    dscset = Object.item.__set__

    def setter(obj, val): dscget(obj,Object).update(val) # leave type checking to the static object
    Object.item = property( dscget, setter )
reassign()
del reassign
# __new__.__closure__ holds the descriptor setter(s)
</code>```

so no need for all the verification BS in the question :D

Body:
I'm working on an advanced interface that works mildly similar to Blender's property definitions.

what I'm doing to handle data is overwriting a member_descriptor object with a property that keeps reference of the member_descriptor's methods internally.

class Object(object):
    """an example"""
    __slots__ = ['item']
    def __init__(obj):
        obj.item = static_object() # stored in the descriptor and updated

def reassign():
    dscget = Object.item.__get__
    dscset = Object.item.__set__

    def setter(obj, val):
        """my problem lies here"""
        if hasattr(Object, 'item'): # this will create an infinite recursion loop
            dscget(obj,Object).update(val)
        elif val.__class__ is static_object: dscset(obj,val)
        else: print( 'FIXME: Object.item cannot be initialized with type %s'%val.__class__ )

    Object.item = property( dscget, setter )

so since hasattr checks the property, which checks the property, and so on, what would be a more efficient and performative way of checking if the descriptor holds the required item??

I don't want to use try because except AttributeError is super slow...

for example:

    def setter(obj, val):
        """the slow method"""
        try: dscget(obj,Object).update(val)
        except AttributeError: # because the descriptor holds nothing.
            if val.__class__ is static_object: dscset(obj,val)
            else: print( 'FIXME: Object.item cannot be initialized with type %s'%val.__class__ )

is there an alternate method, or is this poop the best I got??

Body:
so after some bashes to the head, and talking with a bpy dev who told me to back up and think of a better approach, I've settled on this:

def reassign():

    class Object(object):
        __slots__ = ['item']
        def __new__(cls):
            obj = object.__new__(cls)
            dscset(obj,static_object())
            return obj
    globals()['Object'] = Object

    dscget = Object.item.__get__
    dscset = Object.item.__set__

    def setter(obj, val): dscget(obj,Object).update(val) # leave type checking to the static object
    Object.item = property( dscget, setter )
reassign()
del reassign
# __new__.__closure__ holds the descriptor setter(s)

so no need for all the verification BS in the question :D