问:
How do I use key value pairs from a dictionary to feed table view cells their title?
I'm currently trying to complete the finishing touches on my first app. Written in swift via Xcode as part of a course I'm taking, I've got a list of images that appear in a table view, and I want to programmatically alter the names of the files so it doesn't display IMG_xxxxx.jpg. I created a dictionary to associate each photo with the desired name, but I cannot figure out how to make the table view display a cell title that is the value of a key in said dictionary based on which file gets loaded in any given cell.

```<code>//This is the dictionary
let imageTitles = ["IMG_1085.JPG" : "Num Num Num",
                   "IMG_1251.JPG" : "Star of the Show",
                   "IMG_1643.JPG" : "Ante Up",
                   "IMG_1630.jpg" : "Someone called my name?",
                   "IMG_1340.JPG" : "Ahhhhhhhhh",
                   "IMG_1595.jpg" : "Focus",
                   "IMG_1689.JPG" : "He Likes Me",
                   "IMG_1676.jpg" : "Warm and Cozy",
                   "IMG_1688.JPG" : "It's Like Looking Into a Mirror...",
                   ]
</code>```

These are the bits that load the name of a cell. One is commented out (that's the 'official' code taught by the instructor, I'm trying to take it one step further for learning's sake) and the other is my own attempts at completing this task (I've not saved each and every try- I just rewrite with something new when unsuccessful.) The other comment was more a note to self when I decided to add this feature. I suppose it is possible I'm trying to do this in the wrong spot, but I don't think that is the case. The error thrown is saying that I can't have a string:string reference when int is expected, and that makes sense (logically, I would assume .row would be an int value, but I don't know how to make a statement that asks for a string:string value, which I believe would solve my problem).

```<code> override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Picture", for: indexPath)
    //cell.textLabel?.text = pictures[indexPath.row]
    cell.textLabel?.text = imageTitles[indexPath.row]
    //this is where I need to make the reference of the dictonary

    return cell
}
</code>```

Lastly, if I'm right about just not knowing how to write a parameter that needs string:string, is there any way to have figured that out burdened with inexperience? I tried looking for existing threads on sites like this but without any luck.

Thanks in advance for any assistance!

答:
You need an array as data source, simple example an array of the file names

```<code>var pictures = ["IMG_1085.JPG", "IMG_1251.JPG", "IMG_1643.JPG", "IMG_1630.jpg", "IMG_1340.JPG", "IMG_1595.jpg", "IMG_1689.JPG", "IMG_1676.jpg", "IMG_1688.JPG"]
</code>```

In cellForRow get the file name for the index path and map it to the title

```<code> override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Picture", for: indexPath)
    let fileName = pictures[indexPath.row]
    cell.textLabel?.text = imageTitles[fileName] ?? "N/A"
    return cell
}
</code>```

A better solution is a custom struct as model which includes both the file name and the human readable description.

Body:
I'm currently trying to complete the finishing touches on my first app. Written in swift via Xcode as part of a course I'm taking, I've got a list of images that appear in a table view, and I want to programmatically alter the names of the files so it doesn't display IMG_xxxxx.jpg. I created a dictionary to associate each photo with the desired name, but I cannot figure out how to make the table view display a cell title that is the value of a key in said dictionary based on which file gets loaded in any given cell.

//This is the dictionary
let imageTitles = ["IMG_1085.JPG" : "Num Num Num",
                   "IMG_1251.JPG" : "Star of the Show",
                   "IMG_1643.JPG" : "Ante Up",
                   "IMG_1630.jpg" : "Someone called my name?",
                   "IMG_1340.JPG" : "Ahhhhhhhhh",
                   "IMG_1595.jpg" : "Focus",
                   "IMG_1689.JPG" : "He Likes Me",
                   "IMG_1676.jpg" : "Warm and Cozy",
                   "IMG_1688.JPG" : "It's Like Looking Into a Mirror...",
                   ]

These are the bits that load the name of a cell. One is commented out (that's the 'official' code taught by the instructor, I'm trying to take it one step further for learning's sake) and the other is my own attempts at completing this task (I've not saved each and every try- I just rewrite with something new when unsuccessful.) The other comment was more a note to self when I decided to add this feature. I suppose it is possible I'm trying to do this in the wrong spot, but I don't think that is the case. The error thrown is saying that I can't have a string:string reference when int is expected, and that makes sense (logically, I would assume .row would be an int value, but I don't know how to make a statement that asks for a string:string value, which I believe would solve my problem).

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Picture", for: indexPath)
    //cell.textLabel?.text = pictures[indexPath.row]
    cell.textLabel?.text = imageTitles[indexPath.row]
    //this is where I need to make the reference of the dictonary

    return cell
}

Lastly, if I'm right about just not knowing how to write a parameter that needs string:string, is there any way to have figured that out burdened with inexperience? I tried looking for existing threads on sites like this but without any luck.

Thanks in advance for any assistance!

Body:
You need an array as data source, simple example an array of the file names

var pictures = ["IMG_1085.JPG", "IMG_1251.JPG", "IMG_1643.JPG", "IMG_1630.jpg", "IMG_1340.JPG", "IMG_1595.jpg", "IMG_1689.JPG", "IMG_1676.jpg", "IMG_1688.JPG"]

In cellForRow get the file name for the index path and map it to the title

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Picture", for: indexPath)
    let fileName = pictures[indexPath.row]
    cell.textLabel?.text = imageTitles[fileName] ?? "N/A"
    return cell
}

A better solution is a custom struct as model which includes both the file name and the human readable description.


来源: stackexchange

问:
How do I only check 1 Div Block but not anything else
Recently I started doing a OnePager Website; I'm having trouble with this div block here "Box-Middle" and "Text-Middle":

I want "Elektro One and Elektroinstallationen, Produkte & Kommunikationstechnik" to be vertically aligned in the white box, but I cant figure it how?

And also I want the text "Elektro One and Elektroinstallationen, Produkte & Kommunikationstechnik" to not have opacity, because it would look better

And also I wanted to do the header list all center

#home {
  background-image: url(bilder/Hintergrund.jpg);
  background-position: center center;
  background-size: cover;
  box-shadow: 0 17px 53px rgba(0, 0, 0, 0.2);
}

#home h1,
h2 {
  margin-top: 25px;
}

#home h1 {
  margin-bottom: auto;
  color: #adadad;
}

#home h2 {
  color: #8a8a8a;
}

#Box-Middle {
  margin-top: 350px;
  width: 100%;
  height: 300px;
  background: white;
}

#home #Box-Middle {
  opacity: 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="home">
  <hr>
  <div id="Box-Middle">
    <div id="Text-Middle">
      <h1>Elektro One</h1>
      <h2>Elektroinstallationen, Produkte & Kommunikationstechnik</h2>
    </div>
  </div>
</section></code>```

答:
Add this to the div that contains what you want to center:

In this case: #Box-Middle

```<code>display: flex;
align-items: center;
</code>```

As for the Header list, wrap it around a div and set its text-aling to center:

```<code>.header-list {text-align: center;}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Recently I started doing a OnePager Website; I'm having trouble with this div block here "Box-Middle" and "Text-Middle":

I want "Elektro One and Elektroinstallationen, Produkte & Kommunikationstechnik" to be vertically aligned in the white box, but I cant figure it how?

And also I want the text "Elektro One and Elektroinstallationen, Produkte & Kommunikationstechnik" to not have opacity, because it would look better

And also I wanted to do the header list all center

#home {
  background-image: url(bilder/Hintergrund.jpg);
  background-position: center center;
  background-size: cover;
  box-shadow: 0 17px 53px rgba(0, 0, 0, 0.2);
}

#home h1,
h2 {
  margin-top: 25px;
}

#home h1 {
  margin-bottom: auto;
  color: #adadad;
}

#home h2 {
  color: #8a8a8a;
}

#Box-Middle {
  margin-top: 350px;
  width: 100%;
  height: 300px;
  background: white;
}

#home #Box-Middle {
  opacity: 50%;
}

Elektro One

Elektroinstallationen, Produkte & Kommunikationstechnik

Body:
Add this to the div that contains what you want to center:

In this case: #Box-Middle

display: flex;
align-items: center;

As for the Header list, wrap it around a div and set its text-aling to center:

.header-list {text-align: center;}


问:
How can I turn my DataFrame into a Radar Chart using Python?
I have a DataFrame I want to turn into a Radar Chart. The DataFrame looks like this when it's ran...

```<code>╔═══════════════════╗
║ Col A      Col B  ║
╠═══════════════════╣
║ Home       6.797  ║
║ Other      3.243  ║
║ Used       12.567 ║
║ New        8.985  ║
║ Service    1.345  ║
╚═══════════════════╝
</code>```

I repurposed some code I found on another Stack Overflow question pertaining to Pandas and Radar Charts and it works for the most part except I can't get the values of Col B to align properly within the chart. Below is the code I'm using...

```<code>df['Z'] = np.ones(len(df))
points = mergedFrame.pivot_table(values='Z', index=['Col A'], columns=['Col B'])
fig = plt.figure()
ax = fig.add_subplot(111, projection="polar")

theta = np.arange(len(points))/float(len(points))*2.*np.pi
l1, = ax.plot(theta, color="C2", marker="o", label="Name of Col B")

def _closeline(line):
    x, y = line.get_data()
    x = np.concatenate((x, [x[0]]))
    y = np.concatenate((y, [y[0]]))
    line.set_data(x, y)
[_closeline(l) for l in [l1]]

ax.set_xticks(radar)
ax.set_xticklabels(points.index)
plt.legend()
plt.title("Title")
plt.show()
</code>```

And the chart looks like this...

Since I'm still such a newbie at Python I have no idea what I'm doing wrong here. I've tried many things to modify the code including eliminating the first two lines of code and simply putting... points = df['Col B'] instead but all it did was erase the names around the circle while leaving everything else the same. What am I doing wrong here?

Also how can I fill the area inside the theta with a light green? I tried l1, = ax.fill(theta, facecolor = 'g', alpha=0.25) below the l1, = ax.plot(theta, color="C2", marker="o", label="Name of Col B") line, but it gave me this error AttributeError: 'Polygon' object has no attribute 'get_data' and I can't seem to work it out.

Any help is much appreciated!

答:
Here is an adaption of the code at this example to get you started with the way your data is stored.

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

df = pd.DataFrame({'Col A': ['home', 'other', 'used', 'new', 'service'],
                   'Col B': [6.797, 3.243, 12.567, 8.985, 1.345]})
fig = plt.figure()
ax = fig.add_subplot(111, projection="polar")

# theta has 5 different angles, and the first one repeated
theta = np.arange(len(df) + 1) / float(len(df)) * 2 * np.pi
# values has the 5 values from 'Col B', with the first element repeated
values = df['Col B'].values
values = np.append(values, values[0])

