Adding sequence item to configuration

Question: I have a configuration item in my custom module, part of which is a sequence, basically I'm attempting to create something akin to an array of items
my_module.schema.yml
my_module.settings:
  type: config_object
  label: 'Configuration'
  mapping:
    custom_fields:
      label: 'Custom Fields'
      type: sequence
      sequence:
        type: mapping
        label: 'Custom Field'
        mapping:
          field_label:
            type: string
            label: 'Field Label'
          field_key:
            type: string
            label: 'Field Key'

What I want to be able to do is add a new item to this 'list' as desired, but for the most part up to now (in other areas of my module) I've just been using $config->set(key, value) which will just overwrite the current setting, is there a method to add another value to the existing setting, or do I have to load the existing configuration, add it in manually, then save over the whole lot?
Answer: turns out, yes, you can retrieve the existing set of variables and add to it, but I'm not saying for certain that this is the correct, or best way to do it
// Load the current configuration and add this to it
$custom_fields = $config->get('custom_fields');
$custom_fields[] = array(
  'field_label' => 'some label',
  'field_key' => 'some_key',
);
$config->set('custom_fields', $custom_fields);

The above works fine, if anyone encounters this and wants to see how to do it, or anyone knows a better way, please feel free to comment

Adding sequence item to configuration


Given Two Circles Intersect Each Other. Find the Area. Does This Question Have an Error?

Question:

2 circle instersect each other. One with radius 1, another with radius r. Form $120^\circ$,  outside the two cricles.

AB = $\sqrt{r^2 - r + 1}$ (matched key answer)
I find r = 0.5 (matched key answer)

So. AB = $\sqrt{\frac{3}{4}}$

However. I have been thinking hours about 3rd problems..
I think this is what the plane looks like more or less :

But. I found that with
 APB = $120^\circ$,
AB is not  $\sqrt{\frac{3}{4}}$
Is there error with the question? Or where am i wrong?
Is there more effective way to solve it?
Comment: Because the line go through circle centers?
Comment: why did you make tangents go through circle centers?
Comment: notice that in your drawing the angle formed by the tangent lines is actually $90°$. Do you see why?
Comment: Why it is 90 degrees? APQ goes through circle center too
Comment: $PB$ is a radius and thus perpendicular to the tangent $AP$, and vice versa.
Comment: Ok. I meant APQ in your drawing. Ok i get it. Also. Why do you know the center of Cr inside intersection?
Comment: 'cause $AB < AP$?
Comment: Oh. True.. thank you
Comment: Why you think it is exactly half of Cr is the intersection?
Comment: you mean why the line connecting intersection points $P$ and $Q$ passes though center of $\mathcal C_r$?
Comment: Yes. Why is that?
Comment: added some details in my answer, below the figure.
Comment: I added further details on the general case in my answer. Let me know is this clarifies.
Answer: The situation, with $r = \frac12$, is shown in the picture below. From the fact that $\overline{AB} = \frac{\sqrt 3} 2$, $\overline{PB} = \frac12$, and $\overline{AP} = 1$, we gather that $\triangle APQ$ is equilateral.
You can then determine the area of the intersection between the two circles by summing half of the area of circle $\mathcal C_r$ with a circular segment of circle $\mathcal C$ subtended by an angle of $60°$ (that is, one sixth of the circle area minus the area of the equilateral triangle). This gives
\begin{eqnarray}
\mathcal A&=& \frac{\pi}{8}+\left(\frac{\pi}{6}-\frac{\sqrt 3}{4}\right)=\\
&=& \frac{7\pi}{24} - \frac{\sqrt{3}}{4}.
\end{eqnarray}

EDIT
To better understand the situation, you can proceed as follows.
Draw circle $\mathcal C$, with center in $A$ then draw a diameter and take $B$ on it such that $\overline{AB} = \frac{\sqrt 3}{2}$. $B$ is going to be the center of $\mathcal C_r$.
Now draw the line through $B$ perpendicular to $AB$, that intersects $\mathcal C$ in $P$ and $Q$. From Pythagorean Theorem, $\overline{PB} = \frac{1}{2}$, so $\mathcal C_r$ is the circle with center in $B$ and passing through $P$ and $Q$.
EDIT 2 The general case is shown in the figure below.
By construction we have that $\angle TPS = 120°$. From the fact that radii are perpendicular to tangent lines we have $\angle APS = 90°$ and $\angle TPB = 90°$.
Therefore we have $\angle TPA = 30°$ and $\angle APB = 60°$.
Draw from $A$ the line perpendicular to $PB$, and call $H$ its intersection with $PB$. Since $\triangle APH$ is half of an equilateral triangle, $\overline{PH} = \frac12\cdot \overline{AP} = \frac12$, and, by Pythagorean Theorem, $\overline{AH} = \frac{\sqrt 3}{2}$. $\overline{PB} = r$ by definition. Thus $\overline{HB} =r-\frac12$.
Again Pythagorean Theorem, on $\triangle AHB$, gives, in conclusion
\begin{eqnarray}
\overline{AB}^2 &=& \frac34 + \left(r-\frac12\right)^2=\tag{1}\label{eq1}\\
&=& r^2-r+1.
\end{eqnarray}
From \eqref{eq1},
$$\overline{AB}^2 \geq \frac34,$$
with the minimum attained when $r=\frac12$ and thus $H\equiv B$, as in the figure above.
Comment: Ok. True. Thank you
Comment: △APH is half equilateral from △APB?
Comment: @Lifeforbetter no need for trigonometry in this case: take any equilateral triangle and draw an altitude. What you get are to right-angled triangles similar to $APH$.
Comment: APB. Is that matched phytagoras? 1, 0.25, $\sqrt3$/2
Comment: @Lifeforbetter correct
Comment: No. It doesn't...?
Comment: @Lifeforbetter the smaller side is $1/2$
Comment: How to find AB with your drawing? It is not matched key answer..?
Comment: @Lifeforbetter $AB$ is $\sqrt 3/2$ **by construction**.
Comment: Sorry. What i meant is answer question 1 based on your drawing. Find AB in terms of r
Comment: @Lifeforbetter, well, of course you **cannot** use the drawing to demonstrate point 1., since the drawing is based on the specific case found in point 2.

I thought you did not need a demonstration of 1. and 2. since you already found the correct answers yourself. Was I wrong?
Comment: Yes. I found the answer for 1 and 2 based on my drawing... but i cannot find it with yours. From my drawing. $AB^2 = AP^2 + BP^2 - 2AP. BP.Cos120$
Comment: @Lifeforbetter you cannot because my drawing has $r$ fixed and equal to $\frac12$. Your drawing shows a different instance of the situation, where $r \neq \frac{1}{2}$ and thus $\overline{AB} \neq \frac{\sqrt 3}{2}$, but that is fine if you just need to find the *relationship* between $\overline{AB}$ and $r$.
Comment: Oh. Right.. ok. Thank you
Comment: @Lifeforbetter, well, to be precise, your drawing **does not** show a correct instance, since, as we said, the angle between tangents, there, isn't $120°$.
Comment: Oh.. right.. i will try
Comment: Yes. Thank you for the help
Comment: @Lifeforbetter $APB$ is equilateral only in the special case of the first figure, though.
Comment: You said in 2nd figure :
Draw from $A$ the line perpendicular to $PB$, and call $H$ its intersection with $PB$. Since $\triangle APH$ is half of an equilateral triangle,  But. I don't think $\triangle APH$ is half of an equilateral triangle, in 2nd figure.
Comment: @Lifeforbetter yes it is, it's a right-angled triangle with 90-60-30 degrees angles. That's what I meant.
Comment: So, you get $\overline{PH} = 1/2 \overline{AP}$ because of $\sin 30^{\circ}$?
Comment: How to know PH = 1/2 AP?
Comment: @Lifeforbetter read again my comment above and consider that in an equilateral triangle, altitudes and medians coincide!
Comment: APH is right triangle, but APB not a equlateral....?
Comment: @Lifeforbetter no, it's not. I'm talking about properties of of **any** 90-60-30 right-angle triangles... No need to consider $\triangle APB$, at this aim...
Comment: So, it is always another side is half hypotenuse side? In right angle triangles..
Comment: @Lifeforbetter if the angles are 90-60-30, of course yes.
Comment: Ok, thank you...
Comment: BTW, what program you use to draw this plane?
Comment: @Lifeforbetter Geogebra


Is it possible to cache POST methods in HTTP?

Question: With very simple caching semantics: if the parameters are the same (and the URL is the same, of course), then it's a hit. Is that possible? Recommended?
Answer: The corresponding RFC 2616 in section 9.5 (POST) allows the caching of the response to a POST message, if you use the appropriate headers.

Responses to this method are not cacheable, unless the response
includes appropriate Cache-Control or Expires header fields. However,
the 303 (See Other) response can be used to direct the user agent to
retrieve a cacheable resource.

Note that the same RFC states explicitly in section 13 (Caching in HTTP) that a cache must invalidate the corresponding entity after a POST request.

Some HTTP methods MUST cause a
cache to invalidate an entity. This is
either the entity referred to by the
Request-URI, or by the Location    or
Content-Location headers (if present).
These methods are:
  - PUT
  - DELETE
  - POST

It's not clear to me how these specifications can allow meaningful caching.
This is also reflected and further clarified in RFC 7231 (Section 4.3.3.), which obsoletes RFC 2616.

Responses to POST requests are only cacheable when they include
explicit freshness information (see Section 4.2.1 of [RFC7234]).
However, POST caching is not widely implemented.
For cases where an origin server wishes the client to be able to
cache the result of a POST in a way that can be reused by a later
GET, the origin server MAY send a 200 (OK) response containing the
result and a Content-Location header field that has the same value
as the POST's effective request URI (Section 126.96.36.199).

