问:
<HttpResponse status_code=200, "image/png"> is not JSON serializable
I have build a CNN model and able to classify well. But i want trying to use Django to classify the class of an image when an image is passed in the url. Here are few thing i tried. the prediction function in my apps.py

```<code>def prediction(image_loc):
    image_path = 'D:/'
    image = cv2.imread(os.path.join(image_path,image_loc))
    print("image in matrix is ", image)
    output = image.copy()

    # Pre-Process the image for classification
    image = cv2.resize(image, (96, 96))
    image = image.astype("float") / 255.0
    image = img_to_array(image)
    image = np.expand_dims(image, axis=0)

    # Load the trained convolutional neural network and the label binarizer
    print("[INFO] Loading Model...")
    model_RP = load_model(os.path.join(os.getcwd(), "model\cnn_model_RP.hdf5"))
    lb_path = os.path.join(os.getcwd(),"model\labelbin_RP")
    lb_RP = pickle.loads(open(lb_path, "rb").read())
    print("[INFO] Model Loading Complete.")

    # Classify the input image
    print("[INFO] classifying image...")
    proba = model_RP.predict(image)[0]
    idx = np.argmax(proba)
    label = lb_RP.classes_[idx]

    #we will mark our prediction as "correct" of the input image filename contains the predicted label text
    #(obviously this makes the assumption that you have named your testing image files this way)

    filename = image_loc[image_loc.rfind(os.path.sep) + 1:]
    correct = "correct" if filename.rfind(label) != -1 else "incorrect"

    # Build the label and draw the label on the image
    label = "{}: {:.2f}% ({})".format(label, proba[idx] * 100, correct)
    output = imutils.resize(output, width=400)
    cv2.putText(output, label, (10, 25),  cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2)

    # show the output image
    print("[INFO] {}".format(label))
    #plt.imshow(output)
    #plt.show()

    #return(plt.show())
    return(label) #- WORKING

    #return HttpResponse(output, content_type = 'image/png')
    #resp = HttpResponse("", content_type = 'image/png')
    #resp.write('output')
    #return resp

</code>```

If i return just the label it works, below is Code snippet from my apps.py

```<code>    label = "{}: {:.2f}% ({})".format(label, proba[idx] * 100, correct)
    return (label)
</code>```

2.a  Here is the problem. I am trying to return the image as well with label on it. which i am not successful.

```<code>    label = "{}: {:.2f}% ({})".format(label, proba[idx] * 100, correct)
    output = imutils.resize(output, width=400)
    cv2.putText(output, label, (10, 25),  cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2)

    return HttpResponse(output, content_type = 'image/png')
</code>```

2.b Here is the 2nd approach to return the image, unfortunately failed.

```<code>     label = "{}: {:.2f}% ({})".format(label, proba[idx] * 100, correct)
     output = imutils.resize(output, width=400)
     cv2.putText(output, label, (10, 25),  cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2)
     resp = HttpResponse("", content_type = 'image/png')
     resp.write('output')
     return resp
</code>```

Here is my views.py

```<code>@api_view(['GET'])  # Decorator
def call_model(request):
    #if request.method == 'GET':

            # sentence is the query we want to get the prediction for
    params =  request.GET.get('image_loc')

            # predict method used to get the prediction
    resp = prediction(image_loc = params)

            # returning JSON response
    return Response(resp)
</code>```

Stack trace of error, when i run the below on the browser.

```<code>http://127.0.0.1:8000/model/img?format=json&image_loc=bulbasaur_plush.png
</code>```

```<code>TypeError at /model/img
<HttpResponse status_code=200, "image/png"> is not JSON serializable
Request Method: GET
Request URL:    http://127.0.0.1:8000/model/img?format=json&image_loc=bulbasaur_plush.png
Django Version: 2.2.12
Exception Type: TypeError
Exception Value:
<HttpResponse status_code=200, "image/png"> is not JSON serializable
Exception Location: C:\Anaconda3\envs\tf35\lib\json\encoder.py in default, line 179
Python Executable:  C:\Anaconda3\envs\tf35\python.exe
Python Version: 3.5.5
Python Path:
['D:\\Discern\\Term 3\\deploy',
 'C:\\Anaconda3\\envs\\tf35\\python35.zip',
 'C:\\Anaconda3\\envs\\tf35\\DLLs',
 'C:\\Anaconda3\\envs\\tf35\\lib',
 'C:\\Anaconda3\\envs\\tf35',
 'C:\\Users\\prade\\AppData\\Roaming\\Python\\Python35\\site-packages',
 'C:\\Anaconda3\\envs\\tf35\\lib\\site-packages',
 'C:\\Anaconda3\\envs\\tf35\\lib\\site-packages\\win32',
 'C:\\Anaconda3\\envs\\tf35\\lib\\site-packages\\win32\\lib',
 'C:\\Anaconda3\\envs\\tf35\\lib\\site-packages\\Pythonwin']
Server time:    Fri, 29 May 2020 04:35:18 +0000

</code>```

Tried to looks at similar posts but they are related to text, so could not get my issue solved.

Could someone help please.

答:
It looks like resp is a HttpResponse object (can't tell more, you did not gave code for prediction).

You have to make something JSON serializable within the Response() constructor (usually a dict, or a list, with only string / int / boolean).

(BTW, the @api_view decorator of Django Rest Framework is outdated, @action is prefered with last version)

Body:
I have build a CNN model and able to classify well. But i want trying to use Django to classify the class of an image when an image is passed in the url. Here are few thing i tried. the prediction function in my apps.py

def prediction(image_loc):
    image_path = 'D:/'
    image = cv2.imread(os.path.join(image_path,image_loc))
    print("image in matrix is ", image)
    output = image.copy()

    # Pre-Process the image for classification
    image = cv2.resize(image, (96, 96))
    image = image.astype("float") / 255.0
    image = img_to_array(image)
    image = np.expand_dims(image, axis=0)

    # Load the trained convolutional neural network and the label binarizer
    print("[INFO] Loading Model...")
    model_RP = load_model(os.path.join(os.getcwd(), "model\cnn_model_RP.hdf5"))
    lb_path = os.path.join(os.getcwd(),"model\labelbin_RP")
    lb_RP = pickle.loads(open(lb_path, "rb").read())
    print("[INFO] Model Loading Complete.")

    # Classify the input image
    print("[INFO] classifying image...")
    proba = model_RP.predict(image)[0]
    idx = np.argmax(proba)
    label = lb_RP.classes_[idx]

    #we will mark our prediction as "correct" of the input image filename contains the predicted label text
    #(obviously this makes the assumption that you have named your testing image files this way)

    filename = image_loc[image_loc.rfind(os.path.sep) + 1:]
    correct = "correct" if filename.rfind(label) != -1 else "incorrect"

    # Build the label and draw the label on the image
    label = "{}: {:.2f}% ({})".format(label, proba[idx] * 100, correct)
    output = imutils.resize(output, width=400)
    cv2.putText(output, label, (10, 25),  cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2)

    # show the output image
    print("[INFO] {}".format(label))
    #plt.imshow(output)
    #plt.show()

    #return(plt.show())
    return(label) #- WORKING

    #return HttpResponse(output, content_type = 'image/png')
    #resp = HttpResponse("", content_type = 'image/png')
    #resp.write('output')
    #return resp

If i return just the label it works, below is Code snippet from my apps.py

    label = "{}: {:.2f}% ({})".format(label, proba[idx] * 100, correct)
    return (label)

2.a  Here is the problem. I am trying to return the image as well with label on it. which i am not successful.

    label = "{}: {:.2f}% ({})".format(label, proba[idx] * 100, correct)
    output = imutils.resize(output, width=400)
    cv2.putText(output, label, (10, 25),  cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2)

    return HttpResponse(output, content_type = 'image/png')

2.b Here is the 2nd approach to return the image, unfortunately failed.

     label = "{}: {:.2f}% ({})".format(label, proba[idx] * 100, correct)
     output = imutils.resize(output, width=400)
     cv2.putText(output, label, (10, 25),  cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2)
     resp = HttpResponse("", content_type = 'image/png')
     resp.write('output')
     return resp

Here is my views.py

@api_view(['GET'])  # Decorator
def call_model(request):
    #if request.method == 'GET':

            # sentence is the query we want to get the prediction for
    params =  request.GET.get('image_loc')

            # predict method used to get the prediction
    resp = prediction(image_loc = params)

            # returning JSON response
    return Response(resp)

Stack trace of error, when i run the below on the browser.

http://127.0.0.1:8000/model/img?format=json&image_loc=bulbasaur_plush.png

TypeError at /model/img
<HttpResponse status_code=200, "image/png"> is not JSON serializable
Request Method: GET
Request URL:    http://127.0.0.1:8000/model/img?format=json&image_loc=bulbasaur_plush.png
Django Version: 2.2.12
Exception Type: TypeError
Exception Value:
<HttpResponse status_code=200, "image/png"> is not JSON serializable
Exception Location: C:\Anaconda3\envs\tf35\lib\json\encoder.py in default, line 179
Python Executable:  C:\Anaconda3\envs\tf35\python.exe
Python Version: 3.5.5
Python Path:
['D:\\Discern\\Term 3\\deploy',
 'C:\\Anaconda3\\envs\\tf35\\python35.zip',
 'C:\\Anaconda3\\envs\\tf35\\DLLs',
 'C:\\Anaconda3\\envs\\tf35\\lib',
 'C:\\Anaconda3\\envs\\tf35',
 'C:\\Users\\prade\\AppData\\Roaming\\Python\\Python35\\site-packages',
 'C:\\Anaconda3\\envs\\tf35\\lib\\site-packages',
 'C:\\Anaconda3\\envs\\tf35\\lib\\site-packages\\win32',
 'C:\\Anaconda3\\envs\\tf35\\lib\\site-packages\\win32\\lib',
 'C:\\Anaconda3\\envs\\tf35\\lib\\site-packages\\Pythonwin']
Server time:    Fri, 29 May 2020 04:35:18 +0000

Tried to looks at similar posts but they are related to text, so could not get my issue solved.

Could someone help please.


来源: stackexchange

问:
What is the point of Node.js
Ok this is probably a little blunt and to the point, but what is the point/need for Node.js

I've noticed it mainly through CloudFoundry but just not too sure what its supposed to be doing. However I am guessing its probably something pretty big as why else would VMWare be supporting it.

Thanks in advance.

答:
It's an...

Efficient and 100% event driven IO framework,

flexible enough to use the best underlying OS features it can find,

presenting an API in a high-level programming language (the same language your client-side will most-likely use),

implemented on top of the best available intepreting engine for that language, and

supporting more and more third party libraries with each passing day.

Effecient in server side api, avoid using for CPU intensive operation

:)

ContentLicense: CC BY-SA 3.0

Title: What is the point of Node.js


问:
Multi-party WebRTC without SFU
Based on this article, when implementing a WebRTC solution without a server, I assume it means SFU, the bottleneck is that only 4-6 participants can work.

Is there a solution that can work around this? For example, I just want to use Firebase as the only backend, mainly signaling and no SFU. What is the general implementation strategy to achieve at least 25-50 participants in WebRTC?