# draw the polygon and the mark the points for each angle/value combination
l1, = ax.plot(theta, values, color="C2", marker="o", label="Name of Col B")
plt.xticks(theta[:-1], df['Col A'], color='grey', size=12)
ax.tick_params(pad=10) # to increase the distance of the labels to the plot
# fill the area of the polygon with green and some transparency
ax.fill(theta, values, 'green', alpha=0.1)

# plt.legend() # shows the legend, using the label of the line plot (useful when there is more than 1 polygon)
plt.title("Title")
plt.show()
```

Body:
I have a DataFrame I want to turn into a Radar Chart. The DataFrame looks like this when it's ran...

╔═══════════════════╗
║ Col A      Col B  ║
╠═══════════════════╣
║ Home       6.797  ║
║ Other      3.243  ║
║ Used       12.567 ║
║ New        8.985  ║
║ Service    1.345  ║
╚═══════════════════╝

I repurposed some code I found on another Stack Overflow question pertaining to Pandas and Radar Charts and it works for the most part except I can't get the values of Col B to align properly within the chart. Below is the code I'm using...

df['Z'] = np.ones(len(df))
points = mergedFrame.pivot_table(values='Z', index=['Col A'], columns=['Col B'])
fig = plt.figure()
ax = fig.add_subplot(111, projection="polar")

theta = np.arange(len(points))/float(len(points))*2.*np.pi
l1, = ax.plot(theta, color="C2", marker="o", label="Name of Col B")

def _closeline(line):
    x, y = line.get_data()
    x = np.concatenate((x, [x[0]]))
    y = np.concatenate((y, [y[0]]))
    line.set_data(x, y)
[_closeline(l) for l in [l1]]

ax.set_xticks(radar)
ax.set_xticklabels(points.index)
plt.legend()
plt.title("Title")
plt.show()

And the chart looks like this...

Since I'm still such a newbie at Python I have no idea what I'm doing wrong here. I've tried many things to modify the code including eliminating the first two lines of code and simply putting... points = df['Col B'] instead but all it did was erase the names around the circle while leaving everything else the same. What am I doing wrong here?

Also how can I fill the area inside the theta with a light green? I tried l1, = ax.fill(theta, facecolor = 'g', alpha=0.25) below the l1, = ax.plot(theta, color="C2", marker="o", label="Name of Col B") line, but it gave me this error AttributeError: 'Polygon' object has no attribute 'get_data' and I can't seem to work it out.

Any help is much appreciated!


问:
How to zip each element from a 1D array with the elements from each row of a 2D array?
I am trying to plot a dataset using matplotlib which contains multiple y coordinates per x. To plot them I have to combine these arrays to show them in a single plot. How do I zip each element from a 1D array with the elements from each row of a 2D array (corresponding with the index for the element of the 1D array)? Without using explicit for-loops. Using built-ins (eg. zip/list comprehension) or even better: numpy?

Turning:

```<code>x = [1, 2, 3]
y = [[4, 5], [6, 7], [8, 9]]
</code>```

Into:

```<code>r = [(1, 4), (1, 5), (2, 6), (2, 7), (3, 8), (3, 9)]
</code>```

答:
This is making use of iterators only, using
itertools.chain.from_iterable

```<code>import itertools

x = [1, 2, 3]
y = [[4, 5], [6, 7], [8, 9]]

list(zip(list(itertools.chain.from_iterable(itertools.repeat(n, 2) for n in x)),
     list(itertools.chain.from_iterable(y))))
</code>```

Output

```<code>[(1, 4), (1, 5), (2, 6), (2, 7), (3, 8), (3, 9)]
</code>```

This should be faster in longer runs, IMHO.

Body:
I am trying to plot a dataset using matplotlib which contains multiple y coordinates per x. To plot them I have to combine these arrays to show them in a single plot. How do I zip each element from a 1D array with the elements from each row of a 2D array (corresponding with the index for the element of the 1D array)? Without using explicit for-loops. Using built-ins (eg. zip/list comprehension) or even better: numpy?

Turning:

x = [1, 2, 3]
y = [[4, 5], [6, 7], [8, 9]]

Into:

r = [(1, 4), (1, 5), (2, 6), (2, 7), (3, 8), (3, 9)]

Body:
This is making use of iterators only, using
itertools.chain.from_iterable

import itertools

x = [1, 2, 3]
y = [[4, 5], [6, 7], [8, 9]]

list(zip(list(itertools.chain.from_iterable(itertools.repeat(n, 2) for n in x)),
     list(itertools.chain.from_iterable(y))))

Output

[(1, 4), (1, 5), (2, 6), (2, 7), (3, 8), (3, 9)]

This should be faster in longer runs, IMHO.


问:
maxRequestPathLength not in ASP.NET 4 documentation and doesn't work
If I try to use the new maxRequestPathLength settings in an ASP.NET application it does not work.  I get an unrecognized attribute error.  I've tried using both ASP.NET Integrated and Classic application pools in IIS 7.  What is also funny is that if you search for maxRequestPathLength on MSDN it is no where to be found in the documentation except in the list of new features for ASP.NET 4.  What gives?</p>

答:
This had me foxed for a little while. The way to do this in .NET 4 is like this:

```<code><httpRuntime maxUrlLength="1024" relaxedUrlToFileSystemMapping="true"/>
</code>```

in the <system.web> section of the web.config. I did this and it worked.

ContentLicense: CC BY-SA 2.5

Body:
This had me foxed for a little while. The way to do this in .NET 4 is like this:

<httpRuntime maxUrlLength="1024" relaxedUrlToFileSystemMapping="true"/>

in the <system.web> section of the web.config. I did this and it worked.

ContentLicense: CC BY-SA 3.0


问:
Calculate all possible sum combinations in a given array of space delimited numbers using BASH
Is there a way to calculate all possible sum combinations in a given array of space delimited 'n' numbers using pure BASH?

example: 2 3 4....n

Output: 5 7 6 9 and so on

答:
This is one way you can do it but it requires Python3 :

```<code>import itertools
numbers = [2, 3, 4]
print(list(itertools.chain(*list(map(lambda x: x,
     [list(map(sum, list(itertools.combinations(numbers,x)))) for x in range(2, len(numbers) +1)]
     )))))
</code>```

Will print :

```<code>[5, 6, 7, 9]
</code>```

I don't think Bash is the right tool for this if you want it to be dynamic and fast.

Body:
This is one way you can do it but it requires Python3 :

import itertools
numbers = [2, 3, 4]
print(list(itertools.chain(*list(map(lambda x: x,
     [list(map(sum, list(itertools.combinations(numbers,x)))) for x in range(2, len(numbers) +1)]
     )))))

Will print :

[5, 6, 7, 9]

I don't think Bash is the right tool for this if you want it to be dynamic and fast.


问:
Apply filter to search in django
I want to search a user name in the database and list all the results of the search in another page.
In this page, on the listed results, I want to apply some filtering.
It sounds like a simple thing to do but I am having difficulties.
I am using django-filters.

in the home.html I have my search

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home</title>
</head>
<body>
<form action = {% url 'users:index' %} method="get">
    {% csrf_token %}

        <div class="d-flex justify-content-center">
            <div>
                <input class="form-control" type="text" name="search"
                       placeholder="Search a user...">
            </div>
            <div>
                <button class="btn btn-dark" type="submit" name="action">Search</button>
            </div>
        </div>
</form>
</body>
</html>
</code>```

The results are listed in index.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Users App</title>
</head>
<body>

<form method="GET">
    {{ filter.form }}
    <button type="submit" >Search</button>