According to this, the result of a cached POST (if this ability is indicated by the server) can be subsequently used for as the result of a GET request for the same URI.
Comment: This is being clarified by HTTPbis; see http://www.mnot.net/blog/2012/09/24/caching_POST for a summary.
Comment: The origin server is a broker between HTTP and the application that handles the POST requests.  The application is beyond the HTTP boundary and it can do whatever it pleases.  If caching makes sense for a specific POST request it's free to cache, as much as the OS can cache disk requests.
Comment: Diomidis, your statement that caching POST requests would not be HTTP, is wrong. Please see reBoot's answer for details. It's not very helpful to have the wrong answer show up at the top, but that's how democracy works. If you agree with reBoot, it would be nice if you corrected your answer.
Comment: Eugene, can we agree that a) POST should invalidate the cached entity (per section 13.10), so that e.g. a subsequent GET must fetch a fersh copy and b) that the POST's response can be cached (per section 9.5), so that e.g. a subsequent POST can receive the same response?
Comment: Clarification by Mark Nottingham, with slightly changed wording, is now standardized as [RFC 7231](https://tools.ietf.org/html/rfc7231#section-4.3.3) which obsoletes RFC 2616.
Comment: This section applies to an intermediate cache (like a caching proxy server), not the origin server.
Comment: That is what I meant, that the application running on the origin server is not bound by the HTTP restrictions on caching.
Comment: True, but they can be interpreted in this context too (and they do make sense).
Comment: Diomidis, we can probably agree on many things, but I explicitly criticized the 'if you cached, it would not be HTTP' statement, as the HTTP spec says (albeit formulated in inversely) 'caching is OK, if appropriate headers are used'.
Comment: Eugene, I modified the entry as I suggested.  I can't however see how this would work in practice.
Comment: Yes, under certain conditions, as indicated in the answer.
Answer: According to RFC 2616 Section 9.5:

"Responses to POST method are not
  cacheable, UNLESS the response
  includes appropriate Cache-Control or
  Expires header fields."

So, YES, you can cache POST request response but only if it arrives with appropriate headers.  In most cases you don't want to cache the response. But in some cases - such as if you are not saving any data on the server - it's entirely appropriate.
Note, however many browsers, including current Firefox 3.0.10, will not cache POST response regardless of the headers.  IE behaves more smartly in this respect.
Now, i want to clear up some confusion here regarding RFC 2616 S. 13.10. POST method on a URI doesn't "invalidate the resource for caching" as some have stated here. It makes a  previously cached version of that URI stale, even if its cache control headers indicated freshness of longer duration.
Comment: "making a cached version of the URI stale" applies where you use the same URI for `GET` and `POST` requests. If you are a cache sitting between the client and the server, you see `GET /foo` and you cache the response. Next you see `POST /foo` then you are *required* to invalidate the cached response from `GET /foo` even if the `POST` response doesn't include any cache control headers *because they are the same URI*, thus the next `GET /foo` will have to revalidate even if the original headers indicated the cache would still be live (if you had not seen the `POST /foo` request)
Comment: What's the difference between "invalidate the resource for caching" and "making a cached version of the URI stale"? Are you saying that the server is allowed to cache a POST response but clients may not?
Comment: ```But in some cases - such as if you are not saving any data on the server - it's entirely appropriate.```. What's the point of such a POST API in the first place then?
Answer: If you're wondering whether you can cache a post request, and try researching an answer to that question, you likely won't succeed. When searching "cache post request" the first result is this StackOverflow question.
The answers are a confused mixture of how caching should work, how caching works according to the RFC, how caching should work according to the RFC, and how caching works in practice. Let's start with the RFC, walk through how browser's actually work, then talk about CDNs, GraphQL, and other areas of concern.
RFC 2616
Per the RFC, POST requests must invalidate the cache:
13.10 Invalidation After Updates or Deletions

..

Some HTTP methods MUST cause a cache to invalidate an entity. This is
either the entity referred to by the Request-URI, or by the Location
or Content-Location headers (if present). These methods are:
  - PUT
  - DELETE
  - POST

This language suggests POST requests are not cacheable, but that is not true (in this case). The cache is only invalidated for previously stored data. The RFC (appears to) explicitly clarify that yes, you can cache POST requests:
9.5 POST

..

Responses to this method are not cacheable, unless the response
includes appropriate Cache-Control or Expires header fields. However,
the 303 (See Other) response can be used to direct the user agent to
retrieve a cacheable resource.

Despite this language, setting the Cache-Control must not cache subsequent POST requests to the same resource. POST requests must be sent to the server:
13.11 Write-Through Mandatory

..

All methods that might be expected to cause modifications to the
origin server's resources MUST be written through to the origin
server. This currently includes all methods except for GET and HEAD.
A cache MUST NOT reply to such a request from a client before having
transmitted the request to the inbound server, and having received a
corresponding response from the inbound server. This does not prevent
a proxy cache from sending a 100 (Continue) response before the
inbound server has sent its final reply.

How does that make sense? Well, you're not caching the POST request, you're caching the resource.
The POST response body can only be cached for subsequent GET requests to the same resource. Set the Location or Content-Location header in the POST response to communicate which resource the body represents. So the only technically valid way to cache a POST request, is for subsequent GETs to the same resource.
The correct answer is both:

"yes, the RFC allows you to cache POST requests for subsequent GETs to the same resource"
"no, the RFC does not allow you to cache POST requests for subsequent POSTs because POST is not idempotent and must be written through to the server"

Although the RFC allows for caching requests to the same resource, in practice, browsers and CDNs do not implement this behavior, and do not allow you to cache POST requests.
Sources:

https://www.rfc-editor.org/rfc/rfc2616#section-13 HTTP/1.1 RFC
https://www.mnot.net/blog/2012/09/24/caching_POST

Demonstration of Browser Behavior
Given the following example JavaScript application (index.js):
const express = require('express')
const app = express()

let count = 0

app
    .get('/asdf', (req, res) => {
        count++
        const msg = `count is ${count}`
        console.log(msg)
        res
            .set('Access-Control-Allow-Origin', '*')
            .set('Cache-Control', 'public, max-age=30')
            .send(msg)
    })
    .post('/asdf', (req, res) => {
        count++
        const msg = `count is ${count}`
        console.log(msg)
        res
            .set('Access-Control-Allow-Origin', '*')
            .set('Cache-Control', 'public, max-age=30')
            .set('Content-Location', 'http://localhost:3000/asdf')
            .set('Location', 'http://localhost:3000/asdf')
            .status(201)
            .send(msg)
    })
    .set('etag', false)
    .disable('x-powered-by')
    .listen(3000, () => {
        console.log('Example app listening on port 3000!')
    })

And given the following example web page (index.html):
<!DOCTYPE html>

    <button onclick="getRequest()">Trigger GET request</button>

    <button onclick="postRequest('trigger1')">Trigger POST request (body 1)</button>

    <button onclick="postRequest('trigger2')">Trigger POST request (body 2)</button>

Install NodeJS, Express, and start the JavaScript application. Open the web page in your browser. Try a few different scenarios to test browser behavior:

Clicking "Trigger GET request" displays the same "count" every time (HTTP caching works).
Clicking "Trigger POST request" triggers a different count every time (HTTP caching for POST does not work).
Clicking "Trigger GET request", "Trigger POST request", and "Trigger GET request" shows the POST request invalidates the GET request's cache.
Clicking "Trigger POST request" then "Trigger GET request" shows that browsers will not cache POST requests for subsequent GET requests even though it's allowed by the RFC.

This shows that, even though you can set the Cache-Control and Content-Location response headers, there is no way to make a browser cache an HTTP POST request.
Do I have to follow the RFC?
Browser behavior is not configurable, but if you're not a browser, you aren't necessarily bound by the rules of the RFC.
If you're writing application code, there's nothing stopping you from explicitly caching POST requests (pseudocode):
if (cache.get('hello')) {
  return cache.get('hello')
} else {
  response = post(url = 'http://somewebsite/hello', request_body = 'world')
  cache.put('hello', response.body)
  return response.body
}

CDNs, proxies, and gateways do not necessarily have to follow the RFC either. For example, if you use Fastly as your CDN, Fastly allows you to write custom VCL logic to cache POST requests.
Should I cache POST requests?
Whether your POST request should be cached or not depends on the context.
For example, you might query Elasticsearch or GraphQL using POST where your underlying query is idempotent. In those cases, it may or may not make sense to cache the response depending on the use case.
In a RESTful API, POST requests usually create a resource and should not be cached. This is also the RFC's understanding of POST that it is not an idempotent operation.
GraphQL
If you're using GraphQL and require HTTP caching across CDNs and browsers, consider whether sending queries using the GET method meets your requirements instead of POST. As a caveat, different browsers and CDNs may have different URI length limits, but operation safelisting (query whitelist), as a best practice for external-facing production GraphQL apps, can shorten URIs.
Comment: One of the best answers I've ever seen
Answer: Overall:
Basically POST is not an idempotent operation.  So you cannot use it for caching.  GET should be an idempotent operation, so it is commonly used for caching.
Please see section 9.1 of the HTTP 1.1 RFC 2616 S. 9.1.
Other than GET method's semantics:
The POST method itself is semantically meant to post something to a resource.  POST cannot be cached because if you do something once vs twice vs three times, then you are altering the server's resource each time.   Each request matters and should be delivered to the server.
The PUT method itself is semantically meant to put or create a resource.  It is an idempotent operation, but it won't be used for caching because a DELETE could have occurred in the meantime.
The DELETE method itself is semantically meant to delete a resource.   It is an idempotent operation, but it won't be used for caching because a PUT could have occurred in the meantime.
Regarding client side caching:
A web browser will always forward your request even if it has a response from a previous POST operation.  For example you may send emails with gmail a couple days apart.  They may be the same subject and body, but both emails should be sent.
Regarding proxy caching:
A proxy HTTP server that forwards your message to the server would never cache anything but a GET or a HEAD request.
Regarding server caching:
A server by default wouldn't automatically handle a POST request via checking its cache.  But of course a POST request can be sent to your application or add-in and you can have your own cache that you read from when the parameters are the same.
Invalidating a resource:
Checking the HTTP 1.1 RFC 2616 S. 13.10 shows that the POST method should invalidate the resource for caching.
Comment: "Basically POST is not an idempotent operation. So you cannot use it for caching." That's just wrong, and it does not really make sense, see reBoot's answer for details. Unfortunately, I can't downvote yet, otherwise I would have.
Comment: Eugene: I changed "is not" to "may not".
Comment: Thanks Brian, that sounds better. My problem with your "POST not idemp. -> can't be cached" though was - and I did not make that clear enough - even though an operation is not idempotent that does not mean it is not cacheable. I guess the question is are you looking at it from the point of view of the server, who offers the data and knows its semantics, or are you looking at it from the receiving side (be it a caching proxy etc. or a client). If it's the client/proxy pov, I totally agree with your post. If it's the server  pov, if the server says: "client can cache", than client can cache.
Comment: Eugene: If it makes a difference whether it is called once or 5 times, such as if you are posting a message to a list, then you want that call to hit the server 5 times right?  And you don't want to cache it so it doesn't hit the server right? Because there are side effects that are important.
Comment: [cont'd] I have however not made my mind up whether the server indeed should send cache-allowing expires header ONLY if it the operation is idempotent. It kind of makes sense, though, I guess. [just saw your response]: Agreed, so I gues I made my mind up: Server should only signal cacheability in case of idempotency - and that could be a POST as well, especially considering the need for X-HTTP-Method-Override in some cases.
Comment: The OP asked if it was possible, not if it should be done, and the HTTP specification (as referenced in other answers) does indicate that a server may return cache headers to indicate that the response can be cached.

The rest of the detail in your answer is good.
Comment: `REST` - "POST not idemp. -> can't be cached", `HTTP` - "POST can be cached". Choose depending on whether you're sticking to REST or simply use HTTP to as a data exchange protocol. Both are right in their own domains.
Answer: Mark Nottingham has analyzed when it is feasible to cache the response of a POST. Note that the subsequent requests that want to take advantage of caching must be GET or HEAD requests. See also http semantics

POSTs don't deal in representations of identified state, 99 times out of 100.
However, there is one case where it does; when the server goes out of
its way to say that this POST response is a representation of its URI,
by setting a Content-Location header that's the same as the request
URI. When that happens, the POST response is just like a GET response
to the same URI; it can be cached and reused -- but only for future
GET requests.

https://www.mnot.net/blog/2012/09/24/caching_POST.
Answer: If you do cache a POST response, it must be at the direction of the web application.  This is what is meant by "Responses to this method are not cachable, unless the response includes appropriate Cache-Control or Expires header fields."
One can safely assume that the application, which knows whether or not the results of a POST are idempotent, decides whether or not to attach the necessary and proper cache control headers.  If headers that suggest caching is allowed are present, the application is telling you that the POST is, in actuality, a super-GET; that the use of POST was only required due to the amount of unnecessary and irrelevant (to the use of the URI as a cache key) data necessary to perform the idempotent operation.
Following GET's can be served from cache under this assumption.
An application that fails to attach the necessary and correct headers to differentiate between cachable and non-cachable POST responses is at fault for any invalid caching results.
That said, each POST that hits the cache requires validation using conditional headers.  This is required in order to refresh the cache content to avoid having the results of a POST not be reflected in the responses to requests until after the lifetime of the object expires.
Answer: If it's something that doesn't actually change data on your site, it should be a GET request.  Even if it's a form, you can still set it as a get request.  While, like others point out, you could cache the results of a POST, it wouldn't make semantic sense because a POST by definition is changing data.
Comment: If the parameter data is too long, a GET request won't work with all servers, thus POST is needed, especially if the source should run on servers that the code author doesn't configure.
Comment: The POST request might not be changing any data that is used to generate the response page, in which case it could make sense to cache the response.
Comment: David Z: Surely if a POST is changing data then the response should give some indication of success / failure. Not required exactly, but I can't think of a situation where a POST would change data and the response be static.
Comment: @Gogowitsch very true, you'll run into a 414 error code - https://stackoverflow.com/a/2891598/792238
Answer: With firefox 27.0 & with httpfox, on May 19, 2014, I saw one line of this:
00:03:58.777    0.488   657 (393)   POST    (Cache) text/html   https://users.jackiszhp.info/S4UP
Clearly, the response of a post method is cached, and it is also in https.
Unbelievable!
Answer: POST is used in stateful Ajax.  Returning a cached response for a POST defeats the communication channel and the side effects of receiving a message.  This is Very Very Bad.  It's also a real pain to track down.  Highly recommended against.
A trivial example would be a message that, as a side effect, pays your salary $10,000 the current week.  You DON'T want to get the "OK, it went through!" page back that was cached last week.  Other, more complex real-world cases result in similar hilarity.
Comment: Not really an answer - POST used for all sorts of things and sometimes there are valid reasons to *wish* to cache response.


In Guitar Pro, how do I specify fret numbers for a chord?

Question: I'm using the notation software Guitar Pro to create and edit tablature, and I can't figure out how to specify the fret number that a chord should be played on.  This is different than adding a capo to the track.  I want to specify, for example that the following E9 chord should be played across frets 6-7:
<code>E9:3
</code>
How do I specify fret numbers in the chord builder in Guitar Pro?
Answer: After some poking around I found the UI feature hidden in plain sight--a scroll bar to the right of the chord diagram.
To adjust the fret range, click and drag the scroll bar to the right of the chord diagram.
In Guitar Pro 7 the mouse scroll wheel can also be used.


Alternative to .includes()?

Question: I'm trying to develop a method to match words in array (fItems) with words from a string which has been converted into an Array (stringArray). The code I have below works most the time, but the trouble is that 'includes()' searches for patterns, rather than matching the whole word.
As an example. it gets confused if I'm looking for 'wall', and it returns 'wallet'. Also, I want the input to be flexible. So for instance, if glass is inputted, the item 'glass shard' is still returnable.
Is there are more precise way to match exact words?

for (let i = 0; i < db.items.length; i++) {
  for (let j = 0; j < stringArray.length; j++) {
   if (db.items[i].name.includes(stringArray[j])) {
    fItems.push(db.items[i]);
   };
  }
 };
Comment: You mean just an straight comparison? `db.items[i].name == stringArray[j]`
Comment: So you're trying to get the *intersection* of the two arrays. Look that up, you'll find plenty of solutions on SO.
Comment: No, not a straight comparison. I want the input to be flexible. So for instance, if glass is inputted, the item 'glass shard' is still returnable.
Comment: put the db data
Comment: This sounds like pattern matching on strings, use a regular expression instead. Its faster and easier to use.
Answer: from comment

No, not a straight comparison. I want the input to be flexible. So for instance, if glass is inputted, the item 'glass shard' is still returnable.

It sounds like what you are really after is pattern matching in a string. A regular expression would be the best thing to use for that as this is why they were created (pattern matching with the option of replacement).
let str = 'The glass shard';
let search = 'glass';
let isMatch = new RegExp('\\b'+search+'\\b', 'i').test(str); // i is case insensitive

// If you use unicode characters then this might be a better expression
// thank you @Touffy
let isMatch = new RegExp('(?:^|\\s)'+search, 'i').test(str); // i is case insensitive

In the code above \b is used to denote a word boundary so glass is a match but glassware would not be matched. i is used to specify case insensitive.
Also to test your expressions online before you place them in your code you can use this site https://regex101.com/, I use this all the time to verify the expressions I build are accurate.
Comment: since OP was using `Array.includes`, he may have the option to specify Unicode-safe regexes. Otherwise, don't forget that `\b` will match the empty space between `\w` and any non-ASCII character, including letters commonly used in English such as "é".
Comment: @Igor - and unfortunately, not easy to overcome. `\S` sometimes works as a good-enough replacement for `\w`.
Comment: Thank you. I have to admit, I go a little pale when someone mentions regex. I guess it's time to find a way to learn them. But they do seem to make life easier. I will try to learn to use them.
Comment: Good answer, expect that OP seems to be using ES2015 (`let`) and the code in the answer is ES5.
Comment: @Cuckoo - I added one update to the last expression for if you happen to be searching unicode text. Regular expressions do make life simpler if you deal with a lot of text, I use them regularly (no pun intended) and once you start using them you get the hang of them fairly quickly.
Comment: Thanks again, I'm going to try and implement it.
Comment: I'm struggling to understand how I implement regex with my code. Could you give me an example please? Where the search string is array1 = ["a","wall"]; and the database in array2 = ["a glass shard", "a wallet", "a stone wall"]; - so that it returns 'a stone wall'.
Answer: I think you can use split and indexOf methods instead of it. After split, you can check it with indexOf.

From Comment: As Pavlo said, also you can use includes, instead of indexOf method.

for (let i = 0; i < db.items.length; i++) {
        for (let j = 0; j < stringArray.length; j++) {
            if (db.items[i].name.split(' ').indexOf(stringArray[j])!==-1) {
                fItems.push(db.items[i]);
            };
        }
    };

Comment: You can use `Array#includes` instead of `Array#indexOf`, assuming the code is ES2016.
Comment: @Pavlo thanks for your suggestion. I have just learned it thanks of you :)
Comment: I used includes in the original code I posted, the trouble is it looks for matching patterns, not whole words.
Answer: Make a dot function and use it just like es6 includes() in es5 as below :
String.prototype.includes = function (str) {
 return this.indexOf(str) !== -1;
}

Following is the string
var myString = 'this is my string';

Checking the match as following:
console.log(myString.includes('string')); // true
console.log(myString.includes('street')); //false

Now you can add this for ES5 using same indexOf in includes way

Alternative to .includes()?


Html 5 canvas update with KinetickJS

Question: I am using KinetickJS to draw images on screen.
I have a layer on the stage, and recieve 1000 of images in base64 format.
First I try to draw them with Kinetic
Example 1, works fine BUT after 1000 of images when I try to drag or do something with layer it became veeeeeeeery slow.So I try next example
var imageObj = new Image();
        imageObj.onload = function () {
            var image = new Kinetic.Image({
                x: imageInfo.LocationX,
                y: imageInfo.LocationY,
                image: imageObj,
                width: imageInfo.Width,
                height: imageInfo.Height,
                name: "Update"
            });

            layer.add(image);
            layer.draw();

        };
        imageObj.src = "data:image/jpeg;base64," + imageInfo.Image;

Example 2, but in this case canvas began blinking for each update
var imageObj = new Image();

       imageObj.onload = function () {

                 var canvas = layer.canvas;
                  var context = canvas.getContext('2d');
//                   context.globalCompositeOperation = "destination-over";
             context.drawImage(imageObj, imageInfo.LocationX, imageInfo.LocationY);

            };
        imageObj.src = "data:image/jpeg;base64," + imageInfo.Image;

So do you have any ideas how to make it faster and/or disable blinking?
Comment: Forget to add, maybe its posible to combine or merger images or layers with kinetick. Because I do not need any action with images that come to me I just need to place it to correct position and scale.In this case I will have only one image on layer. Is there any solution for this?
Answer: The newest KineticJS 4.3 speeds up dragging and other functionality quite a lot. This would probably fix your problem.
 http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.3.0.min.js

Html 5 canvas update with KinetickJS


How can I use two resources with the same alias (modx)?

Question: I am using friendly URLS, but Modx doesn't allow to use the same alias name, even if it is in another folder, like for example:
http://www.mypage/friends/blog

and
http://www.mypage/community/blog

is not possible. I get the error message:
Resource is already using the URI

Can somebody help me?
Answer: In System Settings make sure Use Friendly Alias Path is set to Yes.


Differentiating between II and II7 (secondary dominant V of V)

Question: I'm studying harmony and start to make roman numeral analysis on Bach pieces.
I often mistake a II (second degree) for a secondary dominant on the 2nd degree(V7 of V).
I guess there are some notes differences :

the minor 7th must be present in the dominant seventh to create a tritone while the II can just be a triad.
in a major context, II will be minor (ex : Dm in C) while V7 of V will have a major third (ex : D-F#-A-C in C)...

My questions are :

Are these the only difference in notes?
Apart from the notes, what is the difference in terms of harmonic roles between II and V of V in a chord progression?

Thanks.
Answer: First let me make this remark: as always when analyzing, know what key you are in and look for accidentals outside the key. If there are no accidentals outside the key then you can't be dealing with a secondary dominant.
Now let's look at the chords in the key of C major:

ii:   D  F  A
V/V:  D  F# A

ii7:  D  F  A  C
V7/V: D  F# A  C

As you can see the only difference is the F# in both the triad and the seventh, but that is a BIG difference because F# is not in the key of C so that accidental should be a big red flag that you are going outside the key.
As for function it is very simple. They both go to V, but they do it very different ways. ii and ii7 are both predominants so they want to go to a dominant chord (either V, V7, vii°, or vii°7). V/V and V7/V are both dominants that tonicize V (make V sound like the tonic).
The big difference is again going back to the example above is the F# that acts as the leading tone when used as a secondary dominant and makes G feel like tonic. You don't have that tonicization when you are just using ii or ii7.
Comment: You can see a good example of the use of secondary dominants (such as V/V) in the hymn "Now Thank We All Our God" (in the key of Eb, in the music I'm looking at).  The word "our" in "hath blessed us on our way" has a V/V.  Note the A natural, the leading tone for Bb.  This is part of F-A-C, the V of Bb which is the V of Eb.  This strengthens the "fiveness" of the chord witout actually moving to the new key.  If you go further, to the "of" in "with countless gifts of love", you will see a V/ii.  (Again, note the E natural.)  This V/ii strengthens the "twoness" of the ii chord.
Answer: The ii of a major key is a triad (in C) D-F-A. adding a minor 7th will make it minor 7th ( !!) -D-F-A-C. This usually resolves to C through the V - G, or G7.
When a piece may modulate to its dominant (now we're in G ), that ii usually becomes a II, as in D - F# - A (with the optional 7th of C ).That produces the tritone tension to take the piece unequivocally into G.The F# is the leading note of the new key, G.
Using a Dmin. will not have the same push as using D maj. and putting the min.7th of that in as well gives the extra push.
ii-V-I (and II-V-I ) are very common changes , used lots in jazz. Bach used them occasionally.


nginx not acknowledging passenger_root option

Question: I'm running a sinatra app on passenger, and trying to hook it to nginx.
The relevant part of my config looks like:
http {
    passenger_root /path/to/gem; #this is a valid path
    passenger_ruby /path/to/ruby; #ditto

    #etc...

    server {
        listen 80;
        server_name hello.org;
        root /path/to/stuff/public;
        passenger_enabled on;
    }
}

Whenever I start nginx however, I get:
Starting nginx: [alert]: Phusion Passenger is disabled becasue the 'passenger_root' option is not set. Please set this option if you want to enable Phusion Passenger.

What am I missing here? Thanks!
Answer: I had two installs of nginx after I rebuilt nginx with passenger support - the bash script was still reading from the old config!
Answer: I had the same issue as lowgain... using rvm + nginx, I installed passenger, which then recompiled nginx to include passenger stuff. Unfortunately, the old version was at /etc/nginx and the new version at /opt/nginx.
I had to remove nginx via apt:
sudo apt-get remove nginx
I also had to replace /etc/init.d/nginx with a new version. Once I was done with all that, it worked.


Vertical scroll in card doesn't go all the way

Question: I am trying to create a results page where each result is in a card, and inside the card, there are nested information such as menu and name. I want the menu part to be vertically scrollable, but for some reason, the last card doesn't scroll all the way down. I don't want the card to be scrollable, just the menu part.
HTML:

McDonalds

401 College Ave, Ithaca, NY 14850

Filet O Fish

Lightly breaded and fried white fish served on a brioche with romaine
                            lettuce and pickles

5.00

Filet O Fish

Lightly breaded and fried white fish served on a brioche with romaine
                            lettuce and pickles

5.00

Filet O Fish

Lightly breaded and fried white fish served on a brioche with romaine
                            lettuce and pickles

5.00

McDonalds

401 College Ave, Ithaca, NY 14850

Filet O Fish

Lightly breaded and fried white fish served on a brioche with romaine
                            lettuce and pickles

5.00

Filet O Fish

Lightly breaded and fried white fish served on a brioche with romaine
                            lettuce and pickles

5.00

Filet O Fish

Lightly breaded and fried white fish served on a brioche with romaine
                            lettuce and pickles

5.00

McDonalds

401 College Ave, Ithaca, NY 14850

Filet O Fish

Lightly breaded and fried white fish served on a brioche with romaine
                            lettuce and pickles

5.00

Filet O Fish

Lightly breaded and fried white fish served on a brioche with romaine
                            lettuce and pickles

5.00

Filet O Fish

Lightly breaded and fried white fish served on a brioche with romaine
                            lettuce and pickles

5.00

CSS:
.result {
 overflow: hidden;
 max-height: 350px;
 margin-bottom: 20px;
 background-color: white;
}
enter code here
.rest-title {
 font-size: 2rem;
 font-weight: 700;
 margin-bottom: 0px
}

.rest-address {
 font-family: 'Open Sans';
 font-size:14px
}

.item-container {
 overflow-y: scroll;
}

Comment: Do you want to scroll in x-asis or y-asis? I am able to scroll with your code in y-asis.
Comment: y axis, but for me, it doesn't scroll all the way down, as shown in the picture. Part of it cuts off
Answer: In every group of item-containers, the last divs are crushing because you set max-height for them.
In the .result class, you're setting;
max-height:350px
overflow: hidden

Because of these two, you cannot fully see the last items of .item-container class. So, if you will change the overflow attribute like overflow-y: scroll, it should solve your problem. With this solution, you will be able to scroll in all results.
If you want to scroll in .item-containter only; you should set a max-height and keep the  overflow-y:scroll.


Is there an easy way to get longest word that contains a certain letter?

Question: I am trying to get the largest word that contains the letter 'f' through a for loop, through my code I tried to make it as simple as possible with a if and and statement. It is however not working as it returns the largest word but not the one that includes the letter f, why is it not working?
def main():
    sentence = "Absence makes the heart grow fonder"
    letter = "f"
    longest_word = get_longest_word(sentence, letter)
    print('"' + longest_word + '" is the longest word containing the letter "'
          + letter + '".')

def get_longest_word(sentence, letter):
    words_list = sentence.split()
    largest = words_list[0]
    my_list = []
    for word in words_list:
        if letter in word and len(word) > len(largest):
            largest = word
    return largest

main()

Comment: The problem is that you initialise `largest` to the first word, even if it doesn't have the sought letter. Initialise it to `''` and get rid of `my_list` (which you're not using)
Answer: The reason is that you initialise largest to words_list[0], which is 'Absence', the longest word in the sentence.
Therefore, even when 'fonder' is reached, even though the first part of your if passes (it contains an 'f'), the second part about length does not.
Personally, I would just do this:
from operator import itemgetter

def get_longest_word(sentence, letter):
    words_with_letter = ((word, len(word)) for word in sentence.split() if letter in word)
    return max(words_with_letter, key=itemgetter(1))[0]

This converts the sentence into an iterable of tuples where the first element is the word and the second its length, and where all the words already contain the letter in question.
Then, all we need to do is get the word with the longest length i.e. the highest value in the second position.
Output:
"fonder" is the longest word containing the letter "f".

Answer: You can approach this much more easily using the in operator:
for word in word_list:
    if 'f' in word:
        longest_words.append(word)

longest_word = sorted(longest_words)[0]


MVC em C#, separar por pastas ou biblioteca de classes?

Question: Vi uns exemplos que separam por pastas, e outros que separam por uma biblioteca de classes e depois cria o apontamento nas referências. Ambas as formas podem ser usadas?
Comment: ViewModel... se você vai utilizar apenas em um projeto MVC, não vejo problema de estar no mesmo namespace da aplicação web... agora se vc já for utilizá-las em um a aplicação web e em uma web api (por exemplo), não faria sentido estar em uma biblioteca comum para ambos?
Comment: Existem alguns padrões, como o famoso "N-Tier Layer" (Aplicação com várias camadas) e o Domain-Driven Design http://www.eduardopires.net.br/2014/10/tutorial-asp-net-mvc-5-ddd-ef-automapper-ioc-dicas-e-truques/, recomendo de inicio você estudar bastante orientação a objetos (OO) e o SOLID http://www.eduardopires.net.br/2013/04/orientacao-a-objeto-solid/
Comment: Olá Jean, na pergunta eu não quis perguntar sobre qual design-pattern é melhor. Mas sim sobre a diferença, no C# MVC, separar a model view... Por pastas, ou criar uma biblioteca de classes e fazer o apontamento nas referências.
Answer: ambas podem ser usadas sim, porém ambas tem sentidos em seu uso.
Eu geralmente separo por bibliotecas os recursos que são e podem ser acessíveis por outras aplicações, não apenas a MVC, por exemplo se criar uma aplicação que consuma classes em comum, como por exemplo entidades da base de dados, seria interessante separa-las e manter o recurso comum entre elas em outro local (DLL por exemplo).
Já essa questão de pastas eu separo por pastas os meus projetos para agrupamentos e separação das camadas da minha aplicação como um todo, exemplo a camada responsável pelos dados, pela apresentação da aplicação ao usuário final, pelos serviços distintos se houver, etc.
Espero ter ajudado! :)


Knowing if an account had tweeted

Question: Background info:
My website has an account system and we wanted to give the accounts "reward points" everytime they tweeted / facebook share.
For facebook share, we are able to track which account had shared by using the redirect_uri and redirect them back to our site (with the specified url) and noting it. https://developers.facebook.com/docs/reference/dialogs/feed/
Is there such thing on twitter as well? I had been trying to find real hard but i can't find a way for me to inform my system that a certain account had tweeted.
Thanks!
Answer: One of the basic objects in the Twitter API is the User object, which gives you a decent amount of information about the user in question.  Once of the properties of the User object is called "status", which is a Tweet object, which is the user's most recent tweet.
So, in your application, you could store the unique identifier and date/time of the user's last tweet.  Then at an interval of your choosing, you could get the information about the user and see if the ID of their most recent tweet matches what you have in your database.  If it does not match, then the user has posted a new tweet.
Twitter API documentation of the User object
Twitter API documenation of the Tweet object

Knowing if an account had tweeted


How to add notification value for item on NavigationView for Material Design Drawer?

Question: My question is very simple, how to add a notification value right of the item on NavigationView for Material Design Drawer like that ?

Is there a property in the menu items for defining the drawer?
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <group
        android:checkableBehavior="single">

        <item
            android:id="@+id/drawer_home"
            android:checked="true"
            android:icon="@drawable/ic_home_black_24dp"
            android:title="@string/home"/>

        <item
            android:id="@+id/drawer_favourite"
            android:icon="@drawable/ic_favorite_black_24dp"
            android:title="@string/favourite"/>
        ...

        <item
            android:id="@+id/drawer_settings"
            android:icon="@drawable/ic_settings_black_24dp"
            android:title="@string/settings"/>

    </group>
</menu>

Comment: for that you have to make your own `listview` inside navigation view.Because `NavigationView` doens't allow much flexibility.
Comment: @Moinkhan Exactly my question is whether the View navigation component to at least this flexibility. Good practice grow to use this component, so ...
Comment: Oh yeah.. and may be they improved navigation view in future release.
Comment: @Moinkhan Additionally, ListView is now replaced by RecyclerView.
Comment: you can work with a ListView or a recycler view inflating a custom row layout with the notification count view hidden for every row and in getView() or in onBindViewHolder() you can set the count and make the count view visible
Comment: @Moinkhan Yes, I also think it will be !! :)
Comment: Thank you @chiragjn it's the same proposal that Moinkhan. There is thus no property in the menu?
Comment: There are no attributes to do what you want directly. You could have done it easily if the actionLayout for a MenuItem would be considered, but from my quick tests that doesn't happen. The only way to do it and have the default NavigationView would be to include the "notification" in the title of the MenuItem(this however would be hacky(hard to do right) as hell and not recommended at all). In the end as others pointed out use a ListView, RecyclerView etc. I don't know if you looked but maybe you could find some already made libraries(I've seen some for this navigation).
Comment: Thank you for your reply @Luksprog . But yes, it's very simple to do with a RecyclerView or other ListView. But the idea was really to exploit the news component of Android Material Design .. I really hope that they will improve in the next release.
Comment: You can check this answer for similar question: http://stackoverflow.com/questions/30560663/navigationview-menu-items-with-counter-on-the-right/33607630#33607630
Answer: This is possible with NavigationView from Version 23 of AppCompat-V7 using action views.
1. Create a layout for the counter e.g. nav_drawer_counter.xml:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:gravity="center_vertical"
    android:textColor="@color/colorPrimary"/>

Add a reference to it from each item you'd like to show a counter value for in your menu/nav_drawer.xml (ensure you use the app namespace):
<item
    ...
    app:actionLayout="@layout/activity_main_nav_drawer_menu_counter"
    />

Add a method to set a value to the TextView e.g:
@Override
protected void onCreate(Bundle savedInstanceState) {
....
setNavItemCount(R.id.nav_notifications, 10);
}

private void setNavItemCount(@IdRes int itemId, int count) {
TextView view = (TextView) navigationView.getMenu().findItem(itemId).getActionView();
view.setText(count > 0 ? String.valueOf(count) : null);
}

Answer: Oh Yes... You can change that counter value.
From the images given by you it looks live you are using Rudson Lima's Material Design Navigation Drawer
In its library there is a function public void setNewCounterValue(int drawerItemPosition, int counterValue); inside the class NavigationLiveo.
Hope you will use its object properly to call this function.
Best of Luck... :-)
Comment: You have the best answer so far on this issue, I give you so the bounty. Nevertheless, I think now it is simply not possible without using a library... I hope that Google will update its NavigationView component to enable it natively.
Comment: Thank you... And you are correct its still not available in NavigationView support library. Hope Google will give it soon to all.
Answer: You should check exactly how it was done on the original project's github:
https://github.com/rudsonlive/NavigationDrawer-MaterialDesign/
https://play.google.com/store/apps/details?id=br.liveo.navigationliveo
Basically you create a custom view for the ListView's lines and update them accordingly.
Answer: From some research, I have found that, no, there is no real way to add the notifications to the drawer. However, the example shown in the Creating a Navigation Drawer tutorial at Developers shows how to force a redraw every time it is opened (and also how to implement it with the Menu XML sheets). It does not go into detail about how to add the notifications, but there are other sources for that.
This tutorial is another "how to make a navigation drawer" tutorial with the bonus of exact details on how the adapted the ListView adapters to suit a notification button. I think this is more than likely what you are looking for.
Good luck! I hope that helps.
Answer: You could use a library for this. Try MaterialNavigationDrawer or MaterialDrawer


IIS URL Rewrite rule - How can I remove some segments?

Question: I have read the article Creating Rewrite Rules for the URL Rewrite Module at iis.net and I would like to remove some segments from my urls.
for example, from:
/article/archive/2289/01/articleid/191/reftab/36/word1 word2 word3

to:
/article/articleid/191/word1-word2-word3

I have changed my web.config file with this but I don't be able to solve my issue:
<rewrite>
  <rules>
    <rule name="Remove segments">
      <match url="^article/archive/2289/01/([0-9]+)/([_0-9a-z-]+)" />
      <action type="Rewrite" url="article/articleid/{R:1}/{R:2}" />
    </rule>
  </rules>
</rewrite>

Answer: It looks like you are trying to do it backwards.  The <match> element represents the friendly URL - the URL the user enters in the browser, the URL contained in a link, and the URL that IIS receives.
The <action> element represents the unfriendly URL - the ugly URL that you would have to use if you weren't using the rewrite module.
<match url="^article/articleid/([0-9]+)/([_0-9a-z-]+)" />
<action type="Rewrite" url="/article/archive/2289/01/articleid/{R:1}/reftab/36/{R:2}" />

The trouble here is that you probably don't want to hardcode 2289/01, right?  You'll need to incorporate that into your friendly URL, or come up with some intermediary handler that can handle the request without those numbers.


React Router in app served from Google Cloud Storage

Question: I'd like to serve a React app from static file storage (Google Cloud Storage, AWS equivalent is S3).
In the past I've only ever deployed React apps to an NGINX server (or in an NGINX container) where I can configure all requests to point to index.html, regardless of the requested path, so that React Router can handle the routing on the client side.
I'm struggling to understand how this would work in static file storage, by just running npm run build and uploading the built app to Cloud Storage.
Example: To my understanding, if you request <domain>/profile, it will look for a file named "profile" in static file storage and then return the storage provider's 404 page if it doesn't exist. But I want this to be handled by React Router, which means this request still technically returns the index.html page, then the JavaScript on the client side looks at the URL and renders either the profile page component or a soft 404 page component which I can customise from within my React app.
Answer: Okay, so 6 months down the track, I now have the answer and I'm sharing it to help anyone who's stuck like I was.
When configuring a GCS bucket to serve a static site, you are given the choice to choose which file it should serve as the index page, and which file to serve on a 404. Turns out, you can pretty easily achieve client-side routing on a Single Page App (with any JavaScript framework) by configuring the bucket to point all traffic that would return a 404 page to the same index.html file. This way, it will still render the "single page" that holds all the client-side routing logic, and the path it looks at will be in the URL!
TLDR; Set index.html as your custom 404 page.


UIAppearance of UILabel whithin UICollectionViewCell - selected/unselected

Question: I am currently working with UIAppearance for the colors of all my outlets on my project, which allowed me to create my own "DIY" version of a nightmode on my iOS app.
sample :
UILabel.appearance().textColor = colorScheme.primaryColor
UILabel.appearance(whenContainedInInstancesOf: [MyController.self]).textColor = colorScheme.secondaryColor
...

Note: Colorscheme is just a struct with all my colors, that switch depending on the state .lightMode / .darkMode
I recently build a subclass of UICollectionViewCell with a UILabel inside, and I wanted to use the same method to define the colors within it. However I am troubling to figure out how to set a different color for the nested UILabel depending on the selected state of the Cell.
For instance :
// create a default UIView with specific backgroundColor
let selectedBackgroundView = UIView()
selectedBackgroundView.backgroundColor = colorScheme.selectedBackgroundColor

MyCollectionViewCell.appearance().backgroundColor = colorScheme.backgroundColor // default
MyCollectionViewCell.appearance().selectedBackgroundView = selectedBackgroundView // set specific view used when cell is selected

This code above works fine when I want to set different background colors when MyCollectionViewCell is selected or not, however I want the nested UILabel to change its fontColor as well, depending if the cell is selected or not. Is there a propper way to achieve this with UIAppearance?
Answer: Finally found a Workaround for this issue. I post my solution it may help someone.
first I define the color for both textColor and highlightedTextColor
UILabel.appearance(whenContainedInInstancesOf: [MyCollectionViewCell.self]).textColor = colorScheme.color1
UILabel.appearance(whenContainedInInstancesOf: [MyCollectionViewCell.self]).highlightedTextColor = colorScheme.color2

Then in MyCollectionViewCell I "bind" the isSelected to UILabel isHighlighted :
class MyCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var myLabel: UILabel!

    override var isSelected: Bool {
        didSet {
            self.myLabel.isHighlighted = isSelected
        }
    }
}