Update: This Github project shares a different statement.  It states "A full mesh is great for up to ~100 connections"

答:
If you want to make a conference with 25 people all sending their video, then a regular webrtc setup will not work. Except if you massively lower your video quality. The reason for this is that every participant would need to send 24 seperate streams to every other client. So lets say you stream is 128 KB/s then you will need to have 3MB/s in upload speed available. Which isn't always available. Then also downloading that same amount.

The problem is that isn't scalable. That's why you need an SFU. Then you will only send a single stream and receive from others. The other positive thing about SFUs is that you can use simulcast which adapts the quality of your received streams depending on your network speed.

You can use the Janus gateway or mediasoup for example. Here is an already setup mediasoup video conferencing application that is scalable github repository

ContentLicense: CC BY-SA 4.0

Title: Multi-party WebRTC without SFU


问:
ASP.Net to PDF conversion
I am using Itextsharp version 5.0.6 to convert Asp.net page into PDF. I am not able to create the PDF from the HMTML string with the css. If any one knows how to do with css please help me.

If any one has experience in iTextsharp kindly advice me and share your experience.

Thanks,
Parthasarathy M

答:
Having worked with iText's old HTML->PDF code, I can suggest that you:

Accept more answers to your questions.  :P

Don't do that.  iText's HTML->PDF converter is acceptable, but its CSS support is still spotty.  The new XMLWorker is an improvement, but there's still Much Better Options available to you.

I've been a committer on iText for a couple years now.  HTML->PDF conversion is not its strength.  Getting better, still a long way to go.

In particular, I'm quite happy with the results from WKHTML2PDF.  I was able to render an HTML page with a GOOGLE MAP to PDF.  You won't find that anywhere else (other than a browser's theoretical "current page to PDF" function, which I haven't heard of as yet).

Title: ASP.Net to PDF conversion


问:
URL Rewrite exceptions for Blazor WebAssembly Hosted deployment
During development, i have used Swagger on the server side of my Blazor WebAssembly App. Always launching (debug) using kestrel instead of IIS Express.
Routing worked as expected, all my component routed properly and if i manually typed /swagger, i got to the swagger page. All good.

We have deployed under IIS on our pre-prod servers, the Server side and Blazor WebAssembly App (client) work as expected and are usable, however, my /swagger url gets rewritten (I assume) to go somewhere in my App instead of letting it go to Swagger, obviously there isn't any component that answers to /swagger.

My only guess is that, when hosted on IIS, the aspnet core app takes care of telling IIS what to rewrite and how (similar to the configs that could be provided thru a web.config for a "Standalone" deployment.)

I can't find how to specify exceptions, I've been following the doc at
https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/blazor/webassembly?view=aspnetcore-3.1#iis

Any idea how i could add an exception for /swagger ?

EDIT:

Turns out it works without issues in Chrome, only Firefox has the unwanted behavior. If i clear my cache, or use Incognito mode, the issue does not happen in Firefox. So, it seems that Firefox caches some stuff and tries to send my URL input to the Blazor Wasm instead of going thru to the server. I will debug some more with the dev tools and fiddler open to try and figure it out, will report back.

答:
Do you have UseSwagger first in your Startup.Configure method?

```<code>public static void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseSwagger();
    app.UseSwaggerUI(c =>
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "YourAppName V1")
    );
</code>```

In Startup.ConfigureServices I have the Swagger code last.

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddSwaggerGen(c =>
        c.SwaggerDoc(
            name: "v1",
            info: new OpenApiInfo
            {
                Title = "YourAppName",
                Version = "V1",
            }));
}
</code>```

This is working just fine for us.

Note: You must navigate to https://yourdomain/swagger/index.html

Body:
Do you have UseSwagger first in your Startup.Configure method?

public static void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseSwagger();
    app.UseSwaggerUI(c =>
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "YourAppName V1")
    );

In Startup.ConfigureServices I have the Swagger code last.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddSwaggerGen(c =>
        c.SwaggerDoc(
            name: "v1",
            info: new OpenApiInfo
            {
                Title = "YourAppName",
                Version = "V1",
            }));
}

This is working just fine for us.

Note: You must navigate to https://yourdomain/swagger/index.html


问:
How to find the next instance of text in HTML using Beautiful Soup?
I'm writing a program that looks up the National Food Holiday for the current day using this site: https://foodimentary.com/today-in-national-food-holidays/may-holidays/.

So far I've been able to consistently get the tag with the current date, but I'm having trouble using that as a base reference to get the associated Food Day. Here's what I have so far:

```<code>month = date.today().strftime('%b') # Get month
day = date.today().strftime('%d') # Get day
date = f'{month.lower()}-{day}' # Format date

# Get HTML from home page
url = 'https://foodimentary.com/today-in-national-food-holidays/todayinfoodhistorycalenderfoodnjanuary/'
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser') # Parse HTML with Beautiful Soup

# Get the current month URL
months = soup.find('ul', id='menu-months', class_='menu') # Isolate the months table
monthUrl = months.find('a', href=True, string=month)['href'] # Get the month URL for the current month

# Get HTML from month page, parse
r = requests.get(monthUrl)
soup = BeautifulSoup(r.text, 'html.parser')

# Find tag with URL that contains formatted date
holidayTag = soup.select_one(f'a[href*={date}]')
print(holidayTag)

# TODO: Get the name of the food day based on holidayTag
</code>```

Using my browser's developer console, it seems like the most consistent pattern to correlate date with name of food holiday is that the holiday is always the next instance of text after the date tag. Here's an example piece of HTML:

```<code>

<div style="text-align:center;">
   <strong><a title="May 29" href="https://foodimentaryguy.wordpress.com/2011/05/29/may-29/">May 29</a></strong><br>
   <span style="color:#000000;"><a style="color:#000000;" href="https://foodimentary.com/2017/02/12/february-12th-is-national-biscotti-day/">National Biscuit Day</a></span>
   <div style="text-align:center;"><strong><a title="May 28" href="https://foodimentaryguy.wordpress.com/2011/05/28/may-28/">May 28</a></strong><br>
      <span style="color:#000000;"><a style="color:#000000;" href="https://foodimentary.com/2016/05/28/may-28-is-national-brisket-day/">National Brisket Day</a></span>
   </div>
</div>
</code>```

My question is: how can I use Beautiful Soup to get the name of the holiday from the date tag?

答:
This text is very unstructured (most probably written by hand and not machine generated). I recommend using re module for main parsing:

```<code>import re
from bs4 import BeautifulSoup

url = 'https://foodimentary.com/today-in-national-food-holidays/may-holidays/'
soup = BeautifulSoup(requests.get(url).content, 'html.parser')
txt = soup.select_one('section[role="main"]').text

out = {}
for day, names in re.findall(r'^([A-Z][^\n]+\d\s*)$(.*?)\n\n', txt, flags=re.DOTALL|re.M):
    out[day.strip()] = [name.replace('\xa0', ' ') for name in names.strip().split('\n')]

# pretty print on screen:
from pprint import pprint
pprint(out)
</code>```

Prints:

```<code>{'May 1': ['National Chocolate Parfait Day'],
 'May 10': ['National Liver and Onions Day'],
 'May 11': ['National “Eat What You Want” Day'],
 'May 12': ['National Nutty Fudge Day'],
 'May 13': ['National Apple Pie Day',
            'National Fruit Cocktail Day',
            'National Hummus Day'],
 'May 14': ['National Brioche Day', 'National Buttermilk Biscuit Day'],
 'May 15': ['National Chocolate Chip Day'],
 'May 16': ['National Barbecue Day'],
 'May 17': ['National Cherry Cobbler Day'],
 'May 18': ['National Cheese Souffle Day', 'I love Reese’s Day'],
 'May 19': ['National Devil’s Food Cake Day'],
 'May 2': ['National Chocolate Truffle Day'],
 'May 20': ['National Quiche Lorraine Day', 'National Pick Strawberries Day'],
 'May 21': ['National Strawberries and Cream Day'],
 'May 22': ['National Vanilla Pudding Day'],
 'May 23': ['National Taffy Day'],
 'May 24': ['National Escargot Day'],
 'May 25': ['National Brown-Bag-It Day', 'National Wine Day'],
 'May 26': ['National Blueberry Cheesecake Day', 'National Cherry Dessert Day'],
 'May 27': ['National Italian Beef Day', 'National Grape Popsicle Day'],
 'May 28': ['National Brisket Day'],
 'May 29': ['National Biscuit Day'],
 'May 3': ['National Raspberry Popover Day',
           'National Raspberry Tart Day',
           'National Chocolate Custard Day'],
 'May 30': ['National Mint Julep Day'],
 'May 31': ['National Macaroon Day'],
 'May 4': ['National Candied Orange Peel Day',
           'National Homebrew Day',
           'National Hoagie Day'],
 'May 5': ['National Enchilada Day – Happy Cinco de Mayo!'],
 'May 6': ['National Crepe Suzette Day'],
 'May 7': ['National Roast Leg of Lamb Day'],
 'May 8': ['National Coconut Cream Pie Day'],
 'May 9': ['National Shrimp Day', 'National Foodies Day*']}