</form>
{% if filter.qs %}
    <ul>
    {% for user in filter.qs %}
        <li><a href="{% url 'users:detail' user.id %}">{{ user.name }}, {{ user.nationality }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No users available.</p>
{% endif %}
</body>
</html>
</code>```

now if I try to apply the filter off filter.form I get the error Cannot use None as a query value.
Here are the views.py:

```<code># Create your views here.
def home(request):
    return render(request, 'users/home.html')

class UserListView(ListView):
    model = User
    template_name = 'users/index.html'
    # queryset = User.objects.filter(name__icontains='Bruno') same as
    def get_queryset(self):  # new
        query = self.request.GET.get('search')
        return User.objects.filter(name__icontains=query)
    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data(**kwargs)
        context['filter'] = UserFilter(self.request.GET, queryset=self.get_queryset())
        return context

</code>```

urls.py

```<code>app_name = 'users'
urlpatterns = [
    path('home/', views.home, name='home'),
    path('', views.UserListView.as_view(), name='index'),
    path('<int:user_id>/', views.detail, name='detail'),
]

</code>```

filters.py

```<code>import django_filters as filters
from .models import User
class UserFilter(filters.FilterSet):
    class Meta:
        model = User
        fields = ('name', 'surname',)
</code>```

the problem is that after the search as been sent with a POST method, if I try to use again the UserListView view  the command self.request.GET.get('search') returns an empty object.

How can I filter on the results of the search? Is there a way to save the search query such that the filter is applied only on the searched items?

答:
For the "Cannot use None as a query value" error you can update your get_queryset() to check for None or empty values.

```<code>def get_queryset(self):
    query = self.request.GET.get('search')
    if query:
        return User.objects.filter(name__icontains=query)
    else:
        return User.objects.none()  # or .all() depending on what you want to show
</code>```

Title: Apply filter to search in django

Body:
I want to search a user name in the database and list all the results of the search in another page.
In this page, on the listed results, I want to apply some filtering.
It sounds like a simple thing to do but I am having difficulties.
I am using django-filters.

in the home.html I have my search

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Home</title>

<form action = {% url 'users:index' %} method="get">
    {% csrf_token %}

                <input class="form-control" type="text" name="search"
                       placeholder="Search a user...">

                <button class="btn btn-dark" type="submit" name="action">Search</button>

</form>

The results are listed in index.html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Users App</title>

<form method="GET">
    {{ filter.form }}
    <button type="submit" >Search</button>
</form>
{% if filter.qs %}

    {% for user in filter.qs %}

{{ user.name }}, {{ user.nationality }}

    {% endfor %}

{% else %}

No users available.

{% endif %}

now if I try to apply the filter off filter.form I get the error Cannot use None as a query value.
Here are the views.py:

# Create your views here.
def home(request):
    return render(request, 'users/home.html')

class UserListView(ListView):
    model = User
    template_name = 'users/index.html'
    # queryset = User.objects.filter(name__icontains='Bruno') same as
    def get_queryset(self):  # new
        query = self.request.GET.get('search')
        return User.objects.filter(name__icontains=query)
    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data(**kwargs)
        context['filter'] = UserFilter(self.request.GET, queryset=self.get_queryset())
        return context

urls.py

app_name = 'users'
urlpatterns = [
    path('home/', views.home, name='home'),
    path('', views.UserListView.as_view(), name='index'),
    path('<int:user_id>/', views.detail, name='detail'),
]

filters.py

import django_filters as filters
from .models import User
class UserFilter(filters.FilterSet):
    class Meta:
        model = User
        fields = ('name', 'surname',)

the problem is that after the search as been sent with a POST method, if I try to use again the UserListView view  the command self.request.GET.get('search') returns an empty object.

How can I filter on the results of the search? Is there a way to save the search query such that the filter is applied only on the searched items?

Body:
For the "Cannot use None as a query value" error you can update your get_queryset() to check for None or empty values.

def get_queryset(self):
    query = self.request.GET.get('search')
    if query:
        return User.objects.filter(name__icontains=query)
    else:
        return User.objects.none()  # or .all() depending on what you want to show


问:
fetching data from a database in realtime, with ajax?
I am fetching data from the following database:

I have arduino-box that send that data.

And display the data with this CSS & HTML code:

```<code>    <div class="event">
        <img src="http://dummyimage.com/80x70/f00/fff.png" alt="picture" />
        <p>Room 2</p>
        <p class="patient-name">Jon Harris</p>
        <p class="event-text">This is a pixel. A flying pixel!</p>
        <p class="event-timestamp">feb 2 2011 - 23:01</p>
    </div>

.event {
    display:block;
    background: #ececec;
    width:380px;
    padding:10px;
    margin:10px;
    overflow:hidden;
    text-align: left;
}
.event img {
    display:block;
    float:left;
    margin-right:10px;
}

.event p {
    font-weight: bold;
}

.event img + p {
    display:inline;
}

.patient-name {
    display:inline;
    color: #999999;
    font-size: 9px;
    line-height:inherit;
    padding-left: 5px;
}
.event-text{
    color: #999999;
    font-size: 12px;
    padding-left: 5px;
}
.event-timestamp{
    color: #000;
    padding-left: 5px;
    font-size: 9px;
}
</code>```

Here is my PHP code:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>DASHBOARD - Arduino 3</title>
  <link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
    <?php
    $con = mysql_connect("localhost","*****","***");
        if(!con)
        {
            die('Could not connect: ' . mysql_error());
        }

        mysql_select_db("arduino_db",$con);

        $result = mysql_query("SELECT * FROM events");
        //Start container
        echo " <div id='background_container'> ";

        while($row = mysql_fetch_array($result))
        {
            echo "<div class='event'>";
            echo "<img src='img/ev_img/red.jpg' alt='picture' />";
            echo "<p>" . $row['inneboende'] . "</p>";
            echo "<p class='patient-name'>" . "$row['overvakare']" . "</p>";
            echo "<p class='event-text'>" . "$row['handelse']" . "</p>";
            echo "<p class='event-timestamp'>" . "$row['tid']" . "</p>";
            echo "</div>";
        }

        //end container
        echo "</div>"
        mysql_close($con);

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

The arduino box is sending data to the database.. lets say every 3sec. I dont want to press F5 every 5sec to get the new data. Should I use AJAX for this? I have read some AJAX on the net, but I haven´t find any good tuts for it.

答:
If you are just trying to refresh the page every 5 seconds, you should use javascript and look at setTimeout:

```<code>setTimeout("location.reload(true);",5000);
</code>```

5000 is equal to 5 seconds.

Body:
I am fetching data from the following database:

I have arduino-box that send that data.

And display the data with this CSS & HTML code:

Room 2

Jon Harris

This is a pixel. A flying pixel!

feb 2 2011 - 23:01

.event {
    display:block;
    background: #ececec;
    width:380px;
    padding:10px;
    margin:10px;
    overflow:hidden;
    text-align: left;
}
.event img {
    display:block;
    float:left;
    margin-right:10px;
}

.event p {
    font-weight: bold;
}

.event img + p {
    display:inline;
}

.patient-name {
    display:inline;
    color: #999999;
    font-size: 9px;
    line-height:inherit;
    padding-left: 5px;
}
.event-text{
    color: #999999;
    font-size: 12px;
    padding-left: 5px;
}
.event-timestamp{
    color: #000;
    padding-left: 5px;
    font-size: 9px;
}

Here is my PHP code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>DASHBOARD - Arduino 3</title>
  <link rel="stylesheet" type="text/css" href="css/style.css">

    <?php
    $con = mysql_connect("localhost","*****","***");
        if(!con)
        {
            die('Could not connect: ' . mysql_error());
        }

        mysql_select_db("arduino_db",$con);

        $result = mysql_query("SELECT * FROM events");
        //Start container
        echo "
 ";

        while($row = mysql_fetch_array($result))
        {
            echo "
";
            echo "";
            echo "
" . $row['inneboende'] . "
";
            echo "
" . "$row['overvakare']" . "
";
            echo "
" . "$row['handelse']" . "
";
            echo "
" . "$row['tid']" . "
";
            echo "
";
        }

        //end container
        echo "
"
        mysql_close($con);

    ?>

The arduino box is sending data to the database.. lets say every 3sec. I dont want to press F5 every 5sec to get the new data. Should I use AJAX for this? I have read some AJAX on the net, but I haven´t find any good tuts for it.

Body:
If you are just trying to refresh the page every 5 seconds, you should use javascript and look at setTimeout:

setTimeout("location.reload(true);",5000);

5000 is equal to 5 seconds.


问:
How to refresh a sheet's cell value in Google Apps Script
I'm experimenting with Blockspring which provides a Google Sheets add-on which can, for example, run a function which returns data from a webservice e.g.

```<code>=BLOCKSPRING("get-stock-current-stats", "ticker", "MSFT")
</code>```

I want to refresh a cell's data but don't see a 'refresh' call in the docs.

```<code>function onOpen() {
  createTimeDrivenTriggers()
}

function createTimeDrivenTriggers() {
  // Trigger every minute
  ScriptApp.newTrigger('myFunction')
      .timeBased()
      .everyMinutes(1)
      .create();

}

function myFunction() {
  Logger.log('I ran'); // can see this in the logs
  SpreadsheetApp.getActiveSheet().getRange('B4').getValue() //presumably returns a value to the script

}
</code>```

答:
Posting a useful snippet, in case you need to force all formulas to recalculate. This is considerably more performant than other examples posted here.

```<code>function forceRefreshSheetFormulas(sheetName) {
  var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = activeSpreadsheet.getSheetByName(sheetName);
  var range = sheet.getDataRange();
  var numCols = range.getNumColumns();
  var numRows = range.getNumRows();
  var rowOffset = range.getRow();
  var colOffset = range.getColumn();

  // Change formulas then change them back to refresh it
  var originalFormulas = range.getFormulas();

  //Loop through each column and each row in the sheet
  //`row` and `col` are relative to the range, not the sheet
  for (row = 0; row < numRows ; row++){
    for(col = 0; col < numCols; col++){
      if (originalFormulas[row][col] != "") {
        range.getCell(row+rowOffset, col+colOffset).setFormula("");
      }
    };
  };
  SpreadsheetApp.flush();
  for (row = 0; row < numRows ; row++){
    for(col = 0; col < numCols; col++){
      if (originalFormulas[row][col] != "") {
        range.getCell(row+rowOffset, col+colOffset).setFormula(originalFormulas[row][col]);
      }
    };
  };
  SpreadsheetApp.flush();
};
</code>```

There are a few tricks at work:
- Setting a cell's formula to "" clears it, so we avoid that.
- We need to change the formula, flush, and change it back and flush again.

Body:
I'm experimenting with Blockspring which provides a Google Sheets add-on which can, for example, run a function which returns data from a webservice e.g.

=BLOCKSPRING("get-stock-current-stats", "ticker", "MSFT")

I want to refresh a cell's data but don't see a 'refresh' call in the docs.

function onOpen() {
  createTimeDrivenTriggers()
}

function createTimeDrivenTriggers() {
  // Trigger every minute
  ScriptApp.newTrigger('myFunction')
      .timeBased()
      .everyMinutes(1)
      .create();

}

function myFunction() {
  Logger.log('I ran'); // can see this in the logs
  SpreadsheetApp.getActiveSheet().getRange('B4').getValue() //presumably returns a value to the script

}

Body:
Posting a useful snippet, in case you need to force all formulas to recalculate. This is considerably more performant than other examples posted here.

function forceRefreshSheetFormulas(sheetName) {
  var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = activeSpreadsheet.getSheetByName(sheetName);
  var range = sheet.getDataRange();
  var numCols = range.getNumColumns();
  var numRows = range.getNumRows();
  var rowOffset = range.getRow();
  var colOffset = range.getColumn();

  // Change formulas then change them back to refresh it
  var originalFormulas = range.getFormulas();

  //Loop through each column and each row in the sheet
  //`row` and `col` are relative to the range, not the sheet
  for (row = 0; row < numRows ; row++){
    for(col = 0; col < numCols; col++){
      if (originalFormulas[row][col] != "") {
        range.getCell(row+rowOffset, col+colOffset).setFormula("");
      }
    };
  };
  SpreadsheetApp.flush();
  for (row = 0; row < numRows ; row++){
    for(col = 0; col < numCols; col++){
      if (originalFormulas[row][col] != "") {
        range.getCell(row+rowOffset, col+colOffset).setFormula(originalFormulas[row][col]);
      }
    };
  };
  SpreadsheetApp.flush();
};

There are a few tricks at work:
- Setting a cell's formula to "" clears it, so we avoid that.
- We need to change the formula, flush, and change it back and flush again.


问:
STDOUT and STDERR out of order
I have a perl script which writes messages to STDOUT and STDERR (via print/croak statements), but I also redirect the STDOUT and STDERR to a logfile:

```<code>File::Tee::tee STDOUT, ">>", "$logFile" ;
File::Tee::tee STDERR, ">>", "$logFile" ;
</code>```

Now the output logfile has messages from STDOUT and STDERR displayed out of order. Also the actual output on terminal is also out of order. I have tried flushing the buffers (as recommended here: https://perl.plover.com/FAQs/Buffering.html) but it doesn't help:

```<code>select(STDERR) ;
$| = 1 ;
select(STDOUT) ;
$| = 1 ;
</code>```

Does anyone know what I must do to see the output in order (I also tried additionally flushing the filehandle corresponding to $logfile, but its still the same)?

EDIT:

Thanks to all of you who have replied. A lot of the discussion over this ended up in comments, so I am going to list the few things which I tried based on feedback from all of you.

I already was flushing the STDOUT and STDERR before I used File::Tee. As @jimtut suspected, File::Tee was indeed the culprit - removing it restored the ordering on console. But I did want to redirect the STDOUT and STDERR.

@mob suggested using IO::Tee instead, but I haven't fully understood how to make that work they way I want in my code.

@briandfoy pointed out that there isn't a reliable way to ensure 2 seperate filehandles are seen in the correct order in realtime and also suggested using a logging routine which is the only place which can write to STDOUT/STDERR. @zimd further pointed out that File::Tee uses fork which is the heart of the issue since 2 processes cannot guarantee any order on output.

Since the File::Tee is to blame, I attempted to remove this from the code. I updated my logger function to print to STDOUT/STDERR as well as to additionally print to $log filehandle. Further for capturing the warns in the log, I did the following:

```<code>sub warning_handler {
  my $msg = $_[0] ;
  print STDERR $msg ;
  print $log $msg if defined $log ;
}
$SIG{__WARN__} = \&warning_handler ;
</code>```

This worked great for all of the code under my control. Everything was printing in order now both on console and logfile. However I realized I can't use this solution since I was also calling someone else's perl packages for some functionality and clearly I couldn't intercept the print/croak etc which wrote to STDOUT/STDERR within the 'off the shelf' package. So right now, I don't have a good solution. However I suspect if I can find someway to intercept STDOUT/STDERR within perl, I might be able to get what I need.

EDIT2:
I added my own answer which is probably the closest I got to solving the problem by modifying mob's solution of using IO::Tee instead of File::Tee, but even this misses some messages (though it fixes ordering).

EDIT3:
Finally found the 'solution'

```<code>use IO::Tee ;
use Capture::Tiny qw(capture);
...
...
select(STDERR) ;
$| = 1 ;
select(STDOUT) ;
$| = 1 ;
open (my $log, ">", $logfilename) ;
*REALSTDOUT = *STDOUT ;
*REALSTDERR = *STDERR ;
*STDOUT = IO::Tee->new(\*REALSTDOUT, $log);
*STDERR = IO::Tee->new(\*REALSTDERR, $log);

# Regular Perl code here which sends output to STDOUT/STDERR
...
...
# system calls / calls to .so needs to be catpured
&log_streams(sub { &some_func_which_calls_shared_object() ; }) ;

sub log_streams {
    my ($cr, @args) = @_;  # code reference, with its arguments
    my ($out, $err, $exit) = capture { $cr->(@args) };

    if ($out) {
        print STDOUT $out;
    }
    if ($err) {
        print STDERR $err;
    }
}
</code>```

The use of IO::Tee ensures all perl generated outputs to console also go to logfile, and this happens immediately thereby updating the log and console in realtime. Since IO::Tee is changing the meaning of STDOUT/STDERR filehandles to now refer to the teed handles, it can only intercept stdio from perl statements, it misses sys calls since they bypass perl's STDOUT/STDERR handles. So we capture the syscall output and then use the log_streams routine to forward it to the now aliased STDOUT/STDERR streams. This creates a delay in the system call generated output showing up in log/terminal but there is no delay for perl generated output - i.e. best of both worlds. Do note that the ordering of stderr and stdout generated by an invocation of subroutine some_func_which_calls_shared_object is not preserved since in the log_streams routine, we first print to STDOUT and then to STDERR - as long as the system call is atomic and doesn't do much in terms of interleaving stdout/stderr messages we should be ok.
Appreciate solutions from briandfoy, mob and zimd whose answers I combined to arrive at this solution! Never thought it would require to go through this detail for what seems a very simple problem.

答:
You will have two filehandles writing to $logfile. Unless File::Tee takes care to seek to the end of the filehandle before every write (which it doesn't appear to), you will get a race condition where one filehandle will overwrite the other.

A workaround would be to use the reopen option to the File::Tee::tee function -- that will close the file after each write and reopen it (at the proper end of the file) before the next write. That could hurt your performance though, depending on how often you write to those filehandles.

You might also have better luck with IO::Tee, which is a more straightforward implementation (using tied filehandles) than what File::Tee uses (a background process for each File::Tee::tee call), so you may get fewer surprises. Here is how an IO::Tee solution might look:

```<code>use IO::Tee;
$| = 1;
open my $stdout, ">&=1";  # to write to original stdout
open my $stderr, ">&=2";  # to write to original stderr
open my $fh_log, ">>", $logfile;
*STDOUT = IO::Tee->new($stdout, $fh_log);
*STDERR = IO::Tee->new($stderr, $fh_log);
...
</code>```

There are no background process, extra threads, or anything else to cause a race condition. Both STDOUT and STDERR will both write to the same log filehandle from the same process.

Title: STDOUT and STDERR out of order

Body:
I have a perl script which writes messages to STDOUT and STDERR (via print/croak statements), but I also redirect the STDOUT and STDERR to a logfile:

File::Tee::tee STDOUT, ">>", "$logFile" ;
File::Tee::tee STDERR, ">>", "$logFile" ;

Now the output logfile has messages from STDOUT and STDERR displayed out of order. Also the actual output on terminal is also out of order. I have tried flushing the buffers (as recommended here: https://perl.plover.com/FAQs/Buffering.html) but it doesn't help:

select(STDERR) ;
$| = 1 ;
select(STDOUT) ;
$| = 1 ;

Does anyone know what I must do to see the output in order (I also tried additionally flushing the filehandle corresponding to $logfile, but its still the same)?

EDIT:

Thanks to all of you who have replied. A lot of the discussion over this ended up in comments, so I am going to list the few things which I tried based on feedback from all of you.

I already was flushing the STDOUT and STDERR before I used File::Tee. As @jimtut suspected, File::Tee was indeed the culprit - removing it restored the ordering on console. But I did want to redirect the STDOUT and STDERR.

@mob suggested using IO::Tee instead, but I haven't fully understood how to make that work they way I want in my code.

@briandfoy pointed out that there isn't a reliable way to ensure 2 seperate filehandles are seen in the correct order in realtime and also suggested using a logging routine which is the only place which can write to STDOUT/STDERR. @zimd further pointed out that File::Tee uses fork which is the heart of the issue since 2 processes cannot guarantee any order on output.

Since the File::Tee is to blame, I attempted to remove this from the code. I updated my logger function to print to STDOUT/STDERR as well as to additionally print to $log filehandle. Further for capturing the warns in the log, I did the following:

sub warning_handler {
  my $msg = $_[0] ;
  print STDERR $msg ;
  print $log $msg if defined $log ;
}
$SIG{__WARN__} = \&warning_handler ;

This worked great for all of the code under my control. Everything was printing in order now both on console and logfile. However I realized I can't use this solution since I was also calling someone else's perl packages for some functionality and clearly I couldn't intercept the print/croak etc which wrote to STDOUT/STDERR within the 'off the shelf' package. So right now, I don't have a good solution. However I suspect if I can find someway to intercept STDOUT/STDERR within perl, I might be able to get what I need.

EDIT2:
I added my own answer which is probably the closest I got to solving the problem by modifying mob's solution of using IO::Tee instead of File::Tee, but even this misses some messages (though it fixes ordering).

EDIT3:
Finally found the 'solution'

use IO::Tee ;
use Capture::Tiny qw(capture);
...
...
select(STDERR) ;
$| = 1 ;
select(STDOUT) ;
$| = 1 ;
open (my $log, ">", $logfilename) ;
*REALSTDOUT = *STDOUT ;
*REALSTDERR = *STDERR ;
*STDOUT = IO::Tee->new(\*REALSTDOUT, $log);
*STDERR = IO::Tee->new(\*REALSTDERR, $log);

# Regular Perl code here which sends output to STDOUT/STDERR
...
...
# system calls / calls to .so needs to be catpured
&log_streams(sub { &some_func_which_calls_shared_object() ; }) ;

sub log_streams {
    my ($cr, @args) = @_;  # code reference, with its arguments
    my ($out, $err, $exit) = capture { $cr->(@args) };

    if ($out) {
        print STDOUT $out;
    }
    if ($err) {
        print STDERR $err;
    }
}

The use of IO::Tee ensures all perl generated outputs to console also go to logfile, and this happens immediately thereby updating the log and console in realtime. Since IO::Tee is changing the meaning of STDOUT/STDERR filehandles to now refer to the teed handles, it can only intercept stdio from perl statements, it misses sys calls since they bypass perl's STDOUT/STDERR handles. So we capture the syscall output and then use the log_streams routine to forward it to the now aliased STDOUT/STDERR streams. This creates a delay in the system call generated output showing up in log/terminal but there is no delay for perl generated output - i.e. best of both worlds. Do note that the ordering of stderr and stdout generated by an invocation of subroutine some_func_which_calls_shared_object is not preserved since in the log_streams routine, we first print to STDOUT and then to STDERR - as long as the system call is atomic and doesn't do much in terms of interleaving stdout/stderr messages we should be ok.
Appreciate solutions from briandfoy, mob and zimd whose answers I combined to arrive at this solution! Never thought it would require to go through this detail for what seems a very simple problem.

Body:
You will have two filehandles writing to $logfile. Unless File::Tee takes care to seek to the end of the filehandle before every write (which it doesn't appear to), you will get a race condition where one filehandle will overwrite the other.

A workaround would be to use the reopen option to the File::Tee::tee function -- that will close the file after each write and reopen it (at the proper end of the file) before the next write. That could hurt your performance though, depending on how often you write to those filehandles.

You might also have better luck with IO::Tee, which is a more straightforward implementation (using tied filehandles) than what File::Tee uses (a background process for each File::Tee::tee call), so you may get fewer surprises. Here is how an IO::Tee solution might look:

use IO::Tee;
$| = 1;
open my $stdout, ">&=1";  # to write to original stdout
open my $stderr, ">&=2";  # to write to original stderr
open my $fh_log, ">>", $logfile;
*STDOUT = IO::Tee->new($stdout, $fh_log);
*STDERR = IO::Tee->new($stderr, $fh_log);
...

There are no background process, extra threads, or anything else to cause a race condition. Both STDOUT and STDERR will both write to the same log filehandle from the same process.


问:
Email template - table background image not displaying in MS Office Outlook 365
For the purpose of an email template, I need to implement a background image in the
 and its contain texts over image. Now I have tried:

https://stackoverflow.com/a/15620571/6191987

```<code><!--[if gte mso 9]>
<v:background xmlns:v="urn:schemas-microsoft-com:vml" fill="t">
<v:fill type="tile" src="http://i.imgur.com/n8Q6f.png" color="#f6f6f6"/>
</v:background>
<![endif]-->
</code>```

Its not working latest versions of MS Outlook (Version 16005.11029.20108.0 & Version 1908 Build 11929.20562),

But working fine with older versions.

Any new method to solve this problem?

答:
Have you tried declaring VML have this in your html tag?

```<code><html lang="en" xmlns="http://www.w3.org/1999/xhtml"
        xmlns:v="urn:schemas-microsoft-com:vml"
        xmlns:o="urn:schemas-microsoft-com:office:office">
</code>```

Also what are the dimensions of your bg img?  Outlook has a max img height of 1728px and won't show the image if it is over that.
And it will not show correctly if the bg img is retina.

Body:
For the purpose of an email template, I need to implement a background image in the
 and its contain texts over image. Now I have tried:

https://stackoverflow.com/a/15620571/6191987

Its not working latest versions of MS Outlook (Version 16005.11029.20108.0 & Version 1908 Build 11929.20562),

But working fine with older versions.

Any new method to solve this problem?

Body:
Have you tried declaring VML have this in your html tag?

<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
        xmlns:v="urn:schemas-microsoft-com:vml"
        xmlns:o="urn:schemas-microsoft-com:office:office">

Also what are the dimensions of your bg img?  Outlook has a max img height of 1728px and won't show the image if it is over that.
And it will not show correctly if the bg img is retina.


问:
Using double value as a score for GKLeaderboard?
I wondered if there's a way of using a double value on GKLeaderboard? It insists that I use int64_t, but I need double values to be used, as the leaderboard is for the fastest time, counting to six decimal points.

答:
If you're measuring with microsecond precision, you can just have the units be microseconds instead of seconds. Then you can use integers.

(Similarly, money should never be represented as a floating-point value, but as an integral value representing the smallest amount of money you want to consider — so a dollar would be 100 (cents) rather than 1.0 (dollars).)


问:
ionic 4 ng-true-value equivalence
I'm rewriting an ionic 1 app to ionic 4.5.0, and i have a calculator like this in ionic 1:

HTML:

```<code>    <ion-toggle toggle-class="toggle-positive" id="myid" ng-model="data.product1" ng-false-value="0" ng-true-value="50">{{data.product1}}
      <i class="icon ion-social-euro"></i>
    </ion-toggle>
</code>```

ControllerJs:

```<code>$scope.data = {
    'product1' : 0,
    'product2' : 0,
    'product3' : 0
}
</code>```

On ionic 1 we had directives like:

ng-false-value="0" ng-true-value="50"

so, when toggle were on, the true value were 50, and false 0.

On my new app, i'm trying to do the same:

HTML:

```<code>   <ion-item>
      <ion-label>Product 1 {{data.product1}}</ion-label>
      <ion-toggle name="product1" [(ngModel)]="data.product1"></ion-toggle>
    </ion-item>
</code>```

ts

```<code>data: any = {
    product1: 0,
    product2: 0,
    product3: 0
};
</code>```

{{data.product1}} is showing 0, but when i activate the toggle it's showing true or false

I have found this solution, but it's for angular: https://juristr.com/blog/2018/02/ng-true-value-directive/

Is there any equivalent or something else for ng-true-value and ng-false-value in ionic 4?

答:
The correct approach is:

HTML:

```<code> <ion-item>
          <ion-label>Product1 {{data.product1}}</ion-label>
          <ion-toggle name="product1" [(ngModel)]="data.product1" (ionChange)="calculateProduct1()"></ion-toggle>
 </ion-item>
</code>```

.ts

```<code>data: any = {
  product1: 0,
  product2: 0
}

calculateProduct1() {
  if (this.data.product1) {   // toggle is true
    this.data.product1 = 50;
  } else {                         // toggle is false
    this.data.product1 = 0;
  }
}
</code>```

Thanks to https://stackoverflow.com/users/1934484/tomas-vancoillie

Title: ionic 4 ng-true-value equivalence

Body:
I'm rewriting an ionic 1 app to ionic 4.5.0, and i have a calculator like this in ionic 1:

HTML:

    <ion-toggle toggle-class="toggle-positive" id="myid" ng-model="data.product1" ng-false-value="0" ng-true-value="50">{{data.product1}}

    </ion-toggle>

ControllerJs:

$scope.data = {
    'product1' : 0,
    'product2' : 0,
    'product3' : 0
}

On ionic 1 we had directives like:

ng-false-value="0" ng-true-value="50"

so, when toggle were on, the true value were 50, and false 0.

On my new app, i'm trying to do the same:

HTML:

   <ion-item>
      <ion-label>Product 1 {{data.product1}}</ion-label>
      <ion-toggle name="product1" [(ngModel)]="data.product1"></ion-toggle>
    </ion-item>

ts

data: any = {
    product1: 0,
    product2: 0,
    product3: 0
};

{{data.product1}} is showing 0, but when i activate the toggle it's showing true or false

I have found this solution, but it's for angular: https://juristr.com/blog/2018/02/ng-true-value-directive/

Is there any equivalent or something else for ng-true-value and ng-false-value in ionic 4?

Body:
The correct approach is:

HTML:

 <ion-item>
          <ion-label>Product1 {{data.product1}}</ion-label>
          <ion-toggle name="product1" [(ngModel)]="data.product1" (ionChange)="calculateProduct1()"></ion-toggle>
 </ion-item>

.ts

data: any = {
  product1: 0,
  product2: 0
}

calculateProduct1() {
  if (this.data.product1) {   // toggle is true
    this.data.product1 = 50;
  } else {                         // toggle is false
    this.data.product1 = 0;
  }
}

Thanks to https://stackoverflow.com/users/1934484/tomas-vancoillie


答:
You could treat them as an array of tuples as a quicky:

```<code>let imageTitles: [(imageName: String, imageTitle: String)] = [
    ("IMG_1085.JPG", "Num Num Num"),
    ("IMG_1251.JPG", "Star of the Show"),
    ("IMG_1643.JPG", "Ante Up"),
    ("IMG_1630.jpg", "Someone called my name?"),
    ("IMG_1340.JPG", "Ahhhhhhhhh"),
    ("IMG_1595.jpg", "Focus"),
    ("IMG_1689.JPG", "He Likes Me"),
    ("IMG_1676.jpg", "Warm and Cozy"),
    ("IMG_1688.JPG", "It's Like Looking Into a Mirror..."),
]

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Picture", for: indexPath)
    cell.textLabel?.text = imageTitles[indexPath.row].imageTitle
    return cell
}
</code>```

In future to better manage them, if you can change it, just change it as an array of a specific type something like:

```<code>struct Image {
    var imageName: String
    var imageTitle: String
}