Works flawlessly.
Hope this can help someone


Which statistic to report for repeated cross-validation?

Question: I am doing 10 times repeated 10-fold cross-validation and now I want to report the results.
What is best practice: Report the statistics over all 100 folds or to report the statistics of the means of 10 times 10-fold CV runs?
Comment: The mean is the same in both cases. Suppose you do $n$ repeats of $k$-fold cross-validation. Let $S_{i,j}$ be the test score on the ith repetition and jth fold, then the mean of the means is:

$$\frac{1}{n}\sum_{i=1}^n M_i = \frac{1}{n}\sum_{i=1}^n \frac{1}{k}\sum_{j=1}^k S_{i,j} = \frac{1}{nk}\sum_{i=1}^n\sum_{j=1}^k S_{i,j},$$

which is just the mean over all folds.
Answer: The difference between the two should not be large. That said, Kim (2008) "Estimating classification error rate: Repeated cross-validation,repeated hold-out and bootstrap" that does present an investigation of repeated CV stipulates explicitly: "we obtain the $10$-fold CV estimates $5$ times, and take the average as the final estimate" when presenting the results of repeated CV. To that respect, one of the first widely-cited papers to suggested repeated CV, Dietterich (1998) "Approximate Statistical Tests for Comparing Supervised Classification Learning Algorithms" the description of  $5\times2$-CV is based on five iterations of two-fold cross-validation and the subsequent averaging of the 5 measurements.
So to answer the final question: it would more reasonable to report "means of 10 times 10-fold CV runs" rather than the means of 100 folds.
Comment: Thanks for your answer. However, it does not clarify why they did how they did.
Answer: I would tend towards reporting the statistics (including range) of the 100 folds, even though the 10 fold results are not independent. While this may not be entirely valid, it is usual for people to report the range of 10-fold results when doing one repetition of 10-fold cross-validation.
Including the range should somewhat counteract the smaller CI likely from having a greater number of (non-independent) results to report.
If you wanted to be very thorough, you could fit a random intercept model for each repeat of CV results $y_i$ to account for correlation between CV results:
$$
y_i \sim N(\mu_i, \sigma_i) \\
\mu_i \sim N(\mu_0, \tau)
$$
where $\mu_i$ is the mean for CV repetition $i$ and $\mu_0$ is the overall mean, $\sigma_i$ is the variability for an individual CV repition, and $\tau$ is the variability of CV means across repetitions.
fwiw I think this model is excessive, and examining the full results from repeated CV should allow you to find the optimal/most parsimonious model fairly accurately.