</code>```

Body:
I'm writing a program that looks up the National Food Holiday for the current day using this site: https://foodimentary.com/today-in-national-food-holidays/may-holidays/.

So far I've been able to consistently get the tag with the current date, but I'm having trouble using that as a base reference to get the associated Food Day. Here's what I have so far:

month = date.today().strftime('%b') # Get month
day = date.today().strftime('%d') # Get day
date = f'{month.lower()}-{day}' # Format date

# Get HTML from home page
url = 'https://foodimentary.com/today-in-national-food-holidays/todayinfoodhistorycalenderfoodnjanuary/'
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser') # Parse HTML with Beautiful Soup

# Get the current month URL
months = soup.find('ul', id='menu-months', class_='menu') # Isolate the months table
monthUrl = months.find('a', href=True, string=month)['href'] # Get the month URL for the current month

# Get HTML from month page, parse
r = requests.get(monthUrl)
soup = BeautifulSoup(r.text, 'html.parser')

# Find tag with URL that contains formatted date
holidayTag = soup.select_one(f'a[href*={date}]')
print(holidayTag)

# TODO: Get the name of the food day based on holidayTag

Using my browser's developer console, it seems like the most consistent pattern to correlate date with name of food holiday is that the holiday is always the next instance of text after the date tag. Here's an example piece of HTML:

   May 29

   National Biscuit Day

May 28

      National Brisket Day

My question is: how can I use Beautiful Soup to get the name of the holiday from the date tag?

Body:
This text is very unstructured (most probably written by hand and not machine generated). I recommend using re module for main parsing:

import re
from bs4 import BeautifulSoup

url = 'https://foodimentary.com/today-in-national-food-holidays/may-holidays/'
soup = BeautifulSoup(requests.get(url).content, 'html.parser')
txt = soup.select_one('section[role="main"]').text

out = {}
for day, names in re.findall(r'^([A-Z][^\n]+\d\s*)$(.*?)\n\n', txt, flags=re.DOTALL|re.M):
    out[day.strip()] = [name.replace('\xa0', ' ') for name in names.strip().split('\n')]

# pretty print on screen:
from pprint import pprint
pprint(out)

Prints:

{'May 1': ['National Chocolate Parfait Day'],
 'May 10': ['National Liver and Onions Day'],
 'May 11': ['National “Eat What You Want” Day'],
 'May 12': ['National Nutty Fudge Day'],
 'May 13': ['National Apple Pie Day',
            'National Fruit Cocktail Day',
            'National Hummus Day'],
 'May 14': ['National Brioche Day', 'National Buttermilk Biscuit Day'],
 'May 15': ['National Chocolate Chip Day'],
 'May 16': ['National Barbecue Day'],
 'May 17': ['National Cherry Cobbler Day'],
 'May 18': ['National Cheese Souffle Day', 'I love Reese’s Day'],
 'May 19': ['National Devil’s Food Cake Day'],
 'May 2': ['National Chocolate Truffle Day'],
 'May 20': ['National Quiche Lorraine Day', 'National Pick Strawberries Day'],
 'May 21': ['National Strawberries and Cream Day'],
 'May 22': ['National Vanilla Pudding Day'],
 'May 23': ['National Taffy Day'],
 'May 24': ['National Escargot Day'],
 'May 25': ['National Brown-Bag-It Day', 'National Wine Day'],
 'May 26': ['National Blueberry Cheesecake Day', 'National Cherry Dessert Day'],
 'May 27': ['National Italian Beef Day', 'National Grape Popsicle Day'],
 'May 28': ['National Brisket Day'],
 'May 29': ['National Biscuit Day'],
 'May 3': ['National Raspberry Popover Day',
           'National Raspberry Tart Day',
           'National Chocolate Custard Day'],
 'May 30': ['National Mint Julep Day'],
 'May 31': ['National Macaroon Day'],
 'May 4': ['National Candied Orange Peel Day',
           'National Homebrew Day',
           'National Hoagie Day'],
 'May 5': ['National Enchilada Day – Happy Cinco de Mayo!'],
 'May 6': ['National Crepe Suzette Day'],
 'May 7': ['National Roast Leg of Lamb Day'],
 'May 8': ['National Coconut Cream Pie Day'],
 'May 9': ['National Shrimp Day', 'National Foodies Day*']}


问:
How to get use BGTask in objective-c with iOS 13(Background Fetch)
So i want to build a iOS, i am pretty new to the world of objective-c and one feature i want to implement is the ability to send a API request and do a bit of background processing while the app is not "in focus/in background". I have researched for a couple days about this BGTask API for iOS 13 and have created a projected to see if i can get "background fetch" working. I have not be able to. Im pretty sure i have everything setup correctly but i can not get background fetch functionality to trigger on my iPhone, not even once over the past couple days.

I am using a actual iOS device to test this with iOS 13.4.1

"Permitted background task scheduler identifiers" is setup properly in Info.plist

App is signed

Background processing and Background fetch is checked in Background Modes

I waited the 15 minute interval as per Apples documentation

Here is my code. All this is just a blank iOS project using objective-c. I only edited AppDelegate.m and Info.plist

AppDelegate.m

```<code>#import "AppDelegate.h"
#import <BackgroundTasks/BackgroundTasks.h>

static NSString* TaskID = @"com.myapp.task";

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.

    [[BGTaskScheduler sharedScheduler] registerForTaskWithIdentifier:TaskID
                                                          usingQueue:nil
                                                       launchHandler:^(BGProcessingTask *task) {

        [self handleAppRefreshTask:task];
    }];

    return YES;
}

#pragma mark - UISceneSession lifecycle

- (UISceneConfiguration *)application:(UIApplication *)application configurationForConnectingSceneSession:(UISceneSession *)connectingSceneSession options:(UISceneConnectionOptions *)options {
    // Called when a new scene session is being created.
    // Use this method to select a configuration to create the new scene with.
    return [[UISceneConfiguration alloc] initWithName:@"Default Configuration" sessionRole:connectingSceneSession.role];
}

- (void)application:(UIApplication *)application didDiscardSceneSessions:(NSSet<UISceneSession *> *)sceneSessions {
    // Called when the user discards a scene session.
    // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
    // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}

-(void)handleAppRefreshTask:(BGProcessingTask *)task {
    //do things with task
  NSLog(@"Process started!");
  task.expirationHandler = ^{
    NSLog(@"WARNING: expired before finish was executed.");

  };

  NSString *targetUrl = @"https://webhook.site/1b274a6f-016f-4edf-8e31-4ed7058eaeac";
  NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
  [request setHTTPMethod:@"GET"];
  [request setURL:[NSURL URLWithString:targetUrl]];

  [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:
    ^(NSData * _Nullable data,
      NSURLResponse * _Nullable response,
      NSError * _Nullable error) {

        NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"Data received: %@", myString);
  }] resume];

  task.expirationHandler = ^{
    NSLog(@"WARNING: expired before finish was executed.");

  };

  [task setTaskCompletedWithSuccess:YES];
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
  NSLog(@"Entering background");
  BGProcessingTaskRequest *request = [[BGProcessingTaskRequest alloc] initWithIdentifier:TaskID];
  request.requiresNetworkConnectivity = true;
  request.requiresExternalPower = false;
  request.earliestBeginDate = [NSDate dateWithTimeIntervalSinceNow:60];

  @try {
    [[BGTaskScheduler sharedScheduler] submitTaskRequest:request error:nil];
  }
  @catch(NSException *e){
    NSLog(@" Unable to submit request");
  }

}

@end
</code>```

Is background fetch broken in iOS 13? Even clicking on the “Simulate background fetch" in Xcode debug menu does not work. It just closes the app and nothing happens. Can anybody help/give any advice?

答:
A few observations:

The setTaskCompletedWithSuccess should be inside the network request’s completion handler. You don’t want to mark the task as complete until the request has had a chance to run and you’ve processed the result.

You are calling submitTaskRequest, but passing nil for the NSError reference. You have also wrapped that in an exception handler. But this API call doesn’t throw exceptions, but rather just passes back errors. But you have to supply it an error reference. E.g.

```<code>NSLog(@"Entering background");
BGProcessingTaskRequest *request = [[BGProcessingTaskRequest alloc] initWithIdentifier:TaskID];
request.requiresNetworkConnectivity = true;
request.requiresExternalPower = false;
request.earliestBeginDate = [NSDate dateWithTimeIntervalSinceNow:60];

NSError *error;
if (![[BGTaskScheduler sharedScheduler] submitTaskRequest:request error:&error]) {
    NSLog(@"BGTaskScheduler failed: %@", error);
}
</code>```

In your code, if it failed, you would never know.

You have placed this code in applicationDidEnterBackground. I.e., are you seeing this “Entering background” message at all? The reason I ask is that if you’ve supplied a scene delegate (common if you just created a new iOS 13 app), this method won’t be called, whereas sceneDidEnterBackground will.

You said that you tried “Simulate background fetch”. But you haven’t created a background fetch request (a BGAppRefreshTask). You created a background task (a BGProcessingTask), which is a different thing. To test background processing requests, refer to Starting and Terminating Tasks During Development.

There’s an interesting question as to how you know that the fetch request was processed. You’re just using NSLog (which presumes that you’re keeping your app attached to the Xcode debugger). I would suggest testing this without the app being attached to Xcode. There are a few options:

If you can watch your server logs for requests, that works.

I personally will often put in UserNotifications (and make sure to go into settings and turn on persistent notifications so I don’t miss them).

Another approach that I’ve done is to log these events in some table in my app’s persistent storage and then have some UI within the app to fetch this data so I can confirm what happened.

I’ll often use Unified Logging so that I can watch os_log statements issued by my device from the macOS Console even when Xcode is not running. This is very useful in logging app/scene methods. See WWDC 2016 Unified Logging and Activity Tracing

Whatever you do, for things like background processing, background app refresh, etc., I will program some mechanism so that I can check to see if the requests/tasks took place, even when not attached to Xcode. Being attached to the debugger can, in some cases, affect the app lifecycle, and I want to make sure I’ve got some way to confirm what was going on without the benefit of the console.

Likely obvious, but make sure you never “force quit” the app, as that will stop background processes from taking place.

For more information, See WWDC 2019 video Advances in App Background Execution.

Body:
So i want to build a iOS, i am pretty new to the world of objective-c and one feature i want to implement is the ability to send a API request and do a bit of background processing while the app is not "in focus/in background". I have researched for a couple days about this BGTask API for iOS 13 and have created a projected to see if i can get "background fetch" working. I have not be able to. Im pretty sure i have everything setup correctly but i can not get background fetch functionality to trigger on my iPhone, not even once over the past couple days.

I am using a actual iOS device to test this with iOS 13.4.1

"Permitted background task scheduler identifiers" is setup properly in Info.plist

App is signed

Background processing and Background fetch is checked in Background Modes

I waited the 15 minute interval as per Apples documentation

Here is my code. All this is just a blank iOS project using objective-c. I only edited AppDelegate.m and Info.plist

AppDelegate.m

#import "AppDelegate.h"
#import <BackgroundTasks/BackgroundTasks.h>

static NSString* TaskID = @"com.myapp.task";

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.

    [[BGTaskScheduler sharedScheduler] registerForTaskWithIdentifier:TaskID
                                                          usingQueue:nil
                                                       launchHandler:^(BGProcessingTask *task) {

        [self handleAppRefreshTask:task];
    }];

    return YES;
}

#pragma mark - UISceneSession lifecycle

- (UISceneConfiguration *)application:(UIApplication *)application configurationForConnectingSceneSession:(UISceneSession *)connectingSceneSession options:(UISceneConnectionOptions *)options {
    // Called when a new scene session is being created.
    // Use this method to select a configuration to create the new scene with.
    return [[UISceneConfiguration alloc] initWithName:@"Default Configuration" sessionRole:connectingSceneSession.role];
}

- (void)application:(UIApplication *)application didDiscardSceneSessions:(NSSet<UISceneSession *> *)sceneSessions {
    // Called when the user discards a scene session.
    // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
    // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}

-(void)handleAppRefreshTask:(BGProcessingTask *)task {
    //do things with task
  NSLog(@"Process started!");
  task.expirationHandler = ^{
    NSLog(@"WARNING: expired before finish was executed.");

  };

  NSString *targetUrl = @"https://webhook.site/1b274a6f-016f-4edf-8e31-4ed7058eaeac";
  NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
  [request setHTTPMethod:@"GET"];
  [request setURL:[NSURL URLWithString:targetUrl]];

  [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:
    ^(NSData * _Nullable data,
      NSURLResponse * _Nullable response,
      NSError * _Nullable error) {

        NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"Data received: %@", myString);
  }] resume];

  task.expirationHandler = ^{
    NSLog(@"WARNING: expired before finish was executed.");

  };

  [task setTaskCompletedWithSuccess:YES];
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
  NSLog(@"Entering background");
  BGProcessingTaskRequest *request = [[BGProcessingTaskRequest alloc] initWithIdentifier:TaskID];
  request.requiresNetworkConnectivity = true;
  request.requiresExternalPower = false;
  request.earliestBeginDate = [NSDate dateWithTimeIntervalSinceNow:60];

  @try {
    [[BGTaskScheduler sharedScheduler] submitTaskRequest:request error:nil];
  }
  @catch(NSException *e){
    NSLog(@" Unable to submit request");
  }

}

@end

Is background fetch broken in iOS 13? Even clicking on the “Simulate background fetch" in Xcode debug menu does not work. It just closes the app and nothing happens. Can anybody help/give any advice?

Body:
A few observations:

The setTaskCompletedWithSuccess should be inside the network request’s completion handler. You don’t want to mark the task as complete until the request has had a chance to run and you’ve processed the result.

You are calling submitTaskRequest, but passing nil for the NSError reference. You have also wrapped that in an exception handler. But this API call doesn’t throw exceptions, but rather just passes back errors. But you have to supply it an error reference. E.g.

NSLog(@"Entering background");
BGProcessingTaskRequest *request = [[BGProcessingTaskRequest alloc] initWithIdentifier:TaskID];
request.requiresNetworkConnectivity = true;
request.requiresExternalPower = false;
request.earliestBeginDate = [NSDate dateWithTimeIntervalSinceNow:60];

NSError *error;
if (![[BGTaskScheduler sharedScheduler] submitTaskRequest:request error:&error]) {
    NSLog(@"BGTaskScheduler failed: %@", error);
}

In your code, if it failed, you would never know.

You have placed this code in applicationDidEnterBackground. I.e., are you seeing this “Entering background” message at all? The reason I ask is that if you’ve supplied a scene delegate (common if you just created a new iOS 13 app), this method won’t be called, whereas sceneDidEnterBackground will.

You said that you tried “Simulate background fetch”. But you haven’t created a background fetch request (a BGAppRefreshTask). You created a background task (a BGProcessingTask), which is a different thing. To test background processing requests, refer to Starting and Terminating Tasks During Development.

There’s an interesting question as to how you know that the fetch request was processed. You’re just using NSLog (which presumes that you’re keeping your app attached to the Xcode debugger). I would suggest testing this without the app being attached to Xcode. There are a few options:

If you can watch your server logs for requests, that works.

I personally will often put in UserNotifications (and make sure to go into settings and turn on persistent notifications so I don’t miss them).

Another approach that I’ve done is to log these events in some table in my app’s persistent storage and then have some UI within the app to fetch this data so I can confirm what happened.

I’ll often use Unified Logging so that I can watch os_log statements issued by my device from the macOS Console even when Xcode is not running. This is very useful in logging app/scene methods. See WWDC 2016 Unified Logging and Activity Tracing

Whatever you do, for things like background processing, background app refresh, etc., I will program some mechanism so that I can check to see if the requests/tasks took place, even when not attached to Xcode. Being attached to the debugger can, in some cases, affect the app lifecycle, and I want to make sure I’ve got some way to confirm what was going on without the benefit of the console.

Likely obvious, but make sure you never “force quit” the app, as that will stop background processes from taking place.

For more information, See WWDC 2019 video Advances in App Background Execution.


问:
bit slicing: finding minimum value

Short version

I need to find the minimum value of 64 uint8_t variables encoded as bit slices.

i.e. each bit of the variables is encoded into eight separate uint64_t:

```<code>//Normal layout:
uint8_t values[64]; // This is what you normally use.
                    // Finding minimum would be a simple
                    // matter of a for loop