let imageTitles: [Image] = [
    Image(imageName: "IMG_1085.JPG", imageTitle: "Num Num Num"),
    ...
]

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Picture", for: indexPath)
    cell.textLabel?.text = imageTitles[indexPath.row].imageTitle
    return cell
}
</code>```

Title: How do I use key value pairs from a dictionary to feed table view cells their title?

Body:
I'm currently trying to complete the finishing touches on my first app. Written in swift via Xcode as part of a course I'm taking, I've got a list of images that appear in a table view, and I want to programmatically alter the names of the files so it doesn't display IMG_xxxxx.jpg. I created a dictionary to associate each photo with the desired name, but I cannot figure out how to make the table view display a cell title that is the value of a key in said dictionary based on which file gets loaded in any given cell.

//This is the dictionary
let imageTitles = ["IMG_1085.JPG" : "Num Num Num",
                   "IMG_1251.JPG" : "Star of the Show",
                   "IMG_1643.JPG" : "Ante Up",
                   "IMG_1630.jpg" : "Someone called my name?",
                   "IMG_1340.JPG" : "Ahhhhhhhhh",
                   "IMG_1595.jpg" : "Focus",
                   "IMG_1689.JPG" : "He Likes Me",
                   "IMG_1676.jpg" : "Warm and Cozy",
                   "IMG_1688.JPG" : "It's Like Looking Into a Mirror...",
                   ]

These are the bits that load the name of a cell. One is commented out (that's the 'official' code taught by the instructor, I'm trying to take it one step further for learning's sake) and the other is my own attempts at completing this task (I've not saved each and every try- I just rewrite with something new when unsuccessful.) The other comment was more a note to self when I decided to add this feature. I suppose it is possible I'm trying to do this in the wrong spot, but I don't think that is the case. The error thrown is saying that I can't have a string:string reference when int is expected, and that makes sense (logically, I would assume .row would be an int value, but I don't know how to make a statement that asks for a string:string value, which I believe would solve my problem).

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Picture", for: indexPath)
    //cell.textLabel?.text = pictures[indexPath.row]
    cell.textLabel?.text = imageTitles[indexPath.row]
    //this is where I need to make the reference of the dictonary

    return cell
}

Lastly, if I'm right about just not knowing how to write a parameter that needs string:string, is there any way to have figured that out burdened with inexperience? I tried looking for existing threads on sites like this but without any luck.

Thanks in advance for any assistance!

Body:
You could treat them as an array of tuples as a quicky:

let imageTitles: [(imageName: String, imageTitle: String)] = [
    ("IMG_1085.JPG", "Num Num Num"),
    ("IMG_1251.JPG", "Star of the Show"),
    ("IMG_1643.JPG", "Ante Up"),
    ("IMG_1630.jpg", "Someone called my name?"),
    ("IMG_1340.JPG", "Ahhhhhhhhh"),
    ("IMG_1595.jpg", "Focus"),
    ("IMG_1689.JPG", "He Likes Me"),
    ("IMG_1676.jpg", "Warm and Cozy"),
    ("IMG_1688.JPG", "It's Like Looking Into a Mirror..."),
]

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Picture", for: indexPath)
    cell.textLabel?.text = imageTitles[indexPath.row].imageTitle
    return cell
}

In future to better manage them, if you can change it, just change it as an array of a specific type something like:

struct Image {
    var imageName: String
    var imageTitle: String
}

let imageTitles: [Image] = [
    Image(imageName: "IMG_1085.JPG", imageTitle: "Num Num Num"),
    ...
]

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Picture", for: indexPath)
    cell.textLabel?.text = imageTitles[indexPath.row].imageTitle
    return cell
}


问:
React-Native TextInput one step behind in Child Component
TextInput in Child Component on logging is one step behind in my Input

Parent Component:

import React from 'react';
import {
  View,
  Text,
} from 'react-native';
import NumberInput from '../../Components/NumberInput'; //child component

class Login extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      number: '',
    };
  }

  onChange = value => {
    this.setState({number: value});
    console.log(this.state.number);
  };

  render() {
    return (
      <View>
        <Text>Login</Text>
        <NumberInput onChange={this.onChange} />
      </View>
    );
  }
}```
</div>
</div>
</p>