egrep to print output on the same line

Question: I am running a command and filtering out multiple words using egrep but output is showing up in multiple lines, is there a way i can get the output in a single line with particular set of matched words.
egrep -n "name|recovery"

currently getting output as
6:    "name": "7660",
27:      "recovery": "2020-08-04",
40:    "name": "7667708",
61:      "recovery": "2020-08-03",
74:    "name": "7660271",
95:      "recovery": "2020-08-02",

Required output
1:    "name": "7660", "recovery": "2020-08-04"
2:    "name": "7667708", recovery": "2020-08-03"
3:    "name": "7660271", "recovery": "2020-08-02"

Comment: can you add sample input from which the present output is shown? that way you might get a simpler answer using `awk` instead of trying to process the current output with other tools
Answer: You can pipe several commands to achieve that.
<<your command>> | cut -d: -f2- | sed '{N;s/,\n/,/;}' | grep -n '^'

Answer: Since the pattern for your results is every other line, an easy solution is to use the paste command. For example:
egrep -n "name|recovery" | paste - -

The output is separated by tabs by default. The technique is also useful when using egrep -o with multiple matches on the same line of source text.

egrep to print output on the same line


Field collection with condition node tpl

Question: I've been researching this for the last few days and I cant find a clear explanation of this issue im facing.  I'm receiving an error when a node has an empty collection with no values.
The collection field: field_window_shade
The fields within the collection: field_question, field_answer
Here is my code that is only looping thru the collection array within my node.tpl:
            $wrapper  = entity_metadata_wrapper('node', $node);
            $formtype = field_get_items('node', $node, 'field_window_shade');

            foreach($formtype as $itemid) {
                 $item = field_collection_field_get_entity($itemid);
                 print $item->field_question['und'][0]['value'];
                 print $item->field_answer['und'][0]['value'];
            }