/***********************/

// BITSLICE layout:
uint64_t slices[8]; // This is what I have, due to performance
                    // reasons in other parts of the code (not shown here)

slice[0]; //LSB: Least signignificant bit (for all 64 values)
slice[7]; //MSB: Most significant bit (for all 64 values)
</code>```

Now, how do I find out the minimum value of these? (I do not care about it's position, only it's value)

More context:

In reality I have a much longer array (than 64) of values inside an algorithm which already uses bit-slicing for performance reasons.

So what I have is actually more like (the question above was simplified):

```<code>uint64_t slices[8][100];
</code>```

So what I really need is the minimum value out of all 100*64 values. But I figure this can be done in a regular for loop by applying the answer to the simplified question above.

EDIT: apparently my question wasn't as clear as I thought so It's been updated

答:
Here are simple and efficient functions that compute the minimum and maximum values of the set of 64 byte values encoded as 8 uint64_t packs, each storing 1 bit of each of the 64 values:

#include <stdint.h>

uint8_t maxslice(const uint64_t s[8]) {
    uint8_t max = 0, bit = 0x80;
    uint64_t mask = ~0ULL;
    for (int i = 8; i-- > 0; bit >>= 1) {
        uint64_t x = s[i] & mask;
        if (x) {
            max |= bit;
            mask &= x;
        }
    }
    return max;
}

uint8_t minslice(const uint64_t s[8]) {
    uint8_t min = 0, bit = 0x80;
    uint64_t mask = ~0ULL;
    for (int i = 8; i-- > 0; bit >>= 1) {
        uint64_t x = ~s[i] & mask;
        if (x) {
            min |= bit;
            mask &= x;
        }
    }
    return ~min;
}
```

<p>As can be verified on Godbolt's Compiler Explorer, <code>clang</code> generates branchless code for both functions.</p>

<p>For your extended goal of computing the minimum of a larger set of values organized this way, <code>uint64_t slices[8][100]</code>, you could simply iterate this code on the array and compute the minimum incrementally. It might be worthwhile to test at each step of this loop if the absolute minimum of <code>0</code> has been found already. The tricky part is how the array is organized:</p>

<p><code>uint64_t slices[8][100]</code> defines an array of 8 arrays of 100 <code>uint64_t</code>. In other words the layout in memory is 6400 low order bits, then 6400 bits of order 2, ..., finally 6400 bits of weight 128.</p>

```uint8_t minarray(const uint64_t s[8][100]) {
    uint8_t all_max = 0;
    for (int j = 0; j < 100; j++) {
        uint8_t max = 0, bit = 0x80;
        uint64_t mask = ~0ULL;
        for (int i = 8; i-- > 0; bit >>= 1) {
            uint64_t x = ~s[i][j] & mask;
            if (x) {
                max |= bit;
                mask &= x;
            }
        }
        if (all_max < max) {
            all_max = max;
            if (all_max == 255)
                break;
        }
    }
    return ~all_max;
}
```

<p>In order to vectorize this code, we can transpose the loops: computing with <code>x</code> and <code>mask</code> as arrays of 100 <code>uint64_t</code> will produce the same result but will let the compiler vectorize some of the inner loops:</p>

<pre class="lang-c prettyprint-override"><code>uint8_t minarray1(const uint64_t s[8][100]) {
    uint8_t max = 0, bit = 0x80;
    uint64_t mask[100] = {
        ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL,
        ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL,
        ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL,
        ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL,
        ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL,
        ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL,
        ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL,
        ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL,
        ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL,
        ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL,
    };
    for (int i = 8; i-- > 0; bit >>= 1) {
        uint64_t x[100];
        uint64_t xall = 0;
        for (int j = 0; j < 100; j++) {
            x[j] = ~s[i][j] & mask[j];
            xall |= x[j];
        }
        if (xall) {
            max |= bit;
            for (int j = 0; j < 100; j++) {
                mask[j] &= x[j];
            }
        }
    }
    return ~max;
}
</code>```

Again clang generates unrolled vectorized code. Benchmarking would tell if this approach gives better performance than the previous one.

Title: bit slicing: finding minimum value

Body:
Short version

I need to find the minimum value of 64 uint8_t variables encoded as bit slices.

i.e. each bit of the variables is encoded into eight separate uint64_t:

//Normal layout:
uint8_t values[64]; // This is what you normally use.
                    // Finding minimum would be a simple
                    // matter of a for loop

/***********************/

// BITSLICE layout:
uint64_t slices[8]; // This is what I have, due to performance
                    // reasons in other parts of the code (not shown here)

slice[0]; //LSB: Least signignificant bit (for all 64 values)
slice[7]; //MSB: Most significant bit (for all 64 values)

Now, how do I find out the minimum value of these? (I do not care about it's position, only it's value)

More context:

In reality I have a much longer array (than 64) of values inside an algorithm which already uses bit-slicing for performance reasons.

So what I have is actually more like (the question above was simplified):

uint64_t slices[8][100];

So what I really need is the minimum value out of all 100*64 values. But I figure this can be done in a regular for loop by applying the answer to the simplified question above.

EDIT: apparently my question wasn't as clear as I thought so It's been updated

Body:
Here are simple and efficient functions that compute the minimum and maximum values of the set of 64 byte values encoded as 8 uint64_t packs, each storing 1 bit of each of the 64 values:

#include <stdint.h>

uint8_t maxslice(const uint64_t s[8]) {
    uint8_t max = 0, bit = 0x80;
    uint64_t mask = ~0ULL;
    for (int i = 8; i-- > 0; bit >>= 1) {
        uint64_t x = s[i] & mask;
        if (x) {
            max |= bit;
            mask &= x;
        }
    }
    return max;
}

uint8_t minslice(const uint64_t s[8]) {
    uint8_t min = 0, bit = 0x80;
    uint64_t mask = ~0ULL;
    for (int i = 8; i-- > 0; bit >>= 1) {
        uint64_t x = ~s[i] & mask;
        if (x) {
            min |= bit;
            mask &= x;
        }
    }
    return ~min;
}

As can be verified on Godbolt's Compiler Explorer, clang generates branchless code for both functions.

For your extended goal of computing the minimum of a larger set of values organized this way, uint64_t slices[8][100], you could simply iterate this code on the array and compute the minimum incrementally. It might be worthwhile to test at each step of this loop if the absolute minimum of 0 has been found already. The tricky part is how the array is organized:

uint64_t slices[8][100] defines an array of 8 arrays of 100 uint64_t. In other words the layout in memory is 6400 low order bits, then 6400 bits of order 2, ..., finally 6400 bits of weight 128.

uint8_t minarray(const uint64_t s[8][100]) {
    uint8_t all_max = 0;
    for (int j = 0; j < 100; j++) {
        uint8_t max = 0, bit = 0x80;
        uint64_t mask = ~0ULL;
        for (int i = 8; i-- > 0; bit >>= 1) {
            uint64_t x = ~s[i][j] & mask;
            if (x) {
                max |= bit;
                mask &= x;
            }
        }
        if (all_max < max) {
            all_max = max;
            if (all_max == 255)
                break;
        }
    }
    return ~all_max;
}

In order to vectorize this code, we can transpose the loops: computing with x and mask as arrays of 100 uint64_t will produce the same result but will let the compiler vectorize some of the inner loops:

uint8_t minarray1(const uint64_t s[8][100]) {
    uint8_t max = 0, bit = 0x80;
    uint64_t mask[100] = {
        ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL,
        ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL,
        ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL,
        ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL,
        ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL,
        ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL,
        ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL,
        ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL,
        ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL,
        ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL, ~0ULL,
    };
    for (int i = 8; i-- > 0; bit >>= 1) {
        uint64_t x[100];
        uint64_t xall = 0;
        for (int j = 0; j < 100; j++) {
            x[j] = ~s[i][j] & mask[j];
            xall |= x[j];
        }
        if (xall) {
            max |= bit;
            for (int j = 0; j < 100; j++) {
                mask[j] &= x[j];
            }
        }
    }
    return ~max;
}

Again clang generates unrolled vectorized code. Benchmarking would tell if this approach gives better performance than the previous one.


问:
Is it possible for me to get null values I correlated sub queries?
I got that syntax error:

Msg 102, Level 15, State 1, Line 47

  Incorrect syntax near '('

after running this code:

```<code>select *
from enrollment
where grade = (select null(grade) from enrollment)
</code>```

I was trying to run a correlated subquery to output null values of grade in an enrollment table.

答:
I was trying to run a correlated subquery to output null values of grade in an enrollment table.

I don't see how the question relates to a subquery, but I am wondering whether you just want:

```<code>select * from enrollment where grade is null
</code>```

Body:
I got that syntax error:

Msg 102, Level 15, State 1, Line 47

  Incorrect syntax near '('

after running this code:

select *
from enrollment
where grade = (select null(grade) from enrollment)

I was trying to run a correlated subquery to output null values of grade in an enrollment table.

Body:
I was trying to run a correlated subquery to output null values of grade in an enrollment table.

I don't see how the question relates to a subquery, but I am wondering whether you just want:

select * from enrollment where grade is null


问:
How to make query with "contains" filter but also case insensetive?
I'm looking for a query filter that will return object that has column for example "FooBar" from database by passing argument "oobar". Haven't found it anywhere :(

Edit:
It turned out that "contains" is already case insensetive :O

答:
You can use 'ilike' to query like below</p>

```<code>model.YOURMODEL.query.filter(Model.column.ilike("oobar"))
</code>```

Body:
You can use 'ilike' to query like below

model.YOURMODEL.query.filter(Model.column.ilike("oobar"))


问:
How can I plot consensus sequences as a binary heatmap in R
I have many amino acids sequences like in a fasta format that I did multiple sequence alignment. I was trying to plot something like binary code as heatmap. If it had a change it would be red, if it did not change would be yellow, for example.

I came across to msaplot from ggtreepackage. I also checked ggmsa package for that. But so far, I did not get what I wanted.
So basically I wanted to:

change the multiple sequence alignment to a binary matrix (if the amino differs from the reference sequence, plot x, if not y)

plot as a heatmap

A multiple sequence alignment is something like this for those who don't know.

I know that I should provide some type of data example but I am not sure how to create an example of multiple sequence alignment

if you install ggmsa you can have an example of the data and plot in r using:

```<code>protein_sequences <- system.file("extdata", "sample.fasta", package = "ggmsa")
ggmsa(protein_sequences, start = 265, end = 300)
</code>```

答:
We read in the alignment:

```<code>library(Biostrings)
library(ggmsa)
protein_sequences <- system.file("extdata", "sample.fasta", package = "ggmsa")
aln = readAAMultipleAlignment(protein_sequences)
ggmsa(protein_sequences, start = 265, end = 300)
</code>```

Set the reference as the 1st sequence, some Rattus, you can also use the consensus with consensusString() :

```<code>aln = unmasked(aln)
names(aln)[1]
[1] "PH4H_Rattus_norvegicus"