<blockquote>
  <p>Child Component</p>
</blockquote>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React from 'react';
import {View, Text, TextInput} from 'react-native';
import {withNavigation} from 'react-navigation';

const NumberInput = ({onChange}) => {
  return (
    <View>
      <Text>Enter mobile number to continue</Text>
      <TextInput
        style={styles.input}
        keyboardType={'phone-pad'}
        placeholder="999-999-9999"
        underlineColorAndroid="transparent"
        autoCompleteType="tel"
        maxLength={10}
        onChangeText={value => onChange(value)}
      />
    </View>
  );
};

export default withNavigation(NumberInput);</code>```

答:
Pass your console.warn() as a callback to this.setState()

```<code>this.setState({
    number: value
},() => {
    console.warn(this.state.number);
});
</code>```

Body:
TextInput in Child Component on logging is one step behind in my Input

Parent Component:

import React from 'react';
import {
  View,
  Text,
} from 'react-native';
import NumberInput from '../../Components/NumberInput'; //child component

class Login extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      number: '',
    };
  }

  onChange = value => {
    this.setState({number: value});
    console.log(this.state.number);
  };

  render() {
    return (
      <View>
        <Text>Login</Text>
        <NumberInput onChange={this.onChange} />
      </View>
    );
  }
}

Child Component

import React from 'react';
import {View, Text, TextInput} from 'react-native';
import {withNavigation} from 'react-navigation';

const NumberInput = ({onChange}) => {
  return (
    <View>
      <Text>Enter mobile number to continue</Text>
      <TextInput
        style={styles.input}
        keyboardType={'phone-pad'}
        placeholder="999-999-9999"
        underlineColorAndroid="transparent"
        autoCompleteType="tel"
        maxLength={10}
        onChangeText={value => onChange(value)}
      />
    </View>
  );
};

export default withNavigation(NumberInput);

Body:
Pass your console.warn() as a callback to this.setState()

this.setState({
    number: value
},() => {
    console.warn(this.state.number);
});


问:
Cookie not registered at http (in php)
The cookie is stored in https but not registered in http

```<code>header('Cache-Control: no-store');
var_dump($_COOKIE);
function ishttp(){
    $t=$_SERVER['REQUEST_SCHEME'];
    echo $t;
    if ($t=='http'){return 'http';}
    else {return 'https';}
}
if (ishttp()=='http'){
    setcookie('val','http',time()+90000);
}
else{
    setcookie('val','https',time()+90000);
}
</code>```

I tested on two hosts
There was no problem with a host

image Https output
image Http output

答:
You should try it once with domain parameter  with "/" for same domain:</p>

```<code> header('Cache-Control: no-store');
    var_dump($_COOKIE);
    function ishttp(){
        $t=$_SERVER['REQUEST_SCHEME'];
        echo $t;
        if ($t=='http'){return 'http';}
        else {return 'https';}
    }
    if (ishttp()=='http'){
        setcookie('val','http',time()+90000,"/");
    }
    else{
        setcookie('val','https',time()+90000,"/");
    }