I am after something like this:
            $wrapper  = entity_metadata_wrapper('node', $node);
            $formtype = field_get_items('node', $node, 'field_window_shade');

            if (isset($wrapper->field_question)) {
              foreach($formtype as $itemid) {
                 $item = field_collection_field_get_entity($itemid);
                 print $item->field_question['und'][0]['value'];
                 print $item->field_answer['und'][0]['value'];
              }
            }

I've seen this question asked about 5 different times with 10 different solutions and I can't seem to reach a solution here.
Thank you !
Answer: Did you try field_collection_item in entity_metadata_wrapper? I mean this
$wrapper  = entity_metadata_wrapper('node', $node);
$raw_collection = $wrapper->field_window_shade->value();
$fwrapper = entity_metadata_wrapper('field_collection_item', $raw_collection);

Now use $fwrapper to extract the items (This code is not completely accurate a few modification may be needed)
Visit Extracting a specific data part of a Field Collection Item for more details. Also Programmatically create and update field collection with Entity API and Understanding Field Collection Values can be helpful.
Comment: You welcome. But your answer which is marked as accepted is not similar to my solution
Answer: I've solved this by using the correct field format (filter) type.
here: $item->field_answer->value->raw();  error is now gone
     <?php
            $wrapper         = entity_metadata_wrapper('node', $node);
            $raw_collection = $wrapper->field_window_shade->value();

            foreach ($wrapper->field_window_shade as $item):
                print "