ref = aln[1]
</code>```

Here we iterate through the sequence and make the binary for where the sequences are the same as the reference:

```<code>bm = sapply(1:length(aln),function(i){
as.numeric(as.matrix(aln[i])==as.matrix(ref))
})

bm = t(bm)
rownames(bm) = names(aln)
</code>```

The plot you see above has sequences reversed, so to visualize the same thing we reverse it, and also subset on 265 - 300:

```<code>library(pheatmap)
pheatmap(bm[nrow(bm):1,265:300],cluster_rows=FALSE,cluster_cols=FALSE)
</code>```

The last row, is Rattus, the reference, and anything similar to that is read, as you can see in the alignment above, last 4 sequences are identical.

Body:
I have many amino acids sequences like in a fasta format that I did multiple sequence alignment. I was trying to plot something like binary code as heatmap. If it had a change it would be red, if it did not change would be yellow, for example.

I came across to msaplot from ggtreepackage. I also checked ggmsa package for that. But so far, I did not get what I wanted.
So basically I wanted to:

change the multiple sequence alignment to a binary matrix (if the amino differs from the reference sequence, plot x, if not y)

plot as a heatmap

A multiple sequence alignment is something like this for those who don't know.

I know that I should provide some type of data example but I am not sure how to create an example of multiple sequence alignment

if you install ggmsa you can have an example of the data and plot in r using:

protein_sequences <- system.file("extdata", "sample.fasta", package = "ggmsa")
ggmsa(protein_sequences, start = 265, end = 300)

Body:
We read in the alignment:

library(Biostrings)
library(ggmsa)
protein_sequences <- system.file("extdata", "sample.fasta", package = "ggmsa")
aln = readAAMultipleAlignment(protein_sequences)
ggmsa(protein_sequences, start = 265, end = 300)

Set the reference as the 1st sequence, some Rattus, you can also use the consensus with consensusString() :

aln = unmasked(aln)
names(aln)[1]
[1] "PH4H_Rattus_norvegicus"

ref = aln[1]

Here we iterate through the sequence and make the binary for where the sequences are the same as the reference:

bm = sapply(1:length(aln),function(i){
as.numeric(as.matrix(aln[i])==as.matrix(ref))
})

bm = t(bm)
rownames(bm) = names(aln)

The plot you see above has sequences reversed, so to visualize the same thing we reverse it, and also subset on 265 - 300:

library(pheatmap)
pheatmap(bm[nrow(bm):1,265:300],cluster_rows=FALSE,cluster_cols=FALSE)

The last row, is Rattus, the reference, and anything similar to that is read, as you can see in the alignment above, last 4 sequences are identical.


问:
how to set hex color code for background

Possible Duplicate:

  How can I create a UIColor from a hex string?

I want to programmatically set the color of the UIView Background.

It doesn't seem like I can do it through Interfacebuilder. How should I do it if I want to set it to some hex code color?

答:
I like to use this little piece of code to use HTML web colors in my apps.

Usage:

```<code>[self.view setBackgroundColor: [self colorWithHexString:@"FFFFFF"]]; /* white */
</code>```

The Code:

```<code>-(UIColor*)colorWithHexString:(NSString*)hex
{
    NSString *cString = [[hex stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];

    // String should be 6 or 8 characters
    if ([cString length] < 6) return [UIColor grayColor];

    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];

    if ([cString length] != 6) return  [UIColor grayColor];

    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];

    range.location = 2;
    NSString *gString = [cString substringWithRange:range];

    range.location = 4;
    NSString *bString = [cString substringWithRange:range];

    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];

    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
}
</code>```

Body:
I like to use this little piece of code to use HTML web colors in my apps.

Usage:

[self.view setBackgroundColor: [self colorWithHexString:@"FFFFFF"]]; /* white */

The Code:

-(UIColor*)colorWithHexString:(NSString*)hex
{
    NSString *cString = [[hex stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];

    // String should be 6 or 8 characters
    if ([cString length] < 6) return [UIColor grayColor];

    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];

    if ([cString length] != 6) return  [UIColor grayColor];

    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];

    range.location = 2;
    NSString *gString = [cString substringWithRange:range];

    range.location = 4;
    NSString *bString = [cString substringWithRange:range];

    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];

    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
}


问:
Errors because of vector<string>?
Sorry for the spaghetti code, I don't have much experience with C++ (or coding in general for that matter) but here is my code... Also first time posting on stack overflow so apologies for improper formatting.
I have been scouring the internet for the last 4 hours. Please tell me this is a simple fix.
I have tried using std::vector ingredients.

```<code>//Program_2.h

#pragma once
#include <vector>
#include <string>
#include <iostream>

namespace sandwich
{
    class SandwichMaker
    {
    public:
        vector<string> ingredients;//<-- causing a few errors
        int s = 0;
        int Control();
        void Menu(int &s, vector<string> &vec);
        void PrintSandwich(vector<string> &vec);

    private:

    };
}

//Program_2.cpp

#include "Program_2.h"

using namespace std;
using namespace sandwich;

int SandwichMaker::Control()
{
    SandwichMaker swm;
    //vector<string> ingredients;
    swm.Menu(swm.s, swm.ingredients);

    while (swm.s > 0)
    {
        swm.Menu(swm.s, swm.ingredients);
    }

    system("PAUSE");
    return 0;
}

void SandwichMaker::Menu(int &s, vector<string>& vec)
{
    SandwichMaker swm;
    cout << "Please choose what you would like to do and type the ingredient (1 and 2 only)\n (0 quit, 1 add ingredient, 2 remove ingredient, 3 make sandwich): ";
    cin >> s;

    string tempIngredient = "";

    switch (s)
    {
    case 1://add
        //cout << "Enter the ingredient you are going to add.\n";
        cin.ignore();
        getline(cin, tempIngredient);
        vec.push_back(tempIngredient);
        cout << " Ingredient has been added\n";
        break;
    case 2://remove
        if (!vec.empty())
            vec.pop_back();
        else
            cout << " Nothing has been added yet\n";
        break;
    case 3: //make the sandwich
        swm.PrintSandwich(vec);
        break;
    default:
        break;
    }
}

void SandwichMaker::PrintSandwich(vector<string>& vec)
{
    cout << "Your sandwich contains: ";
    for (size_t i = 0; i < vec.size(); i++)
    {
        cout << i << ", " << vec[i] << endl;
    }
}