</code>```

Title: Cookie not registered at http (in php)

Body:
The cookie is stored in https but not registered in http

header('Cache-Control: no-store');
var_dump($_COOKIE);
function ishttp(){
    $t=$_SERVER['REQUEST_SCHEME'];
    echo $t;
    if ($t=='http'){return 'http';}
    else {return 'https';}
}
if (ishttp()=='http'){
    setcookie('val','http',time()+90000);
}
else{
    setcookie('val','https',time()+90000);
}

I tested on two hosts
There was no problem with a host

image Https output
image Http output

Body:
You should try it once with domain parameter  with "/" for same domain:

 header('Cache-Control: no-store');
    var_dump($_COOKIE);
    function ishttp(){
        $t=$_SERVER['REQUEST_SCHEME'];
        echo $t;
        if ($t=='http'){return 'http';}
        else {return 'https';}
    }
    if (ishttp()=='http'){
        setcookie('val','http',time()+90000,"/");
    }
    else{
        setcookie('val','https',time()+90000,"/");
    }


问:
Remove all constraints affecting a UIView
I have a UIView which is placed on the screen via several constraints. Some of the constraints are owned by the superview, others are owned by other ancestors (e.g. perhaps the view property of a UIViewController).

I want to remove all of these old constraints, and place it somewhere new using new constraints.

How can I do this without creating an IBOutlet for every single constraint and having to remember which view owns said constraint?

To elaborate, the naive approach would be to create a bunch of IBOutlets for each of the constraints, and would then involve calling code such as:

```<code>[viewA removeConstraint:self.myViewsLeftConstraint];
[viewB removeConstraint:self.myViewsTopConstraint];
[viewB removeConstraint:self.myViewsBottomConstraint];
[self.view removeConstraint:self.myViewsRightConstraint];
</code>```

The problem with this code is that even in the simplest case, I would need to create 2 IBOutlets. For complex layouts, this could easily reach 4 or 8 required IBOutlets. Furthermore, I would need to ensure that my call to remove the constraint is being called on the proper view. For example, imagine that myViewsLeftConstraint is owned by viewA. If I were to accidentally call [self.view removeConstraint:self.myViewsLeftConstraint], nothing would happen.

Note: The method constraintsAffectingLayoutForAxis looks promising, but is intended for debugging purposes only.

Update: Many of the answers I am receiving deal with self.constraints, self.superview.constraints, or some variant of those. These solutions won't work since those methods return only the constraints owned by the view, not the ones affecting the view.

To clarify the problem with these solutions, consider this view hierarchy:

Grandfather

Father

Me

Son

Daughter

Brother

Uncle

Now imagine we create the following constraints, and always attach them to their nearest common ancestor:

C0: Me: same top as Son (owned by Me)

C1: Me: width = 100 (owned by Me)

C2: Me: same height as Brother (owned by Father)

C3: Me: same top as Uncle (owned by Grandfather)

C4: Me: same left as Grandfather (owned by Grandfather)

C5: Brother: same left as Father (owned by Father)

C6: Uncle: same left as Grandfather (owned by Grandfather)

C7: Son: same left as Daughter (owned by Me)

Now imagine we want to remove all constraints affecting Me. Any proper solution should remove [C0,C1,C2,C3,C4] and nothing else.

If I use self.constraints (where self is Me), I will get [C0,C1,C7], since those are the only constraints owned by Me. Obviously it wouldn't be enough to remove this since it is missing [C2,C3,C4]. Furthermore, it is removing C7 unnecessarily.

If I use self.superview.constraints (where self is Me), I will get [C2,C5], since those are the constraints owned by Father. Obviously we cannot remove all these since C5 is completely unrelated to Me.

If I use grandfather.constraints, I will get [C3,C4,C6]. Again, we cannot remove all of these since C6 should remain intact.

The brute force approach is to loop over each of the view's ancestors (including itself), and seeing if firstItem or secondItem are the view itself; if so, remove that constraint. This will lead to a correct solution, returning [C0,C1,C2,C3,C4], and only those constraints.

However, I'm hoping there is a more elegant solution than having to loop through the entire list of ancestors.

答:
Using a Reusable Sequence

I decided to approach this in a more 'reusable' way.  Since finding all constraints affecting a view is the basis for all of the above, I decided to implement a custom sequence that returns them all for me, along with the owning views.

First thing to do is define an extension on Arrays of NSLayoutConstraint that returns all elements affecting a specific view.

```<code>public extension Array where Element == NSLayoutConstraint {

    func affectingView(_ targetView:UIView) -> [NSLayoutConstraint] {

        return self.filter{

            if let firstView = $0.firstItem as? UIView,
                firstView == targetView {
                return true
            }

            if let secondView = $0.secondItem as? UIView,
                secondView == targetView {
                return true
            }

            return false
        }
    }
}
</code>```

We then use that extension in a custom sequence that returns all constraints affecting that view, along with the views that actually own them (which can be anywhere up the view hierarchy)

```<code>public struct AllConstraintsSequence : Sequence {

    public init(view:UIView){
        self.view = view
    }

    public let view:UIView

    public func makeIterator() -> Iterator {
        return Iterator(view:view)
    }

    public struct Iterator : IteratorProtocol {

        public typealias Element = (constraint:NSLayoutConstraint, owningView:UIView)

        init(view:UIView){
            targetView  = view
            currentView = view
            currentViewConstraintsAffectingTargetView = currentView.constraints.affectingView(targetView)
        }

        private let targetView  : UIView
        private var currentView : UIView
        private var currentViewConstraintsAffectingTargetView:[NSLayoutConstraint] = []
        private var nextConstraintIndex = 0

        mutating public func next() -> Element? {

            while(true){

                if nextConstraintIndex < currentViewConstraintsAffectingTargetView.count {
                    defer{nextConstraintIndex += 1}
                    return (currentViewConstraintsAffectingTargetView[nextConstraintIndex], currentView)
                }

                nextConstraintIndex = 0

                guard let superview = currentView.superview else { return nil }

                self.currentView = superview
                self.currentViewConstraintsAffectingTargetView = currentView.constraints.affectingView(targetView)
            }
        }
    }
}
</code>```

Finally we declare an extension on UIView to expose all the constraints affecting it in a simple property that you can access with a simple for-each syntax.

```<code>extension UIView {

    var constraintsAffectingView:AllConstraintsSequence {
        return AllConstraintsSequence(view:self)
    }
}
</code>```

Now we can iterate all constraints affecting a view and do what we want with them...

List their identifiers...

```<code>for (constraint, _) in someView.constraintsAffectingView{
    print(constraint.identifier ?? "No identifier")
}
</code>```

Deactivate them...

```<code>for (constraint, _) in someView.constraintsAffectingView{
    constraint.isActive = false
}
</code>```

Or remove them entirely...

```<code>for (constraint, owningView) in someView.constraintsAffectingView{
    owningView.removeConstraints([constraint])
}
</code>```

Enjoy!

Body:
I have a UIView which is placed on the screen via several constraints. Some of the constraints are owned by the superview, others are owned by other ancestors (e.g. perhaps the view property of a UIViewController).

I want to remove all of these old constraints, and place it somewhere new using new constraints.

How can I do this without creating an IBOutlet for every single constraint and having to remember which view owns said constraint?

To elaborate, the naive approach would be to create a bunch of IBOutlets for each of the constraints, and would then involve calling code such as:

[viewA removeConstraint:self.myViewsLeftConstraint];
[viewB removeConstraint:self.myViewsTopConstraint];
[viewB removeConstraint:self.myViewsBottomConstraint];
[self.view removeConstraint:self.myViewsRightConstraint];

The problem with this code is that even in the simplest case, I would need to create 2 IBOutlets. For complex layouts, this could easily reach 4 or 8 required IBOutlets. Furthermore, I would need to ensure that my call to remove the constraint is being called on the proper view. For example, imagine that myViewsLeftConstraint is owned by viewA. If I were to accidentally call [self.view removeConstraint:self.myViewsLeftConstraint], nothing would happen.

Note: The method constraintsAffectingLayoutForAxis looks promising, but is intended for debugging purposes only.

Update: Many of the answers I am receiving deal with self.constraints, self.superview.constraints, or some variant of those. These solutions won't work since those methods return only the constraints owned by the view, not the ones affecting the view.

To clarify the problem with these solutions, consider this view hierarchy:

Grandfather

Father

Me

Son

Daughter

Brother

Uncle

Now imagine we create the following constraints, and always attach them to their nearest common ancestor:

C0: Me: same top as Son (owned by Me)

C1: Me: width = 100 (owned by Me)

C2: Me: same height as Brother (owned by Father)

C3: Me: same top as Uncle (owned by Grandfather)

C4: Me: same left as Grandfather (owned by Grandfather)

C5: Brother: same left as Father (owned by Father)

C6: Uncle: same left as Grandfather (owned by Grandfather)

C7: Son: same left as Daughter (owned by Me)

Now imagine we want to remove all constraints affecting Me. Any proper solution should remove [C0,C1,C2,C3,C4] and nothing else.

If I use self.constraints (where self is Me), I will get [C0,C1,C7], since those are the only constraints owned by Me. Obviously it wouldn't be enough to remove this since it is missing [C2,C3,C4]. Furthermore, it is removing C7 unnecessarily.

If I use self.superview.constraints (where self is Me), I will get [C2,C5], since those are the constraints owned by Father. Obviously we cannot remove all these since C5 is completely unrelated to Me.

If I use grandfather.constraints, I will get [C3,C4,C6]. Again, we cannot remove all of these since C6 should remain intact.

The brute force approach is to loop over each of the view's ancestors (including itself), and seeing if firstItem or secondItem are the view itself; if so, remove that constraint. This will lead to a correct solution, returning [C0,C1,C2,C3,C4], and only those constraints.

However, I'm hoping there is a more elegant solution than having to loop through the entire list of ancestors.

Body:
Using a Reusable Sequence

I decided to approach this in a more 'reusable' way.  Since finding all constraints affecting a view is the basis for all of the above, I decided to implement a custom sequence that returns them all for me, along with the owning views.

First thing to do is define an extension on Arrays of NSLayoutConstraint that returns all elements affecting a specific view.

public extension Array where Element == NSLayoutConstraint {

    func affectingView(_ targetView:UIView) -> [NSLayoutConstraint] {

        return self.filter{

            if let firstView = $0.firstItem as? UIView,
                firstView == targetView {
                return true
            }

            if let secondView = $0.secondItem as? UIView,
                secondView == targetView {
                return true
            }

            return false
        }
    }
}

We then use that extension in a custom sequence that returns all constraints affecting that view, along with the views that actually own them (which can be anywhere up the view hierarchy)

public struct AllConstraintsSequence : Sequence {

    public init(view:UIView){
        self.view = view
    }

    public let view:UIView

    public func makeIterator() -> Iterator {
        return Iterator(view:view)
    }

    public struct Iterator : IteratorProtocol {

        public typealias Element = (constraint:NSLayoutConstraint, owningView:UIView)

        init(view:UIView){
            targetView  = view
            currentView = view
            currentViewConstraintsAffectingTargetView = currentView.constraints.affectingView(targetView)
        }

        private let targetView  : UIView
        private var currentView : UIView
        private var currentViewConstraintsAffectingTargetView:[NSLayoutConstraint] = []
        private var nextConstraintIndex = 0

        mutating public func next() -> Element? {

            while(true){

                if nextConstraintIndex < currentViewConstraintsAffectingTargetView.count {
                    defer{nextConstraintIndex += 1}
                    return (currentViewConstraintsAffectingTargetView[nextConstraintIndex], currentView)
                }

                nextConstraintIndex = 0

                guard let superview = currentView.superview else { return nil }

                self.currentView = superview
                self.currentViewConstraintsAffectingTargetView = currentView.constraints.affectingView(targetView)
            }
        }
    }
}

Finally we declare an extension on UIView to expose all the constraints affecting it in a simple property that you can access with a simple for-each syntax.

extension UIView {

    var constraintsAffectingView:AllConstraintsSequence {
        return AllConstraintsSequence(view:self)
    }
}

Now we can iterate all constraints affecting a view and do what we want with them...

List their identifiers...

for (constraint, _) in someView.constraintsAffectingView{
    print(constraint.identifier ?? "No identifier")
}

Deactivate them...

for (constraint, _) in someView.constraintsAffectingView{
    constraint.isActive = false
}

Or remove them entirely...

for (constraint, owningView) in someView.constraintsAffectingView{
    owningView.removeConstraints([constraint])
}

Enjoy!


问:
Practical usage of setjmp and longjmp in C
Can anyone explain me where exactly setjmp() and longjmp() functions can be used practically in embedded programming? I know that these are for error handling. But I'd like to know some use cases.

答: Hands down, the most crucial use of setjmp/longjmp is that it acts a "non-local goto jump".  Goto command (and there rare instances where you will need to use goto over for and while loops) is most-used-safely in the same scope.  If you use goto to jump across scopes (or across auto allocation), you will most-likely corrupt your program's stack.  setjmp/longjmp avoids this by saving the stack info at the location you want to jump to.  Then, when you jump, it loads this stack info. Without this feature, C programmers would most likely had to turn to assembly programming to solve issues that only setjmp/longjmp could solve.  Thank God it exists.  Everything in the C library is extremely important.  You will know when you need it.</p>


问:
Haskell strategies for speculative execution of conditionals / Alternative
I wonder which parallel strategy, spark, or whatever, can be used for speculative execution of a Haskell program that consists of a lot of conditional tests, recursively.

Assume a program that has a lot of conditional tests, recursively.  I imagine that if sparks are used, then most sparks will be working on useless branches.  The spark lifecycle does not include cancellation.

A workable strategy has to be able to efficiently create, but also cancel, units of work, in a dependency tree.

As an example, consider the problem of parsing a text.  A parser consists of a huge tree of basically:

```<code>if <looks-like-1> then
   if <looks-like 1.1> then
     if <looks-like 1.1.1> then
       success
     else failure
   else if <looks-like 1.1> ...