" . $item->field_question->value() . "

";
                print "

" . $item->field_answer->value->raw() . "

";
            endforeach;
        ?>


properties of transformations inbetween quotient modules

Question: Let $R$ be a ring, $M$ and $R$-left module and $U, V$ submodules of $M$. I want to show that
$$f: M/U \cap V \to M/U \oplus M/V, m + U \cap V \mapsto (m + U, m + V)$$
and
$$g: M/U \oplus M/V \to M/(U+V), (m + U, n + V) \mapsto m - n + U + V$$
are two well-defined linear transformations, and that f is injective, g is surjective and $\ker g = Im f$.
Thanks in advance. I'm not quite used to working with constructions like these, so any help would be appreciated.
Answer: Well, the first is clearly well-defined, for if $m_1 + (U\cap V)$ and $m_2 + (U \cap V)$ are representatives of the same class, then $m_1 - m_2 \in (U \cap V) \subset U$, so $m_1 + U$ and $m_2 + U$ represent the same class in $M/U$, and a similar argument works for $V$.
Can you run with that to show that the second is well-defined?
Answer: I'll leave well-defined and linear to you since I don't like to show those two.
To show $f$ is injective, note if $x\in M/(U\cap V)$ with $f(x)=(0,0)$ then $x\in U$ and $x\in V$. So $x\in U\cap V$, i.e. $x=0\in M/(U\cap V)$.
To show $g$ is surjective, note for $x\in M/(U+V)$ we can take $(x+U,0+V)$ so that $f(x+U,0+V)=x+U+V$.
Take an element $m+(U\cap V)$. Then $f(m+(U\cap V))=(m+U, m+V)$. Now $g(m+U, m+V)=m-m+U+V= U+V$ so that $\operatorname{im}(f)\subset\ker(g)$. And you need to show the reverse inclusion.
Comment: Okay, thanks, that definitely helped. Regarding the other inclusion... if $(m + U, n + V)$ with $g(m + U, n + V) = 0 + U + V$. Then $m - n + U + V = 0 + U + V = 0 + U + 0 + V = m + U - n + V$, I think. Does this already implicate that $m + (U + V) = n + (U + V)$? And if I'm not mistaken, then $U \cap V \subseteq U + V$, so therefore $m + (U \cap V) = n + (U \cap V) => (m + U, n + V) \in im(f)$. Is this correct?
Comment: @moran Yes, $m-n+(U+V)=(U+V) \implies m+(U+V)=n+(U+V)$. But I do not think since $U\cap V \subseteq U+V$ we have $m+(U+V)=n+(U+V)\implies m+(U\cap V)= n+ (U\cap V)$ for take the $\mathbb{Z}$-modules $U= 2\mathbb{Z}$, $V=4\mathbb{Z}$, $m=1$ and $n=3$. This gives a counterexample.


HTTP POST request test is not getting passed

Question: I wrote some nodejs codes to be evaluated by a particular test file, candidate.test.js but surprisingly the test keeps failing. Below is the error I am getting:

Error: expect(received).toEqual(expected) // deep equality
Expected: 201
Received: 500

I have below the snippet from both app.js and candidate.test.js.
candidate.test.js
const request = require('supertest');

const app = require('../app');

// ...
async function makeRegularGetRequest(requestBody) {
  return await request(app)
    .post('/restaurant')
    .send(requestBody)
    .expect('Content-Type', /json/);
}

  it('should create a restaurant given valid parameters', async () => {
    const requestBody = {
      name: '123',
      position: 200,
      category: 'Pizza',
      rating: 5,
    };
const createResponse = await makeRegularPostRequest(requestBody);
try {
      expect(createResponse.status).toEqual(201);
    } catch (error) {
      throw error;
    }
  });
// ...

app.js
// ...
app.post('/restaurant', (request, response) => {
  const id = generateRandomString();
  const { name, position, category, rating } = request.body;
  const restaurant = {
    name: name,
    position: position,
    category: category,
    rating: Number(rating),
    id: id,
  };
  restaurants.push(restaurant);
  response.send(restaurant).status(201);
});
// ...

I also tried sending only the statusCode to the page using reponse.send(restaurant).status(201).statusCode, but the error still comes out.
I tested this on Postman and it works really fine but it's strange that the test does not pass.
Comment: You can copy request code from postman also right side from this icon <> it's good for you.
Thanks
Answer: can you console log before and after pushing to restaurants array
Comment: Do you mean I should log the restaurant object?
Comment: No, I mean to log before and after the restaurants array to know weather the error comes from it or not, you got error 500 which means internal server error so we don't know really where is the error in your server
Comment: I did that already and everything looked cleans when I run the file but when I run the test, console log does not work. When I remove ```restaurants.push(restaurant);```and run the test, it shows server timeout. If I remove the route, it show 404.
Comment: try something return await request(app)
    .post('/restaurant')
    .send(requestBody)
    .expect('Content-Type', /json/);
} instead of  .expect('Content-Type', /json/) just add .expect(201)
Comment: I was given the test file and the instruction given does not allow me to edit it.
Comment: are you sure that the app been required in the test file is required correctly? I mean is it the same app running of your server
Comment: Yes, because when I remove the route, it changes the error to 404, which means the route is not found.


How do I communicate from VB6 to a server-side PHP API?

Question: This is a question about communication between VB6 and server-side PHP.
WooCommerce has a plugin that lets you serialize sales of software products. It communications to software applications via a PHP API. The syntax of an API call is like this:
wp_get_request('http://188.8.131.52/~fab/?wc_api=software_api&request=request_key&Secret_Key=<sekret>&email=<email>')

I have a VB6 application that needs to communicate with this api. I am using the following code to send the URL request:
blah = INetObject.OpenURL("http://184.108.40.206/~fab/wp_get_request('http://22.214.171.124/~fab/?wc_api=software_api&request=request_key&Secret_Key=<sekret>&email=<email>')")