</code>```

cant post an images soo link? https://imgur.com/a/mK0UrEU  of all the errors that are getting spit out because of vector.

答:
Your using namespace std comes after your inclusion of Program_2.h, so the SandwichMaker class is defined without using namespace std being in effect.

You thus need to write std::vector, not vector, and std::string, not string.

Note: Do not try to "fix" this by applying using namespace std earlier - that's a bad idea and poor programming. See:

Why is "using namespace std;" considered bad practice?

PS:

You're repeating the word "Sandwich" a whole lot of times: sandwich::SandwichMaker{}.PrintSandwich() - aren't these too many sandwiches?

I know a guy who's a sandwich maker and he never prints sandwiches.

If you have a class named WhateverMaker - you often don't really need the class at all, and could settle for a nice Whatever class, and some functions which return Whatevers. See also this.

Title: Errors because of vector<string>?

Body:
Sorry for the spaghetti code, I don't have much experience with C++ (or coding in general for that matter) but here is my code... Also first time posting on stack overflow so apologies for improper formatting.
I have been scouring the internet for the last 4 hours. Please tell me this is a simple fix.
I have tried using std::vector ingredients.

//Program_2.h

#pragma once
#include <vector>
#include <string>
#include <iostream>

namespace sandwich
{
    class SandwichMaker
    {
    public:
        vector<string> ingredients;//<-- causing a few errors
        int s = 0;
        int Control();
        void Menu(int &s, vector<string> &vec);
        void PrintSandwich(vector<string> &vec);

    private:

    };
}

//Program_2.cpp

#include "Program_2.h"

using namespace std;
using namespace sandwich;

int SandwichMaker::Control()
{
    SandwichMaker swm;
    //vector<string> ingredients;
    swm.Menu(swm.s, swm.ingredients);

    while (swm.s > 0)
    {
        swm.Menu(swm.s, swm.ingredients);
    }

    system("PAUSE");
    return 0;
}

void SandwichMaker::Menu(int &s, vector<string>& vec)
{
    SandwichMaker swm;
    cout << "Please choose what you would like to do and type the ingredient (1 and 2 only)\n (0 quit, 1 add ingredient, 2 remove ingredient, 3 make sandwich): ";
    cin >> s;

    string tempIngredient = "";

    switch (s)
    {
    case 1://add
        //cout << "Enter the ingredient you are going to add.\n";
        cin.ignore();
        getline(cin, tempIngredient);
        vec.push_back(tempIngredient);
        cout << " Ingredient has been added\n";
        break;
    case 2://remove
        if (!vec.empty())
            vec.pop_back();
        else
            cout << " Nothing has been added yet\n";
        break;
    case 3: //make the sandwich
        swm.PrintSandwich(vec);
        break;
    default:
        break;
    }
}

void SandwichMaker::PrintSandwich(vector<string>& vec)
{
    cout << "Your sandwich contains: ";
    for (size_t i = 0; i < vec.size(); i++)
    {
        cout << i << ", " << vec[i] << endl;
    }
}

cant post an images soo link? https://imgur.com/a/mK0UrEU  of all the errors that are getting spit out because of vector.


问:
packaged_task example problem? Stroustrup example modification
I'm trying to modify the example given in Stroustrup C++ 4th Ed Page 122 to call the accumulator() function directly with iterators.  Specifically remove use of *double and use iterators.

So far, I have this, however it has compilation problems which I don't understand.

Does anyone have any pointers on accomplishing this?

```<code>#include <iostream>
#include <memory>
#include <thread>
#include <numeric>
#include <vector>
#include <future>
using namespace std;

double comp2(vector<double>& v) {
  using Task_type = double(vector<double>::iterator,
               vector<double>::iterator, double);

  packaged_task<Task_type> pt0 {accumulate};
  packaged_task<Task_type> pt1 {accumulate};

#if 0
  future<double> f0 {pt0.get_future()};
  future<double> f1 {pt1.get_future()};

  double *first = &v[0];
  // move required bc package_task cannot be copied
  thread t1 {move(pt0), first, first + v.size()/2, 0};
  thread t2 {move(pt1), first + v.size()/2, first + v.size(), 0};

  t1.join();
  t2.join();

  return f0.get() + f1.get();
#endif
}

int main(int argc, char *argv[])
{
  vector<double> v = {1.0, 1.0, 1.0, 1.0};

  cout << "v: " << comp2(v) << endl;

  return 0;
}
</code>```

and the error is:

```<code>g++ -lpthread -pedantic -Wall test87.cc && ./a.out
test87.cc: In function ‘double comp2(std::vector<double>&)’:
test87.cc:13:43: error: no matching function for call to ‘std::packaged_task<double(__gnu_cxx::__normal_iterator<double*, std::vector<double> >, __gnu_cxx::__normal_iterator<double*, std::vector<double> >, double)>::packaged_task(<brace-enclosed initializer list>)’
   packaged_task<Task_type> pt0 {accumulate};
                                           ^