else if ...
</code>```

At a given conditional, we cannot know whether we will backtrack or not until much later.  By speculatively executing the other branch, we can solve this problem faster.

However, if we just use sparks, there is an exponential increase in useless work and we won't get much of a speedup.  There must be a way to cancel work that has started on a branch when we know that it will never be taken.

A generalizaiton of this would be speculative execution for any data type that implements Alternative, the idea being that cancellation of an alternative that is never observed doesn't change the semantics of a program.  So a <|> b where b is not returned from the expression, can be short-circuited, say through throwing an exception during speculative execution, without affecting the semantics.

How would you approach this in Haskell?

答:
If we can countenance abandoning the world of pure parallel computations, we can turn to the async package, which allows cancellation of asynchronous tasks.

For example, here's an speculative "if" that allows conditions that take a while to be calculated. It launches both branches concurrently, and when the result of the condition becomes known promptly kills the losing branch:

```<code>{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE NumDecimals #-}
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async
import Control.Exception (onException)

iffy :: IO Bool -> IO a -> IO a -> IO a
iffy test left right =
    withAsync left \leftAsync ->
    withAsync right \rightAsync ->
        do testResult <- test
           let (shouldWait,shouldCancel) =
                    if testResult then (leftAsync,rightAsync)
                                  else (rightAsync,leftAsync)
           cancel shouldCancel
           wait shouldWait

iffyTest :: Bool -> IO Int
iffyTest b =
    iffy do threadDelay 1e6 >> pure b
         do (threadDelay 2e6 >> pure 5) `onException` putStrLn "cancelled L"
         do (threadDelay 2e6 >> pure 2) `onException` putStrLn "cancelled R"
</code>```

Putting it to work:

```<code>λ iffyTest True
cancelled R
5
λ iffyTest False
cancelled L
2
</code>```

Body:
I wonder which parallel strategy, spark, or whatever, can be used for speculative execution of a Haskell program that consists of a lot of conditional tests, recursively.

Assume a program that has a lot of conditional tests, recursively.  I imagine that if sparks are used, then most sparks will be working on useless branches.  The spark lifecycle does not include cancellation.

A workable strategy has to be able to efficiently create, but also cancel, units of work, in a dependency tree.

As an example, consider the problem of parsing a text.  A parser consists of a huge tree of basically:

if <looks-like-1> then
   if <looks-like 1.1> then
     if <looks-like 1.1.1> then
       success
     else failure
   else if <looks-like 1.1> ...
else if ...

At a given conditional, we cannot know whether we will backtrack or not until much later.  By speculatively executing the other branch, we can solve this problem faster.

However, if we just use sparks, there is an exponential increase in useless work and we won't get much of a speedup.  There must be a way to cancel work that has started on a branch when we know that it will never be taken.

A generalizaiton of this would be speculative execution for any data type that implements Alternative, the idea being that cancellation of an alternative that is never observed doesn't change the semantics of a program.  So a <|> b where b is not returned from the expression, can be short-circuited, say through throwing an exception during speculative execution, without affecting the semantics.

How would you approach this in Haskell?

Body:
If we can countenance abandoning the world of pure parallel computations, we can turn to the async package, which allows cancellation of asynchronous tasks.

For example, here's an speculative "if" that allows conditions that take a while to be calculated. It launches both branches concurrently, and when the result of the condition becomes known promptly kills the losing branch:

{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE NumDecimals #-}
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async
import Control.Exception (onException)

iffy :: IO Bool -> IO a -> IO a -> IO a
iffy test left right =
    withAsync left \leftAsync ->
    withAsync right \rightAsync ->
        do testResult <- test
           let (shouldWait,shouldCancel) =
                    if testResult then (leftAsync,rightAsync)
                                  else (rightAsync,leftAsync)
           cancel shouldCancel
           wait shouldWait

iffyTest :: Bool -> IO Int
iffyTest b =
    iffy do threadDelay 1e6 >> pure b
         do (threadDelay 2e6 >> pure 5) `onException` putStrLn "cancelled L"
         do (threadDelay 2e6 >> pure 2) `onException` putStrLn "cancelled R"

Putting it to work:

λ iffyTest True
cancelled R
5
λ iffyTest False
cancelled L
2


问:
Split array into different size chunks (4, 3, 3, 3, 4, 3, 3, 3, etc)
I have an array like so: [1, 2, 3, 4, 5, 6, 7, 9, 10]. I need to chunk it into different size chunks, yet with a simple pattern of: 4, 3, 3, 3, 4, 3, 3, 3 like so:

```<code>[
    [ // four
        1,
        2,
        3,
        4
    ],
    [ // three (1/3)
        5,
        6,
        7
    ],
    [ // three (2/3)
        8,
        9,
        10
    ],
    [ // three (3/3)
        11,
        12,
        13
    ],
    [ // four
        14,
        15,
        16,
        17
    ],
    [ // three (1/3)
        18,
        19,
        20
    ], // and so on..
]
</code>```

I have tried with this code I have customized:

```<code>const arr; // my array of values
const chuncked = arr.reduce((acc, product, i) => {
    if (i % 3) {
        return acc;
    } else if (!didFourWayReduce) {
        didFourWayReduce = true;
        fourWayReduces++;

        if ((fourWayReduces - 1) % 2) { // only make every second a "4 row"
            return [...acc, arr.slice(i, i + 3)];
        } else {
            return [...acc, arr.slice(i, i + 4)];
        }
    } else {
        didFourWayReduce = false;
        return [...acc, arr.slice(i, i + 3)];
    }
}, []);
</code>```

And it works, almost, expect that the first chunk of threes (1/3) have the last element of the chunk with 4. So 1 key is repeated every first chunk of three. Like so:

```<code>[
    [
        1,
        2,
        3,
        4
    ],
    [
        4, // this one is repeated, and it shouldn't be
        5,
        6
    ]
]
</code>```

答:
const arr = Array.from({ length: 100 }, (_, i) => i);

const copy = [...arr];

const sizes = [4, 3, 3, 3];

const result = [];

let i = 0;

while (i <= arr.length && copy.length) {
  result.push(copy.splice(0, sizes[i % sizes.length]));
  i++;
}

console.log(result);```

Body:
I have an array like so: [1, 2, 3, 4, 5, 6, 7, 9, 10]. I need to chunk it into different size chunks, yet with a simple pattern of: 4, 3, 3, 3, 4, 3, 3, 3 like so:

[
    [ // four
        1,
        2,
        3,
        4
    ],
    [ // three (1/3)
        5,
        6,
        7
    ],
    [ // three (2/3)
        8,
        9,
        10
    ],
    [ // three (3/3)
        11,
        12,
        13
    ],
    [ // four
        14,
        15,
        16,
        17
    ],
    [ // three (1/3)
        18,
        19,
        20
    ], // and so on..
]

I have tried with this code I have customized:

const arr; // my array of values
const chuncked = arr.reduce((acc, product, i) => {
    if (i % 3) {
        return acc;
    } else if (!didFourWayReduce) {
        didFourWayReduce = true;
        fourWayReduces++;

        if ((fourWayReduces - 1) % 2) { // only make every second a "4 row"
            return [...acc, arr.slice(i, i + 3)];
        } else {
            return [...acc, arr.slice(i, i + 4)];
        }
    } else {
        didFourWayReduce = false;
        return [...acc, arr.slice(i, i + 3)];
    }
}, []);

And it works, almost, expect that the first chunk of threes (1/3) have the last element of the chunk with 4. So 1 key is repeated every first chunk of three. Like so:

[
    [
        1,
        2,
        3,
        4
    ],
    [
        4, // this one is repeated, and it shouldn't be
        5,
        6
    ]
]


问:
jQuery animate scrollTop doesn't scroll on any browser
Im making a website, when the user clicks on a sort of button of the navbar the entire webpage should scroll to the section containing the information selected by the user.  But it just simply won’t work for some reason. It used to, but something broke.

navbar code:

    Infomratica

```

<p>The section code:</p>

<pre class="lang-html prettyprint-override"><code><section id="section0" class="sezione0">
    <div class="container-fluid" style="text-align: center;">
        <div id="heading" class="row" style="margin-top: 125px;">
            <div class="col-md" style="margin-bottom: 80px;">Infomatica</div>
        </div>
        <div class="row justify-content-center">
            <div class="button" id="button-3">
                <div id="circle"></div><a>Infomatica</a>
            </div>
        </div>
    </div>
</section>
</code>```

The code that should provide the scroll capability is this:

$('a[href*="#"]').on("click", function (e) {

        e.preventDefault();

        let target = $($(this).attr("href"));
        console.log(target.length);

        if (target.length) {
          $('html, body').animate({
            scrollTop: $(target).offset().top
          }, 1000);
        }

      });
```

I've tried all the possibilities, and none of them worked.

Do you have any idea of what caused it, and how to fix it ?

EDIT:

I have imported jQuery

答:
It seems your opening anchor tag is missing the >. It should be:

```<code><a href="#section0">Informatica</a>
</code>```

Working example below:

$('a[href*="#"]').on("click", function(e) {
  e.preventDefault();
  let target = $($(this).attr("href"));
  if (target.length) {
    $('html, body').animate({
      scrollTop: $(target).offset().top
    }, 1000);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul id="outJS">
 <li>
   Informatica
 </li>
</ul>

<section id="section0" class="sezione0">
  <div class="container-fluid" style="text-align: center;">
    <div id="heading" class="row" style="margin-top: 125px;">
      <div class="col-md" style="margin-bottom: 80px;">Informatica</div>
    </div>
    <div class="row justify-content-center">
      <div class="button" id="button-3">
        <div id="circle"></div><a>Informatica</a>
      </div>
    </div>
  </div>
</section></code>```

Body:
Im making a website, when the user clicks on a sort of button of the navbar the entire webpage should scroll to the section containing the information selected by the user.  But it just simply won’t work for some reason. It used to, but something broke.

navbar code:

    Infomratica

The section code:

Infomatica

Infomatica

The code that should provide the scroll capability is this:

$('a[href*="#"]').on("click", function (e) {

        e.preventDefault();

        let target = $($(this).attr("href"));
        console.log(target.length);

        if (target.length) {
          $('html, body').animate({
            scrollTop: $(target).offset().top
          }, 1000);
        }

      });

I've tried all the possibilities, and none of them worked.

Do you have any idea of what caused it, and how to fix it ?

EDIT:

I have imported jQuery

Body:
It seems your opening anchor tag is missing the >. It should be:

<a href="#section0">Informatica</a>

Working example below:

$('a[href*="#"]').on("click", function(e) {
  e.preventDefault();
  let target = $($(this).attr("href"));
  if (target.length) {
    $('html, body').animate({
      scrollTop: $(target).offset().top
    }, 1000);
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul id="outJS">
 <li>
   <a href="#section0">Informatica</a>
 </li>
</ul>

<section id="section0" class="sezione0">
  <div class="container-fluid" style="text-align: center;">
    <div id="heading" class="row" style="margin-top: 125px;">
      <div class="col-md" style="margin-bottom: 80px;">Informatica</div>
    </div>
    <div class="row justify-content-center">
      <div class="button" id="button-3">
        <div id="circle"></div><a>Informatica</a>
      </div>
    </div>
  </div>
</section>


问:
Powershell multiple function params from ValidateSet
I'm writing a script with PowerShell and at some point I needed to use ValidateSet  on function params. It's a very good feature, but what I need is something more than that.

For example

```<code>Function JustAnExample
{
    param(
        [Parameter(Mandatory=$false)][ValidateSet("IPAddress","Timezone","Cluster")]
        [String]$Fields
    )

    write-host $Fields
}
</code>```

So this code snippet allows me to choose one item from the list like that

JustAnExample -Fields IPAddress

and then prints it to the screen.
I wonder if there is a possibility to allow to choose multiple values and pass them to function from one Validation set like so

```<code>JustAnExample -Fields IPAddress Cluster
</code>```

Maybe there is a library for that or maybe I just missed something but I really can't find a solution for this.

答:
@SokIsKedu, I had the same issue and could not find an answer. So I use the following inside the function:

```<code>function Test-Function {
    param (
        [ValidateSet('ValueA', 'ValueB')]
        [string[]] $TestParam
    )

    $duplicate = $TestParam | Group-Object | Where-Object -Property Count -gt 1
    if ($null -ne $duplicate) {
        throw "TestParam : The following values are duplicated: $($duplicate.Name -join ', ')"
    }

    ...
}
</code>```

It does not prevent duplicates being passed in, but it does catch them.

Body:
I'm writing a script with PowerShell and at some point I needed to use ValidateSet  on function params. It's a very good feature, but what I need is something more than that.

For example

Function JustAnExample
{
    param(
        [Parameter(Mandatory=$false)][ValidateSet("IPAddress","Timezone","Cluster")]
        [String]$Fields
    )

    write-host $Fields
}

So this code snippet allows me to choose one item from the list like that

JustAnExample -Fields IPAddress

and then prints it to the screen.
I wonder if there is a possibility to allow to choose multiple values and pass them to function from one Validation set like so

JustAnExample -Fields IPAddress Cluster

Maybe there is a library for that or maybe I just missed something but I really can't find a solution for this.

Body:
@SokIsKedu, I had the same issue and could not find an answer. So I use the following inside the function:

function Test-Function {
    param (
        [ValidateSet('ValueA', 'ValueB')]
        [string[]] $TestParam
    )

    $duplicate = $TestParam | Group-Object | Where-Object -Property Count -gt 1
    if ($null -ne $duplicate) {
        throw "TestParam : The following values are duplicated: $($duplicate.Name -join ', ')"
    }

    ...
}

It does not prevent duplicates being passed in, but it does catch them.


问:
Mockito - Invalid use of argument matchers
I have Junit test that is testing jms message sending. I am using Spring jmsTemplate to to do this. Here I as in the following code I want to check whether the JMS template has called send message regardless what is it in the values of actuall parameters that are passed.

my publisher method the uses the jmsTemplate to send method looks like following inside..

```<code>jmsTemplate.send(jmsQueueProperties.getProperty(key), new MessageCreator()
{
    public Message createMessage(Session session) throws JMSException
    {
        ObjectMessage obj = session.createObjectMessage(dialogueServiceResponse);
        return obj;
}
});
</code>```

in My tests..

```<code>JmsTemplate mockTemplate = Mockito.mock(JmsTemplate.class);
...
publisher.publishServiceMessage(response);
....
Mockito.verify(mockTemplate,
    Mockito.times(1)).send("appointment.queue",
        Mockito.any(MessageCreator.class));
</code>```

But when in the execution i get

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Invalid use of argument matchers!
  ....

Cause is due to Mockito.any(MessageCreator.class) , but isn't there a way to test my send method is getting executed without creating an actual object in the MessageCreator.

Update
And is there a way to check my session.createObjectMessage(dialogueServiceResponse) is getting called as well

答:
I was seeing this error about a mismatched # of arguments, despite having the correct number...

I realized this was because method being stubbed was static. When I converted it to non-static, it worked as expected.

Body:
I have Junit test that is testing jms message sending. I am using Spring jmsTemplate to to do this. Here I as in the following code I want to check whether the JMS template has called send message regardless what is it in the values of actuall parameters that are passed.

my publisher method the uses the jmsTemplate to send method looks like following inside..

jmsTemplate.send(jmsQueueProperties.getProperty(key), new MessageCreator()
{
    public Message createMessage(Session session) throws JMSException
    {
        ObjectMessage obj = session.createObjectMessage(dialogueServiceResponse);
        return obj;
}
});

in My tests..

JmsTemplate mockTemplate = Mockito.mock(JmsTemplate.class);
...
publisher.publishServiceMessage(response);
....
Mockito.verify(mockTemplate,
    Mockito.times(1)).send("appointment.queue",
        Mockito.any(MessageCreator.class));

But when in the execution i get

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Invalid use of argument matchers!
  ....

Cause is due to Mockito.any(MessageCreator.class) , but isn't there a way to test my send method is getting executed without creating an actual object in the MessageCreator.

Update
And is there a way to check my session.createObjectMessage(dialogueServiceResponse) is getting called as well