The API is supposed to return a JSON object (blah) which I then parse to get the data I want. However it is not working. I've tried various syntactical permutations to no avail. Mostly I get an XML description of the destination page, so my question is this:
How do I communicate to this API from VB6? I've been working this issue for about a week with no results.
Comment: Thanks for the tips. The "Secret Key" is just for the test order. Secret Keys are changed for every order so I'm not giving anything away. When I tried your suggestion I got the following:
Comment: Here's part of what is returned:     and much more. It appears to describe the page of the URL in the call. The WooCommerce API doesn't appear to be triggered by the "wp_get_request" text. According to the WooCommerce docs, the API is supposed to be listening all the time.  Because I'm getting some response, I think the call is getting made from VB6.  I have no clue about web site stuff so there may be something obvious I'm missing.
Comment: Exactly right, Deanna. You've saved me many hours. I'd give you 5 stars, but I don't know how.
Answer: You're confusing the API to be used internally in wordPress code, and what you need to call externally.
This sample was given by you and calls a function internal to WordPress to make the HTTP request:
wp_get_request('http://188.8.131.52/~fab/?wc_api=software_api&request=request_key&Secret_Key=<sekret>&email=<email>')

The equivalant of the wp_get_request() in VB6 would be INetObject.OpenURL():
blah = INetObject.OpenURL('http://188.8.131.52/~fab/?wc_api=software_api&request=request_key&Secret_Key=<sekret>&email=<email>')

Your mistake was trying to mash the two together, thinking wp_get_request was part of the HTTP API itself.
Comment: @user1422047 If this did help, please [accept the answer](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) by clicking the green tick to the left of the post.


One submit button posting to multiple functions

Question: I am displaying a form inside a block and I want it to submit to multiple functions, namely the original submit functions and in addition my own pm_form_submit. Yet I can't get it to work... you can submit to multiple functions right?
In the case bellow only "Test Form Submit" (the original submit function) is displayed.
Submit button of my test form:
function test_form_form ($form,&$form_state){
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );

  return $form;
}

My code for displaying the form in a block:
$form = drupal_get_form ('test_form_form');

//add our submit function (both are here just to test)
$form ['#submit'][] = 'pm_form_submit';
$form ['submit']['#submit'][] = 'pm_form_submit';

$output .= drupal_render ($form);
return $output;

My submit functions: (the pm_form submit is in the same file where I alter the form and the test_form_form_submit is in the file where the form is generated)
function pm_form_submit ($form, &$form_state) {
  drupal_set_message('pm_form_submit');
}

function test_form_form_submit(&$form, &$form_state) {
  drupal_set_message('Test Form Submit');
}