In file included from test87.cc:6:
/usr/include/c++/8/future:1528:2: note: candidate: ‘template<class _Allocator> std::packaged_task<_Res(_ArgTypes ...)>::packaged_task(std::allocator_arg_t, const _Allocator&, std::packaged_task<_Res(_ArgTypes ...)>&&)’
  packaged_task(allocator_arg_t, const _Allocator&,
  ^~~~~~~~~~~~~
/usr/include/c++/8/future:1528:2: note:   template argument deduction/substitution failed:
test87.cc:13:43: note:   candidate expects 3 arguments, 1 provided
   packaged_task<Task_type> pt0 {accumulate};
</code>```

答:
std::accumulate is not a function, it's a function template. To construct the packaged_task, you need to pass it a concrete function, like this:

```<code>packaged_task<Task_type> pt0 {accumulate<vector<double>::iterator, double>};
packaged_task<Task_type> pt1 {accumulate<vector<double>::iterator, double>};
</code>```

You should also make first an iterator instead of a pointer, since it's not guaranteed that an iterator is implemented as a pointer.

```<code>auto first = v.begin();
</code>```

Here's a demo.

Body:
I'm trying to modify the example given in Stroustrup C++ 4th Ed Page 122 to call the accumulator() function directly with iterators.  Specifically remove use of *double and use iterators.

So far, I have this, however it has compilation problems which I don't understand.

Does anyone have any pointers on accomplishing this?

#include <iostream>
#include <memory>
#include <thread>
#include <numeric>
#include <vector>
#include <future>
using namespace std;

double comp2(vector<double>& v) {
  using Task_type = double(vector<double>::iterator,
               vector<double>::iterator, double);

  packaged_task<Task_type> pt0 {accumulate};
  packaged_task<Task_type> pt1 {accumulate};

#if 0
  future<double> f0 {pt0.get_future()};
  future<double> f1 {pt1.get_future()};

  double *first = &v[0];
  // move required bc package_task cannot be copied
  thread t1 {move(pt0), first, first + v.size()/2, 0};
  thread t2 {move(pt1), first + v.size()/2, first + v.size(), 0};

  t1.join();
  t2.join();

  return f0.get() + f1.get();
#endif
}

int main(int argc, char *argv[])
{
  vector<double> v = {1.0, 1.0, 1.0, 1.0};

  cout << "v: " << comp2(v) << endl;

  return 0;
}

and the error is:

g++ -lpthread -pedantic -Wall test87.cc && ./a.out
test87.cc: In function ‘double comp2(std::vector<double>&)’:
test87.cc:13:43: error: no matching function for call to ‘std::packaged_task<double(__gnu_cxx::__normal_iterator<double*, std::vector<double> >, __gnu_cxx::__normal_iterator<double*, std::vector<double> >, double)>::packaged_task(<brace-enclosed initializer list>)’
   packaged_task<Task_type> pt0 {accumulate};
                                           ^
In file included from test87.cc:6:
/usr/include/c++/8/future:1528:2: note: candidate: ‘template<class _Allocator> std::packaged_task<_Res(_ArgTypes ...)>::packaged_task(std::allocator_arg_t, const _Allocator&, std::packaged_task<_Res(_ArgTypes ...)>&&)’
  packaged_task(allocator_arg_t, const _Allocator&,
  ^~~~~~~~~~~~~
/usr/include/c++/8/future:1528:2: note:   template argument deduction/substitution failed:
test87.cc:13:43: note:   candidate expects 3 arguments, 1 provided
   packaged_task<Task_type> pt0 {accumulate};

Body:
std::accumulate is not a function, it's a function template. To construct the packaged_task, you need to pass it a concrete function, like this:

packaged_task<Task_type> pt0 {accumulate<vector<double>::iterator, double>};
packaged_task<Task_type> pt1 {accumulate<vector<double>::iterator, double>};

You should also make first an iterator instead of a pointer, since it's not guaranteed that an iterator is implemented as a pointer.

auto first = v.begin();

Here's a demo.


问:
Woocommerce: $_GET custom parameter (link in new order mail) to updale Woocommerce order status
When a user makes an order the order is set to on hold and the new order email is sent to the shop with a link to confirm the order. I can add the link but I can't make it to change the status of the order (to processing) in Woocommerce when I click on the link the email.

This is how I add the link to the email (this part works)

```<code>add_action( 'woocommerce_email_order_meta', 'ct_add_link_to_new_order__email', 20, 4 );

function ct_add_link_to_new_order__email( $order, $sent_to_admin, $plain_text, $email ) {
   if ( $email->id == 'new_order' ) {

      $link = '<p>';

      $link .= '<a href="'. get_site_url() .'/order/s='. absint( $order->id ) .'" >';

      $link .= pll__( 'Click here to go confirm the order' );

      $link .= '</a>';

      $link .= '</p>';

     echo $link;

   }
}

</code>```

This is how I thought I would get the parameter and change the order status

```<code>add_action( 'init', 'ct_confirm_order');
function ct_confirm_order(){
      if ( isset( $_GET['s'] ) ){
         $order_id = intval( $_GET['s'] );
         $order = new WC_Order($order_id);
         $order = wc_get_order( $order_id );
         $order->update_status( "processing" );
         return;
         }
}

</code>```

When I click the link I get a 404 page does not exist (I created an Order page) and the status is not changed.

答:
you can't just use the $_GET superglobal to grab our query variable

Instead you have to access the query_vars property of the $wp_query object.

```<code>if(isset($wp_query->query_vars['s'])) {
 $sMsdsCat = urldecode($wp_query->query_vars['s']);
}
</code>```

you also need to tell WordPress how to populate that query variable

```<code>function add_rewrite_rules($aRules) {
 $aNewRules = array('order/([^/]+)/?$' => 'index.php?pagename=order&s=$matches[1]');
 $aRules = $aNewRules + $aRules;
 return $aRules;
}

add_filter('rewrite_rules_array', 'add_rewrite_rules');
</code>```

Body:
When a user makes an order the order is set to on hold and the new order email is sent to the shop with a link to confirm the order. I can add the link but I can't make it to change the status of the order (to processing) in Woocommerce when I click on the link the email.

This is how I add the link to the email (this part works)

add_action( 'woocommerce_email_order_meta', 'ct_add_link_to_new_order__email', 20, 4 );

function ct_add_link_to_new_order__email( $order, $sent_to_admin, $plain_text, $email ) {
   if ( $email->id == 'new_order' ) {

      $link = '
';

      $link .= 'id ) .'" >';

      $link .= pll__( 'Click here to go confirm the order' );

      $link .= '';

      $link .= '
';

     echo $link;

   }
}

This is how I thought I would get the parameter and change the order status

add_action( 'init', 'ct_confirm_order');
function ct_confirm_order(){
      if ( isset( $_GET['s'] ) ){
         $order_id = intval( $_GET['s'] );
         $order = new WC_Order($order_id);
         $order = wc_get_order( $order_id );
         $order->update_status( "processing" );
         return;
         }
}

When I click the link I get a 404 page does not exist (I created an Order page) and the status is not changed.

Body:
you can't just use the $_GET superglobal to grab our query variable

Instead you have to access the query_vars property of the $wp_query object.

if(isset($wp_query->query_vars['s'])) {
 $sMsdsCat = urldecode($wp_query->query_vars['s']);
}

you also need to tell WordPress how to populate that query variable

function add_rewrite_rules($aRules) {
 $aNewRules = array('order/([^/]+)/?$' => 'index.php?pagename=order&s=$matches[1]');
 $aRules = $aNewRules + $aRules;
 return $aRules;
}

add_filter('rewrite_rules_array', 'add_rewrite_rules');


问:
Assigning same action to multiple buttons at once
can I assign same action to multiple buttons in the Interface Builder once they are all selected by one connection?</p>

答:
This problem is discussed in numerous threads but it isn't always just laid out simply.  The easiest route is to create a function such as the one below.  It takes the sender, in this case a UIButton, and gets the tag.  You can then run whatever code you want based on that.

```<code>- (IBAction) buttonClick: (id) sender {

    UIButton *button = (UIButton *)sender;
    int row = button.tag;
    NSLog(@"Button clicked: %i", row);
    if (row == 1 ) {
    // do something
    }
}
</code>```

In Interface Builder, attach the button to the function, and then use the Attributes Inspector to set the Tag value for each button, giving each one a different integer value.

ContentLicense: CC BY-SA 2.5

Body:
This problem is discussed in numerous threads but it isn't always just laid out simply.  The easiest route is to create a function such as the one below.  It takes the sender, in this case a UIButton, and gets the tag.  You can then run whatever code you want based on that.

- (IBAction) buttonClick: (id) sender {

    UIButton *button = (UIButton *)sender;
    int row = button.tag;
    NSLog(@"Button clicked: %i", row);
    if (row == 1 ) {
    // do something
    }
}

In Interface Builder, attach the button to the function, and then use the Attributes Inspector to set the Tag value for each button, giving each one a different integer value.


问:
ValueError: invalid literal for int() with base 10: ''
I got this error from my code:

ValueError: invalid literal for int() with base 10: ''.
```

What does it mean? Why does it occur, and how can I fix it?

答:
your answer is throwing errors because of this line

```<code>readings = int(readings)
</code>```

Here you are trying to convert a string into int type which is not base-10. you can convert a string into int only if it is base-10 otherwise it will throw ValueError, stating invalid literal for int() with base 10.

Body:
I got this error from my code:

ValueError: invalid literal for int() with base 10: ''.

What does it mean? Why does it occur, and how can I fix it?

Body:
your answer is throwing errors because of this line

readings = int(readings)

Here you are trying to convert a string into int type which is not base-10. you can convert a string into int only if it is base-10 otherwise it will throw ValueError, stating invalid literal for int() with base 10.


问:
How do I link a library in VSCode?
I'm trying to include curses.h and some functions from that lib (specifically detecting a keyboard hit without stopping), but whenever I try, it gives the error "symbols not found." I'm assuming that this is because the clang++ compiler sees curses.h as a C library. I've gathered I need to link curses.h, but I don't know how and I could not find any real guides.

I'm writing a program in C++ using VSCode and clang++ on a mac. Any help is appreciated.

答: For anyone else who has this problem- my clang version was outdated. It was installed, so after a brief check, I thought all was good. However, it was not able to compile (nor find some libs for some reason) the newer versions of C++. Installing the latest version of clang fixed all issues.</p>

Title: How do I link a library in VSCode?


问:
Override Outlook dark mode button background
I am trying to add support for dark mode to my email templates, however am having an issue when it comes to Outlook. For some reason Outlook is partially overriding the background of my button which is causing it to display incorrectly:

The HTML for the button is as follows:

```<code><td align="center" style="word-break: break-word; font-family: "Nunito Sans", Helvetica, Arial, sans-serif; font-size: 16px;">
  <a href="{{action_url}}" class="f-fallback button" target="_blank" style="color: #fff; border-color: #13c2c2; border-style: solid; border-width: 10px 18px; background-color: #13c2c2 !important; background-image: linear-gradient(#13c2c2, #13c2c2) !important; display: inline-block; text-decoration: none; border-radius: 3px; box-shadow: 0 2px 3px rgba(0, 0, 0, 0.16); -webkit-text-size-adjust: none; box-sizing: border-box;">Reset your password</a>
</td>
</code>```

The button has the following inline style (formatted for your convenince):

color: #fff;
border-color: #13c2c2;
border-style: solid;
border-width: 10px 18px;
background-color: #13c2c2 !important;
background-image: linear-gradient(#13c2c2, #13c2c2) !important;
display: inline-block;
text-decoration: none;
border-radius: 3px;
box-shadow: 0 2px 3px rgba(0, 0, 0, 0.16);
-webkit-text-size-adjust: none;
box-sizing: border-box;
```

<p>Additionally, I've already added the following to the <code><head></code> section of my email.</p>

```<meta name="color-scheme" content="light dark" />
<meta name="supported-color-schemes" content="light dark" />
```

Thanks!

答:
Well, it's not entirely true that you cannot change the background-color to what is set for the border. You actually can change that to tackle this hellish issue in Outlook. Sometimes though, and this case is one of those 'sometimes'.

You use background-image already and that is indeed the way to go. Replace the linear-gradient by a 1x1 pixel .png file that exactly contains that border-colour and repeat that. That color will not be inverted - it's an image after all. For the sake of compatibility, you could try to apply background="file here" as an attribute. It will repeat infinitely, but it's exactly what we want. The color will, however, remain white, unless you make that entire button a separate image.

Body:
I am trying to add support for dark mode to my email templates, however am having an issue when it comes to Outlook. For some reason Outlook is partially overriding the background of my button which is causing it to display incorrectly:

The HTML for the button is as follows:

  Reset your password

The button has the following inline style (formatted for your convenince):

color: #fff;
border-color: #13c2c2;
border-style: solid;
border-width: 10px 18px;
background-color: #13c2c2 !important;
background-image: linear-gradient(#13c2c2, #13c2c2) !important;
display: inline-block;
text-decoration: none;
border-radius: 3px;
box-shadow: 0 2px 3px rgba(0, 0, 0, 0.16);
-webkit-text-size-adjust: none;
box-sizing: border-box;

Additionally, I've already added the following to the  section of my email.

<meta name="color-scheme" content="light dark" />
<meta name="supported-color-schemes" content="light dark" />

Thanks!


问:
Can't access ansible_host property of my inventory items
I have this inventory file:

```<code>[masters]
master ansible_host=1.2.3.4.5 ansible_user=ubuntu

[workers]
worker1 ansible_host=1.2.3.4.5 ansible_user=ubuntu

[nodes]
master ansible_host=1.2.3.4.5 ansible_user=ubuntu
worker1 ansible_host=1.2.3.4.5 ansible_user=ubuntu

[fileserver]
fs-01 ansible_host=1.2.3.4.5 ansible_user=ubuntu
</code>```

I'm trying to install an SSH key from my local machine to all inventory machines.

```<code>- name: install the SSH key on all machines.
  hosts: 127.0.0.1
  connection: local
  tasks:
  - name: install SSH-key
    shell: sshpass -p {{ ssh_key_password }} ssh-copy-id -i /id_rsa.pub -o StrictHostKeyChecking ubuntu@{{ item }}
    with_items:
      - "{{ hostvars['all'].ansible_host }}"
</code>```

However, it ends with this error:

```<code>fatal: [127.0.0.1]: FAILED! => {"msg": "\"hostvars['all']\" is undefined"}
</code>```

I'm trying to get the ansible_host 1.2.3.4.5 of each unique inventory name in my inventory. However, I'm not having much luck. What am I doing wrong?

Body:
I have this inventory file:

[masters]
master ansible_host=1.2.3.4.5 ansible_user=ubuntu

[workers]
worker1 ansible_host=1.2.3.4.5 ansible_user=ubuntu

[nodes]
master ansible_host=1.2.3.4.5 ansible_user=ubuntu
worker1 ansible_host=1.2.3.4.5 ansible_user=ubuntu

[fileserver]
fs-01 ansible_host=1.2.3.4.5 ansible_user=ubuntu

I'm trying to install an SSH key from my local machine to all inventory machines.

- name: install the SSH key on all machines.
  hosts: 127.0.0.1
  connection: local
  tasks:
  - name: install SSH-key
    shell: sshpass -p {{ ssh_key_password }} ssh-copy-id -i /id_rsa.pub -o StrictHostKeyChecking ubuntu@{{ item }}
    with_items:
      - "{{ hostvars['all'].ansible_host }}"

However, it ends with this error:

fatal: [127.0.0.1]: FAILED! => {"msg": "\"hostvars['all']\" is undefined"}

I'm trying to get the ansible_host 1.2.3.4.5 of each unique inventory name in my inventory. However, I'm not having much luck. What am I doing wrong?

Body:
I think the referencing you are looking for is something as below

---
- hosts: localhost
  connection: local
  gather_facts: no
  tasks:
  - name: Print all hosts
    debug:
     msg: "{{hostvars[item]['ansible_host']}}"
    with_items:
    - "{{groups['all']}}"

This gives the output

PLAY [localhost] ***************************************************************************************************************************************************************************************************************************************************************

TASK [Print all hosts] *******************************************************************************************************************************************************************************************************************************************************************
ok: [localhost] => (item=master) => {
    "msg": "1.2.3.4.5"
}
ok: [localhost] => (item=worker1) => {
    "msg": "1.2.3.4.5"
}
ok: [localhost] => (item=fs-01) => {
    "msg": "1.2.3.4.5"
}

PLAY RECAP *********************************************************************************************************************************************************************************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0


问:
can the sorting from an order by statement be saved explicitly in a table (SQL Server Version 2017)
I have this table

```<code>AGENT_CODE AGENT_NAME      WORKING_AREA
---------- ------------- ---------------
A001       Subbarao        Bangalore
A002       Mukesh          Mumbai
A003       Alex            London
</code>```

Sorting the above table should give me the below result.

```<code>select *
from table_name
order by agent_name;

AGENT_CODE AGENT_NAME      WORKING_AREA
---------- ------------- ---------------
A003       Alex             London
A002       Mukesh           Mumbai
A001       Subbarao         Bangalore
</code>```

Now, I want to keep my table and save the sorted order on the positioned rows permanently onto the same table

Eg: when I run

```<code> select * from table_name
</code>```

the results should appear as below without ordering

```<code>AGENT_CODE AGENT_NAME      WORKING_AREA
---------- ------------- ---------------
A003       Alex             London
A002       Mukesh           Mumbai
A001       Subbarao         Bangalore
</code>```

答:
You could create a clustered index on the table ( if there isnt already one). Then your table will be sorted in that order...but it does not guarantee that a select query will return the data in that order. Only by specifying an order by clause will do so.

Why is it not possible to use an order by?

Body:
I have this table

AGENT_CODE AGENT_NAME      WORKING_AREA
---------- ------------- ---------------
A001       Subbarao        Bangalore
A002       Mukesh          Mumbai
A003       Alex            London

Sorting the above table should give me the below result.

select *
from table_name
order by agent_name;

AGENT_CODE AGENT_NAME      WORKING_AREA
---------- ------------- ---------------
A003       Alex             London
A002       Mukesh           Mumbai
A001       Subbarao         Bangalore

Now, I want to keep my table and save the sorted order on the positioned rows permanently onto the same table

Eg: when I run

 select * from table_name

the results should appear as below without ordering

AGENT_CODE AGENT_NAME      WORKING_AREA
---------- ------------- ---------------
A003       Alex             London
A002       Mukesh           Mumbai
A001       Subbarao         Bangalore


问:
Silverlight app in iframe access to parent window
I have Silverlight application test page named A.html hosted in an iframe which is an element of B.html, so is there a way for Silverlight app to access elements in B.html by referring something like HtmlPage.Document..?

Thanks!

答:
In the container html page, add following function:

```<code>function GetParent
{
   return parent;
}
</code>```

In the SL control, do this:

```<code>HtmlWindow parent = (HtmlWindow)HtmlPage.Window.Invoke("GetParentWindow");
</code>```

Now to invoke any function from the parent Html page, just call

```<code>parent.Invoke("myFunction");
</code>```

Hope this solves your issue.

Ahmad.

Body:
In the container html page, add following function:

function GetParent
{
   return parent;
}

In the SL control, do this:

HtmlWindow parent = (HtmlWindow)HtmlPage.Window.Invoke("GetParentWindow");

Now to invoke any function from the parent Html page, just call

parent.Invoke("myFunction");

Hope this solves your issue.

Ahmad.


问:
Load Certain CSV Data Into HTML Textarea
i'm trying to ask someones help here with this.

This script works fine and shows all the csv file data into textarea, but I want it to only load the first column and skip the first 3 rows in the csv file. Is it possible to modify this code to achieve my goals?

Here is how it currently works: https://jsfiddle.net/mhwdjzbo/

Thanks for any suggestions..

Here is the code:

```<code><script type="text/javascript">
    $(document).ready(function(){
        $("#notification_email_id").change(function(e){
            var ext = $("input#notification_email_id").val().split(".").pop().toLowerCase();

            if($.inArray(ext, ["csv"]) == -1){
                alert('Please upload CSV file');
                return false;
            }

            if(e.target.files != undefined){
                var reader = new FileReader();
                reader.onload = function(e){
                    var csv_val=e.target.result.split("\r\n");
                    var csv_value=""+csv_val+"".split(",");
                    var input_data="";
                    for(var i=0;i<csv_value.length;i++){
                        var temp=csv_value[i];
                        var input_data=input_data+""+temp;
                    }
                    final_input_data = input_data.slice(0, -1);
                    $("#notification_email").val(final_input_data);
                };
                reader.readAsText(e.target.files.item(0));
            }
            return false;
        });
    });
    </script>
</head>
<body>
    <table border="0">
        <tr>
            <td><b>How to read data From CSV file using jquery?</b></td>
        </tr>
        <tr>
            <td><textarea class="form-control" name="notification_email" id="notification_email" rows="4" placeholder="CSV file only" cols="40" readonly="readonly" required></textarea></td>
        </tr>
        <tr>
            <td><input name="notification_email_id" id="notification_email_id" type="file" class="" accept=".csv" /></td>
        </tr>
    </table>
</body>
</code>```

答:
You can change your reader.onload function to be like this

reader.onload = function(e) {
  var csv_val = e.target.result.split("\n");
  var final_input_data = "";
  for (var i = 3; i < csv_val.length; i++) {
    final_input_data += csv_val[i].split(' ')[0]+'\n';
  }
  $("#notification_email").val(final_input_data);
};```

Body:
i'm trying to ask someones help here with this.

This script works fine and shows all the csv file data into textarea, but I want it to only load the first column and skip the first 3 rows in the csv file. Is it possible to modify this code to achieve my goals?

Here is how it currently works: https://jsfiddle.net/mhwdjzbo/

Thanks for any suggestions..

Here is the code:

            How to read data From CSV file using jquery?

            <textarea class="form-control" name="notification_email" id="notification_email" rows="4" placeholder="CSV file only" cols="40" readonly="readonly" required></textarea>

            <input name="notification_email_id" id="notification_email_id" type="file" class="" accept=".csv" />


问:
r raster how to vectorize a function to use with overlay
I want to do a raster overlay that uses this function where x and y are rasters and Tbase is a constant.

```<code>gddFunction <- function(x, y, z) {(x + y)/2 - z}
</code>```

like this

```<code>library(raster)
gdd <- overlay(x = tmax_clamped, y = tmin_clamped, z = Tbase, fun = gddFunction)
</code>```

I get the following error message

Error in (function (x, fun, filename = "", recycle = TRUE, forcefun =
  FALSE,  :    cannot use this formula, probably because it is not
  vectorized

I tried following the examples in Help, as follows

```<code> vgddFunction <- Vectorize(gddFunction, SIMPLIFY = FALSE)
 gdd <- overlay(x = tmax_clamped, y = tmin_clamped, z = Tbase, fun = vgddFunction)
</code>```

but got the same error message.

I suspect the problem is that I need z to be a vector of constant values or maybe a raster layer of constant values. But I was hoping the Vectorize operation would do that.

Straightforward map algebra works, as in

```<code>gdd <- (x + y)/2 - z
</code>```

but its slow and I was hoping to speed up the calculation by using overlay

答:
raster::overlay only allows raster arguments to be passed as extra arguments through the ... (see ?overlay). So you can't do directly what are doing now. But we can avoid that problem. A reproducible example:

```<code>library(raster)
r <- raster(ncol = 10, nrow = 10)
r1 <- init(r, fun = runif)
r2 <- init(r, fun = runif)
z <- 3
</code>```

Your error:

```<code>gddFunction <- function(x, y, z) {(x + y)/2 - z}
gdd <- overlay(x = r1, y = r2, z = z, fun = gddFunction)
</code>```

```<code>Error in (function (x, fun, filename = "", recycle = TRUE, forcefun = FALSE,  :
  cannot use this formula, probably because it is not vectorized
</code>```

If we can't pass z directly, we can pass it indirectly with some functional programming:

```<code>gddFunction2 <- function(z) {
  function(x, y) (x + y) / 2 - z
}
gdd <- overlay(x = r1, y = r2, fun = gddFunction2(z))
</code>```

Here, gddFunction2 will return another function that only has an x and y argument that can take the rasters, but you can still change the constant z, which is now an argument to gddFunction2.

You could also write that as:

```<code>gddFunction <- gddFunction2(z)
gdd <- overlay(x = r1, y = r2, fun = gddFunction)
</code>```

Note that your original gddFunction is already vectorized, so that error message is guessing at the problem incorrectly.

Body:
I want to do a raster overlay that uses this function where x and y are rasters and Tbase is a constant.

gddFunction <- function(x, y, z) {(x + y)/2 - z}

like this

library(raster)
gdd <- overlay(x = tmax_clamped, y = tmin_clamped, z = Tbase, fun = gddFunction)

I get the following error message

Error in (function (x, fun, filename = "", recycle = TRUE, forcefun =
  FALSE,  :    cannot use this formula, probably because it is not
  vectorized

I tried following the examples in Help, as follows

 vgddFunction <- Vectorize(gddFunction, SIMPLIFY = FALSE)
 gdd <- overlay(x = tmax_clamped, y = tmin_clamped, z = Tbase, fun = vgddFunction)

but got the same error message.

I suspect the problem is that I need z to be a vector of constant values or maybe a raster layer of constant values. But I was hoping the Vectorize operation would do that.

Straightforward map algebra works, as in

gdd <- (x + y)/2 - z

but its slow and I was hoping to speed up the calculation by using overlay

Body:
raster::overlay only allows raster arguments to be passed as extra arguments through the ... (see ?overlay). So you can't do directly what are doing now. But we can avoid that problem. A reproducible example:

library(raster)
r <- raster(ncol = 10, nrow = 10)
r1 <- init(r, fun = runif)
r2 <- init(r, fun = runif)
z <- 3

Your error:

gddFunction <- function(x, y, z) {(x + y)/2 - z}
gdd <- overlay(x = r1, y = r2, z = z, fun = gddFunction)

Error in (function (x, fun, filename = "", recycle = TRUE, forcefun = FALSE,  :
  cannot use this formula, probably because it is not vectorized

If we can't pass z directly, we can pass it indirectly with some functional programming:

gddFunction2 <- function(z) {
  function(x, y) (x + y) / 2 - z
}
gdd <- overlay(x = r1, y = r2, fun = gddFunction2(z))

Here, gddFunction2 will return another function that only has an x and y argument that can take the rasters, but you can still change the constant z, which is now an argument to gddFunction2.

You could also write that as:

gddFunction <- gddFunction2(z)
gdd <- overlay(x = r1, y = r2, fun = gddFunction)

Note that your original gddFunction is already vectorized, so that error message is guessing at the problem incorrectly.


问:
How can I change encoding to UTF-8 for linux redirection..?
Currently I use vm in GCP.
I want to get stackdriver logs to text file(my log includes Korean(unicode).)

When I try to read using gcloud command, I can read my log (Korean also readable..)
But when I try write to file using redirect command (>),  all Korean characters converted to '???'

my command is here:

```<code>gcloud beta logging read --project=[my project] '[filters]' > log
</code>```

How can I read korean character via file?

Thanks :)

答:
This can be fixed by setting PYTHONIOENCODING to utf-8.

You can do this by adding PYTHONIOENCODING=UTF-8 gcloud ...

Body:
Currently I use vm in GCP.
I want to get stackdriver logs to text file(my log includes Korean(unicode).)

When I try to read using gcloud command, I can read my log (Korean also readable..)
But when I try write to file using redirect command (>),  all Korean characters converted to '???'

my command is here:

gcloud beta logging read --project=[my project] '[filters]' > log

How can I read korean character via file?

Thanks :)


问:
Python Application Assistance
The requirements of my project are as follows:

• Create a Python application that will loop between 1 and 100

• The numbers are to be printed out alongside their squared value

• The app should stop when a squared value of 200 or more is reached

• Reconfigure the application to take in a user value as desired.
For example, if you were to input the value 8 (DO NOT USE THIS VALUE), your
application would produce all squared values from 1 to 8.

This is what I have so far,

**def sq_nos(start, end):
    for i in range(start, end):
        j = i**2
        print(i, j)
        if j > 200:
            break
start = int(input("enter start: "))
end = int(input("enter end: "))
sq_nos(start, end)**

This code is still printing the square value of 255, any solutions?

Any other feedback would be appreciated too.

答:
You have to test before printing the square value. Thus:

```<code>def sq_nos(start, end):
    for i in range(start, end):
        j = i**2
        if j> 200 :
            break
        else:
            print(i,j)
</code>```

But to solve the assignment, I don't know why you are asking for the start value. You only have to ask for the limit of the squared value. Thus, the following would be correct:

```<code>def sq_nos(limit ):
    for i in range(1, 100):
        if i**2 > limit:
            return
        else:
            print(i,i**2)

limit = int(input("enter the limit of the squared value: "))
sq_nos(limit )
</code>```

Title: Python Application Assistance

Body:
You have to test before printing the square value. Thus:

def sq_nos(start, end):
    for i in range(start, end):
        j = i**2
        if j> 200 :
            break
        else:
            print(i,j)

But to solve the assignment, I don't know why you are asking for the start value. You only have to ask for the limit of the squared value. Thus, the following would be correct:

def sq_nos(limit ):
    for i in range(1, 100):
        if i**2 > limit:
            return
        else:
            print(i,i**2)

limit = int(input("enter the limit of the squared value: "))
sq_nos(limit )