when I print_r the $form array I can see the following:
[submit] => Array
    (
        [#type] => submit
        [#value] => Submit
        [#input] => 1
        [#name] => op
        [#button_type] => submit
        [#executes_submit_callback] => 1
        [#limit_validation_errors] =>
        [#process] => Array
            (
                [0] => ajax_process_form
            )

        [#theme_wrappers] => Array
            (
                [0] => button
            )

        [#defaults_loaded] => 1
        [#tree] =>
        [#parents] => Array
            (
                [0] => submit
            )

        [#weight] => 0.001
        [#processed] => 1
        [#required] =>
        [#attributes] => Array
            (
            )

        [#title_display] => before
        [#id] => edit-submit
        [#ajax_processed] =>
        [#sorted] => 1
        [#submit] => Array
            (
                [0] => pm_form_submit
            )

    )

...
[#submit] => Array
    (
        [0] => test_form_form_submit
        [1] => pm_form_submit
    )

Answer: You can't add submit handlers to form after drupal_get_form() is called, because they will not be processed.
You need to add submit handler in hook_form_alter(). If you want add this handler only in specific cases, you can add cutom parameter to drupal_get_form()
Code in block:
$form = drupal_get_form('test_form_form', 'add_pm');
$output .= drupal_render($form);
return $output;

Code in custom module:
function MODULE_form_alter(&$form, &$form_state, $form_id) {
   if (($form_id == 'test_form_form') && ($form_state['build_info']['args'][0] == 'add_pm')) {
     // add custom submit only if form was called with parameter.
     $form ['#submit'][] = 'pm_form_submit';
   }
}

function pm_form_submit($form, &$form_state) {
  drupal_set_message('pm_form_submit');
}

Comment: @WillemdeVries Sorry, think I must've misunderstood your question. I thought you created the test form yourself - if not, then ignore everything I've said, form alter's the way to go! If you define the form function yourself, then you don't need to use an alter.
Comment: or do it in `test_form_form()`
Comment: Thx, now I finally understand what this hook_form_alter is for. Yet this posses a different problem.. I can not change the code of the module that contains the form... so I can not add my own custom hook_form_alter there... any ideas on that?
Comment: Aa all hook_form_alters are called.;-) THX
Comment: @WillemdeVries Typically a form alter is used to alter a form provided by _another_ module. In this case you can also add the submit handler directly in `test_form_form()`.
Comment: @Andy thank you, yet wouldn't I need access to the test_form module for that? I can not change the code of the modules loaded only my own.


Can't configure Entity Data Source to work with Entity Framework 6

Question: I'm trying to use Entity Data Source Control to access my database first Entity Framework model but I can't get it to work with Entity framework 6. It gives me an error saying its not compatible with Entity Framework 6 and instead directed me to install Microsoft.AspNet.EntityDataSource from Nuget which I've done. but for some reason I can't configure it using the wizard. In design view, it doesn't show the little arrow to open the smart tasks panel.
I'm new to ASP.NET and don't know how to configure it in markup view
which data source (or perhaps another technique) should I use to access data objects in Entity Framework 6?
Comment: Im also facing to the same issue. It says to do it manually in mark up but still not figure it out to do it. Anyway I  solved my issue using Linq table join query
Answer: I don't think you can use the wizard to configure EF6 EntiyDataSourceControl. The wizard only works with EF5. You need to configure the EF6 EntityDataSourceControl in code. Here is a corresponding ticket.
Answer: I have gone through same situation as yours.Finally this solved the issue,
Uninstalled EF6 and installed version 5 of Entity Framework through Nuget Package Manager Console, then it worked fine


Como retornar todas as colunas de uma pesquisa trazendo apenas aquelas com maior data

Question: Preciso obter o seguinte retorno:

Id    |CodCliente | Data      |Valor
47    |27         |2021-01-06 |58140000.00
72    |3          |2021-01-11 |18224000.00

declare @tab1 table (
    Id int,
    CodCliente int,
    Data date,
    Valor decimal(18,2)
)

insert into @tab1 (Id, CodCliente, Data, Valor) values (    47, 25, '01/12/2020',   64260000.00 )
insert into @tab1 (Id, CodCliente, Data, Valor) values (    47, 27, '01/06/2021',   58140000.00 )
insert into @tab1 (Id, CodCliente, Data, Valor) values (    72, 3,  '01/11/2021',   18224000.00 )
insert into @tab1 (Id, CodCliente, Data, Valor) values (    72, 11, '01/12/2020',   5100000.00  )

select Id, CodCliente, Data, Valor from @tab1

Id  |CodCliente | Data      |Valor
47  |25         |2020-01-12 |64260000.00
47  |27         |2021-01-06 |58140000.00
72  |3          |2021-01-11 |18224000.00
72  |11         |2020-01-12 |5100000.00

Tentei fazer algo assim mas não desse jeito não me retorna todas as colunas que preciso conforme citado no inicio:
select Id, Max(Data) as Data from @tab1 group by Id

Id  | Data
47  |2021-01-06
72  |2021-01-11

Comment: select * from @tab1 t1 where t1.Data  = (select Max(t2Data) as Data from where t2.Id = t1.Id)
Comment: @Motta funcionou perfeitamente
Answer: Algumas coisas pra dizer a respeito da sua pergunta.
1º tu criou o campo ID que normalmente é a chave primaria. Esse campo não pode repetir valor
2º Tu nomeou um campo como "Data" ... isso ai é palavra reservada. Pra evitar problemas, tenta colocar nas próximas vezes o que o campo representa. Ex: data_nascimento.
Lista de palavras reservadas: https://docs.microsoft.com/pt-br/sql/t-sql/language-elements/reserved-keywords-transact-sql?view=sql-server-ver15
3º Vou considerar que tu quer trazer simplesmente os 2 resultados com data mais recente. Nesse caso tu pode usar o comando LIMIT
select * from @tab1 t
order by t.data desc
limit 2

Comment: Olá @Wagner Faria obrigado pela sua resposta, porém não funcionou sobre o ID e DATA coloquei assim apenas para simplificar o código e torná-lo mais didático até porque não é o foco.
Answer: Uma alternativa para esse tipo de caso é utilizar uma função de classificação (nesse caso a row_number):
with CTE_RN as
(
    select
        Id,
        CodCliente,
        Data,
        Valor,
        row_number() over(partition by Id order by Data desc) as RN
    from @tab1
)

select
    Id,
    CodCliente,
    Data,
    Valor
from CTE_RN
where
    RN = 1

Answer: O exemplo do @Motta funcionou adequadamente:
select * from @tab1 t1 where t1.Data = (select Max(t2Data) as Data from where t2.Id = t1.Id)

Comment: Mas atente ao que disse o @Wagner Faria ...


drupal bootstrap theme working with superfish

Question: I hope this will not be too confusing, apology if it is
My situation:

I used superfish so that I can have a navigation menu with dropdown submenu when the mouse hovering the nav items.
I used bootstrap theme to make the whole site responsive
I use 'main menu' instead of 'navigation' as my navigation menu bar
I customised the menu style by changing 'default.css' in superfish, bootstrap.css and style.css in bootstrap theme.
I have unchecked main menu in appearance tab under the theme setting so that the main menu will not show up twice while I'm using superfish.
I am using drupal 7, superfish-7.x-1.8 and bootstrap-7.x-2.x-dev

When the screen size is reduced, the menu bar disappears and the small button in the corner will show up. When clicking this button, the main menu items should be shown as a drop down menu. My problem is: because I unchecked the main menu, the main menu items will not show up when clicking this small button. But the superfish menu (which is main menu, but set in superfish menu) will be there without changing style for small screen. How can I make the superfish menu items behave the same way as normal main menu + bootstrap?
I really don't know how to explain this more clearly and I am really frustrated by bootstrap theme now :(
Any help would be very much appreciated!
thx
Comment: isn't it easier to just use the navigation menu provided by bootstrap instead of using superfish ?
Comment: Thank you Jayaram, but I am a little bit confused now, what is 'navigation menu provided by bootstrap' in Drupal? Do you mean the 'navigation' under 'Administration >  menu > Navigation'? How can I make it show submenus when mouse hovering the menu items then?
Comment: superfish does not use responsive css. I would suggest using [dropdowns](http://twitter.github.com/bootstrap/components.html#dropdowns) and [Navbar](http://twitter.github.com/bootstrap/components.html#navbar) or [Nav](http://twitter.github.com/bootstrap/components.html#navs) components from bootstrap to customize the menu styling instead of using superfish. did you do this already ?
Comment: Hi, how can I do this in drupal? do I just add the relevant html into page.tpl.php? Sorry if this is a silly question, I am quite new to drupal... Thanks
Answer: Superfish allows you to add custom css classes to the menu items. If you prefer to do it that way

you might want to first select the classes from bootstrap that you want to use to style your superfish menu items. Second add those classes correspondingly in the superfish menu block settings(click configure next to the block).
I also added a html wrapper under advanced HTML settings around the main UL element which is simply , (comma denotes the beginning and ending wrapping elements).
Let me know if that helps!
Comment: Hi Jayaram, sorry for later reply, i was interrupted by another project. This works for me! Thank you so much!
Answer: This is from the http://drupal.org/project/superfish webpage:

Important notes:
v1.9-beta5 is stable enough to be used on production sites. You can
  use it with the Superfish library v1.2-beta2. The latest development
  release (Feb 8) should be used if you're starting a new site that
  requires a responsive (or small-screen compatible) navigation. It
  requires the latest Superfish library (click the ZIP button in the
  Github or click this link). If you're upgrading you must add the path
  to sfsmallscreen.js plugin manually (which should be
  sites/all/libraries/superfish/sfsmallscreen.js) by going to Superfish
  module configuration page (admin/user-interface/superfish) and adding
  the full path at the end of the list of the library files.

Have you tried that? I would try 7.x-1.x-dev
Comment: thanks, but I am using superfish-7.x-1.8 as I said.
Comment: 7.x-1.8 is not 7.x-1.x-dev 7.x-1.8 was last updated 2011-Mar-27 and the dev was last updated 2013-Feb-08


Derive an atlas of Monge patches for a surface in 3D

Question:
Question: If I have an atlas of non-monge charts for a surface, how I can I derive an atlas of monge charts?

In differential geometry, a 'Monge patch' is a chart of the form $f(u,v) = (u, v, h(u,v))$. [2]
In simple terms, it's a parametric equation for a 3D surface patch described by only a height function.
This section from Solid Shape (Koenderink, MIT Press 1990 - p. 233) describes Monge patch representation of surfaces and motivates my interest in learning how to derive them.

The Monge patch representation lends itself particularly well for
  visualizations and for quick and dirty "back of the envelope"
  calculations. You should thoroughly familiarize yourself with it. In a
  local frame you can always use the Monge patch representation for a
  small neighborhood. Very often you can cover whole surfaces with just
  a few Monge patches.

An 'atlas' is a set of charts that cover a surface (a differentiable manifold) so what the author is saying is you can often produce an atlas for a surface where every chart is in Monge form.
Typically in the literature on differential geometry, charts for surfaces in $\mathbb{R}^3$ are not given in Monge form.

As a specific clarifying example here is a typical non-monge chart on a torus. [3]
\begin{align}
x &= c + a*\cos(v)*\cos(u)\\
y &= c + a*\cos(v)*\sin(u)\\
z &= c + a*\sin(v)
\end{align}
$$f(u,v) = (x,y,z)$$
How can I produce an atlas of Monge charts for the torus? That is, a list of parametric equations for surface patches that cover every part of a torus and are all in Monge form.
Specifically, I'd like to understand the process of working the problem in general for simple surfaces in $\mathbb{R}^3$, not just the list of equations for the torus.

Here is a visualization of one Monge chart for a torus and its domain. The parametric question for a surface patch like this is what I'm interested in. [4]

[2] http://mathworld.wolfram.com/MongePatch.html
[3] http://mathworld.wolfram.com/Torus.html
[4] http://faculty.cooper.edu/smyth/DifferentialGeometry/ch4/torusMonge.htm
Comment: You can use obvious trig identities to lead yourself to it. But remember that a surface of revolution has symmetry about (in your case) the $z$-axis, and this means that it's obtained by rotating a curve in the $yz$-plane ($g(y,z)=0$, say) about the $z$-axis. So you get $f(x,y,z)=0$ where $f(x,y,z)=g(?,z)$?
Comment: By the way, I think people are getting over-zealous with closing questions here. I voted to re-open. I didn't give a complete answer because you will learn more for thinking it through for yourself, but I realize that annoys some of the folks on MSE.
Comment: To get Monge patches you need a cartesian equation for the surface, since you need to be able to write it locally as a graph over the $xy$-, $yz$-, or $xz$-plane. So use your parametric equations to deduce the cartesian equation of the torus.
Comment: 'use your parametric equations to deduce the cartesian equation of the torus' is essentially what I'm asking how to do. Do you have any guidance there?

"cartesian equation" is a useful hint thank you!
Answer: Your torus is a function $f : (u,v) \rightarrow (x,y,z)$.
If you choose a xy-point $(a,b)$, you can make monge patch using the following: $(a,b,h(a,b))$.
To connect $f$ with the monge patch, you'll do: $(x=a, y=b, z=h(a,b))$.
To calculate $(u,v)$ out of chosen $(a,b)$, you can do inverse image of $f$:
  $$ f^{-1}((x=a,y=b,z=h(a,b))) : (x,y,z) \rightarrow (u,v)$$
$$ f^{-1}[B] = \{ x \in X | f(x) \in B \} $$
To calculate this inverse image, we need a function $g : (x,y,z) \rightarrow 2$, which can be given by:
$$ g(x,y,z) = ((x=a) \And (y=b)) $$
Once we have $g$ function, we can compose it with $f$ to get:
  $$ (g \circ f)(u,v) = g(f(u,v)) : (u,v) \rightarrow 2$$. The result we want comes from the equation:
 $$ (g \circ f)(u,v) = {true} $$. This allows us to calculate
$(u,v)$.
Now that we have $(u,v)$, we can use $f$ to obtain $(x,y,z)$.
Then from that, we get $z=h(a,b)$ as required.
excersize to the reader: try the pattern with the actual torus formulas.


Elvis operator with Run in kotlin

Question: Im having a bit of trouble with this situation
a?.let {
    b?.let { }
}?: run { }

The thing is, if "b" is null, the run block is executed, even though the elvis operator is referencing the "a" let.
I already tried to use "apply" instead of "run", same thing happens
Comment: i said "thats what i thought" before your edit, sorry
Comment: we need to see what happens in the `let`, because it all depends on that. Also, if `a` is null the `run block` will always execute and completely disregard `b`. Btw, if `a` is not null, and `b` is null, then the `let` will always return a null, thus executing the `run block`.
Comment: thats what i thought but:
https://i.imgur.com/tpC0abK.png
Comment: so how to prevent the b from calling the run block? will i have to use 'if else'?
Comment: you said that is what you thought, but look at my last sentence: `if a is not null, and b is null, then the let will always return a null, thus executing the run block`. It describes your run, a is not null and b is null, thus executing the run.
Comment: Yes, this is normal.  The solution is, in fact, to stop trying to use `?.let` magic and write more straightforward code with if and else.
Answer: The reason is that the let function returns whatever its last expression is. If the last expression evaluates to null (as b?.let would if b is null or the last line of that inner let evaluates to null), then the second part of the Elvis operator will be evaluated.
The solution is to never follow up a scope function call with an Elvis operator. It would work OK with also instead of let since it doesn't return the lambda result, but it's still obtuse-looking code that's hard to read. It's such an ugly pattern to use that people make memes about how ridiculous it is.
For this particular case, I would refactor your code as follows.
val a = a
if (a != null) {
    b?.let {
        //...
    }
} else {
    //...
}

Elvis operator with Run in kotlin


How to print the results of depth wise convolution in tensorflow?

Question: I am applying depth wise convolution. I want to access the first part of the 4 by 4 image and 2 by 2 filter between which convolution is taking place. Can someone please tell me how I can do that?
 `input = tf.Variable(tf.random_normal([1,4,4,2]))
 filter= tf.Variable(tf.random_normal([2,2,2,1]))
 def depth_conv2d(input):
     return tf.nn.depthwise_conv2d(input,filter, strides=[1,2,2,1],padding= 'SAME')
 depth_conv_out = depth_conv2d(input)
 sess = tf. InteractiveSession()
 sess.run(tf.initialize_all_variables())
 print input.eval()[0][:3][:3]`

Answer: Problem
you want the 4x4 of the first "color" of the image, and the 2x2 that will filter that first "color"
Solution
import tensorflow as tf

input  = tf.Variable(tf.random_normal([1,4,4,2]))
filter = tf.Variable(tf.random_normal([2,2,2,1]))
def depth_conv2d(input):
     return tf.nn.depthwise_conv2d(input,filter, strides=[1,2,2,1],padding= 'SAME')
depth_conv_out = depth_conv2d(input)
sess = tf.InteractiveSession()
sess.run(tf.initialize_all_variables())

print "The first part of the 4x4 image"
input_data = sess.run(input)
print input_data[:,:,:,0]
print "The first part of the 2x2 filter"
filter_data = sess.run(filter)
print filter_data[:,:,0,0]

Result
The first part of the 4x4 image
[[[ 0.17095199 -0.24415942 -0.15299758  0.00659828]
  [ 1.87758398  0.88201404  0.22255163 -0.52048266]
  [-0.20067528  0.98255271 -2.09791732 -0.43816876]
  [-0.37301171  0.6178537   2.05873895  1.97340238]]]
The 2x2 filter
[[-0.48764563  1.009269  ]
 [-0.82577544  0.75439191]]


Is it OK to use swiftUI in playground when submitting playground file for WWDC 2021 Scholarship?

Question: Is it OK to use SwiftUI in a playground when submitting the playground file for WWDC 2021 Scholarship?
So, Apple says they only accept the playground file, and it seems using SwiftUI makes me way easier to create a scene. But I'm not sure whether it is OK to do it, or will the tester grade me lower for using SwiftUI?
Answer: Yes. I used SwiftUI last year and am using it again this year.
Edit: I won this year, so I can say for sure that it's fine.
Comment: @SJLee btw you can see existing projects [here](https://github.com/wwdc/2020). Many of the accepted ones also used SwiftUI.